WazeWrapLib

WazeWrap library file

目前為 2025-04-11 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/532551/1569452/WazeWrapLib.js

  1. // ==UserScript==
  2. // @name WazeWrapLib
  3. // @namespace WazeDev
  4. // @version 2025.04.11.000
  5. // @description WazeWrap library file
  6. // @author MapOMatic, WazeDev group
  7. // @include /^https:\/\/(www|beta)\.waze\.com\/(?!user\/)(.{2,6}\/)?editor\/?.*$/
  8. // ==/UserScript==
  9.  
  10. /* global W */
  11. /* global WazeWrap */
  12. /* jshint esversion:6 */
  13. /* eslint-disable */
  14.  
  15. (function () {
  16. 'use strict';
  17. let wwSettings;
  18. let wEvents;
  19.  
  20. function bootstrap(tries = 1) {
  21. alert('test');
  22. if (!location.href.match(/^https:\/\/(www|beta)\.waze\.com\/(?!user\/)(.{2,6}\/)?editor\/?.*$/))
  23. return;
  24.  
  25. if (W && W.map &&
  26. W.model && W.loginManager.user &&
  27. $)
  28. init();
  29. else if (tries < 1000)
  30. setTimeout(function () { bootstrap(++tries); }, 200);
  31. else
  32. console.log('WazeWrap failed to load');
  33. }
  34.  
  35. bootstrap();
  36.  
  37. async function init() {
  38. console.log("WazeWrap initializing...");
  39. WazeWrap.Version = "2025.03.12.01";
  40. WazeWrap.isBetaEditor = /beta/.test(location.href);
  41. loadSettings();
  42. if(W.map.events)
  43. wEvents = W.map.events;
  44. else
  45. wEvents = W.map.getMapEventsListener();
  46.  
  47. //SetUpRequire();
  48. wEvents.register("moveend", this, RestoreMissingSegmentFunctions);
  49. wEvents.register("zoomend", this, RestoreMissingSegmentFunctions);
  50. wEvents.register("moveend", this, RestoreMissingNodeFunctions);
  51. wEvents.register("zoomend", this, RestoreMissingNodeFunctions);
  52. RestoreMissingSegmentFunctions();
  53. RestoreMissingNodeFunctions();
  54. RestoreMissingOLKMLSupport();
  55. RestoreMissingWRule();
  56.  
  57. WazeWrap.Geometry = new Geometry();
  58. WazeWrap.Model = new Model();
  59. WazeWrap.Interface = new Interface();
  60. WazeWrap.User = new User();
  61. WazeWrap.Util = new Util();
  62. WazeWrap.Require = new Require();
  63. WazeWrap.String = new String();
  64. WazeWrap.Events = new Events();
  65. WazeWrap.Alerts = new Alerts();
  66. WazeWrap.Remote = new Remote();
  67.  
  68. WazeWrap.getSelectedFeatures = function () {
  69. let arr = W.selectionManager.getSelectedFeatures();
  70. //inject functions for pulling information since WME backend is receiving frequent changes
  71. arr.forEach((item, index, array) => {
  72. array[index].WW = {};
  73. array[index].WW.getObjectModel = function(){ return item._wmeObject;};
  74. array[index].WW.getType = function(){return item?.WW?.getObjectModel().type;};
  75. array[index].WW.getAttributes = function(){return item?.WW?.getObjectModel().attributes;};
  76. });
  77. return arr;
  78. };
  79. WazeWrap.getSelectedDataModelObjects = function(){
  80. if(typeof W.selectionManager.getSelectedDataModelObjects === 'function')
  81. return W.selectionManager.getSelectedDataModelObjects();
  82. else
  83. return WazeWrap.getSelectedFeatures().map(e => e.WW.getObjectModel());
  84. };
  85.  
  86. WazeWrap.hasSelectedFeatures = function () {
  87. return W.selectionManager.hasSelectedFeatures();
  88. };
  89.  
  90. WazeWrap.selectFeature = function (feature) {
  91. if (!W.selectionManager.select)
  92. return W.selectionManager.selectFeature(feature);
  93.  
  94. return W.selectionManager.select(feature);
  95. };
  96.  
  97. WazeWrap.selectFeatures = function (featureArray) {
  98. if (!W.selectionManager.select)
  99. return W.selectionManager.selectFeatures(featureArray);
  100. return W.selectionManager.select(featureArray);
  101. };
  102.  
  103. WazeWrap.hasPlaceSelected = function () {
  104. return (W.selectionManager.hasSelectedFeatures() && WazeWrap.getSelectedFeatures()[0].WW.getType() === "venue");
  105. };
  106.  
  107. WazeWrap.hasSegmentSelected = function () {
  108. return (W.selectionManager.hasSelectedFeatures() && WazeWrap.getSelectedFeatures()[0].WW.getType() === "segment");
  109. };
  110.  
  111. WazeWrap.hasMapCommentSelected = function () {
  112. return (W.selectionManager.hasSelectedFeatures() && WazeWrap.getSelectedFeatures()[0].WW.getType() === "mapComment");
  113. };
  114.  
  115. initializeScriptUpdateInterface();
  116. await initializeToastr();
  117.  
  118. // 5/22/2019 (mapomatic)
  119. // Temporary workaround to get the address field on the place edit
  120. // panel to update when the place is updated. Can be removed if
  121. // staff fixes it on their end.
  122. try {
  123. W.model.venues.on('objectschanged', venues => {
  124. // Update venue address field display, if needed.
  125. try {
  126. const features = WazeWrap.getSelectedDataModelObjects();
  127. if (features.length === 1) {
  128. const venue = features[0];
  129. if (venues.includes(venue)) {
  130. $('#landmark-edit-general span.full-address').text(venue.getAddress().format());
  131. }
  132. }
  133. } catch (ex) {
  134. console.error('WazeWrap error:', ex);
  135. }
  136. });
  137. } catch (ex) {
  138. // ignore if this doesn't work.
  139. }
  140.  
  141. WazeWrap.Ready = true;
  142. initializeWWInterface();
  143.  
  144. console.log('WazeWrap Loaded');
  145. }
  146. function initializeWWInterface(){
  147. var $section = $("<div>", {style:"padding:8px 16px", id:"WMEPIESettings"});
  148. $section.html([
  149. '<h4 style="margin-bottom:0px;"><b>WazeWrap</b></h4>',
  150. `<h6 style="margin-top:0px;">${WazeWrap.Version}</h6>`,
  151. `<div id="divEditorPIN" class="controls-container">Editor PIN: <input type="${wwSettings.editorPIN != "" ? "password" : "text"}" size="10" id="wwEditorPIN" ${wwSettings.editorPIN != "" ? 'disabled' : ''}/>${wwSettings.editorPIN === "" ? '<button id="wwSetPin">Set PIN</button>' : ''}<i class="fa fa-eye fa-lg" style="display:${wwSettings.editorPIN === "" ? 'none' : 'inline-block'}" id="showWWEditorPIN" aria-hidden="true"></i></div><br/>`,
  152. `<div id="changePIN" class="controls-container" style="display:${wwSettings.editorPIN !== "" ? "block" : "none"}"><button id="wwChangePIN">Change PIN</button></div>`,
  153. '<div id="divShowAlertHistory" class="controls-container"><input type="checkbox" id="_cbShowAlertHistory" class="wwSettingsCheckbox" /><label for="_cbShowAlertHistory">Show alerts history</label></div>'
  154. ].join(' '));
  155. WazeWrap.Interface.Tab('WW', $section.html(), postInterfaceSetup, 'WazeWrap');
  156. }
  157. function postInterfaceSetup(){
  158. $('#wwEditorPIN')[0].value = wwSettings.editorPIN;
  159. setChecked('_cbShowAlertHistory', wwSettings.showAlertHistoryIcon);
  160. if(!wwSettings.showAlertHistoryIcon)
  161. $('.WWAlertsHistory').css('display', 'none');
  162. $('#showWWEditorPIN').mouseover(function(){
  163. $('#wwEditorPIN').attr('type', 'text');
  164. });
  165. $('#showWWEditorPIN').mouseleave(function(){
  166. $('#wwEditorPIN').attr('type', 'password');
  167. });
  168. $('#wwSetPin').click(function(){
  169. let pin = $('#wwEditorPIN')[0].value;
  170. if(pin != ""){
  171. wwSettings.editorPIN = pin;
  172. saveSettings();
  173. $('#showWWEditorPIN').css('display', 'inline-block');
  174. $('#wwEditorPIN').css('type', 'password');
  175. $('#wwEditorPIN').attr("disabled", true);
  176. $('#wwSetPin').css("display", 'none');
  177. $('#changePIN').css("display", 'block');
  178. }
  179. });
  180. $('#wwChangePIN').click(function(){
  181. WazeWrap.Alerts.prompt("WazeWrap", "This will <b>not</b> change the PIN stored with your settings, only the PIN that is stored on your machine to lookup/save your settings. \n\nChanging your PIN can result in a loss of your settings on the server and/or your local machine. Proceed only if you are sure you need to change this value. \n\n Enter your new PIN", '', function(e, inputVal){
  182. wwSettings.editorPIN = inputVal;
  183. $('#wwEditorPIN')[0].value = inputVal;
  184. saveSettings();
  185. });
  186. });
  187. $('#_cbShowAlertHistory').change(function(){
  188. if(this.checked)
  189. $('.WWAlertsHistory').css('display', 'block');
  190. else
  191. $('.WWAlertsHistory').css('display', 'none');
  192. wwSettings.showAlertHistoryIcon = this.checked;
  193. saveSettings();
  194. });
  195. }
  196. function setChecked(checkboxId, checked) {
  197. $('#' + checkboxId).prop('checked', checked);
  198. }
  199. function loadSettings() {
  200. wwSettings = $.parseJSON(localStorage.getItem("_wazewrap_settings"));
  201. let _defaultsettings = {
  202. showAlertHistoryIcon: true,
  203. editorPIN: ""
  204. };
  205. wwSettings = $.extend({}, _defaultsettings, wwSettings);
  206. }
  207. function saveSettings() {
  208. if (localStorage) {
  209. let settings = {
  210. showAlertHistoryIcon: wwSettings.showAlertHistoryIcon,
  211. editorPIN: wwSettings.editorPIN
  212. };
  213. localStorage.setItem("_wazewrap_settings", JSON.stringify(settings));
  214. }
  215. }
  216.  
  217. async function initializeToastr() {
  218. let toastrSettings = {};
  219. try {
  220. function loadSettings() {
  221. var loadedSettings = $.parseJSON(localStorage.getItem("WWToastr"));
  222. var defaultSettings = {
  223. historyLeftLoc: 35,
  224. historyTopLoc: 40
  225. };
  226. toastrSettings = $.extend({}, defaultSettings, loadedSettings)
  227. }
  228.  
  229. function saveSettings() {
  230. if (localStorage) {
  231. var localsettings = {
  232. historyLeftLoc: toastrSettings.historyLeftLoc,
  233. historyTopLoc: toastrSettings.historyTopLoc
  234. };
  235.  
  236. localStorage.setItem("WWToastr", JSON.stringify(localsettings));
  237. }
  238. }
  239. loadSettings();
  240. $('head').append(
  241. $('<link/>', {
  242. rel: 'stylesheet',
  243. type: 'text/css',
  244. href: 'https://cdn.statically.io/gh/WazeDev/toastr/master/build/toastr.min.css'
  245. }),
  246. $('<style type="text/css">.toast-container-wazedev > div {opacity: 0.95;} .toast-top-center-wide {top: 32px;}</style>')
  247. );
  248.  
  249. await $.getScript('https://cdn.statically.io/gh/WazeDev/toastr/master/build/toastr.min.js');
  250. wazedevtoastr.options = {
  251. target: '#map',
  252. timeOut: 6000,
  253. positionClass: 'toast-top-center-wide',
  254. closeOnHover: false,
  255. closeDuration: 0,
  256. showDuration: 0,
  257. closeButton: true,
  258. progressBar: true
  259. };
  260.  
  261. if ($('.WWAlertsHistory').length > 0)
  262. return;
  263. var $sectionToastr = $("<div>", { style: "padding:8px 16px", id: "wmeWWScriptUpdates" });
  264. $sectionToastr.html([
  265. '<div class="WWAlertsHistory" title="Script Alert History"><i class="fa fa-exclamation-triangle fa-lg"></i><div id="WWAlertsHistory-list"><div id="toast-container-history" class="toast-container-wazedev"></div></div></div>'
  266. ].join(' '));
  267. $("#WazeMap").append($sectionToastr.html());
  268.  
  269. $('.WWAlertsHistory').css('left', `${toastrSettings.historyLeftLoc}px`);
  270. $('.WWAlertsHistory').css('top', `${toastrSettings.historyTopLoc}px`);
  271.  
  272. try {
  273. await $.getScript("https://greasyfork.org/scripts/454988-jqueryui-custom-build/code/jQueryUI%20custom%20build.js");
  274. }
  275. catch (err) {
  276. console.log("Could not load jQuery UI " + err);
  277. }
  278.  
  279. if ($.ui) {
  280. $('.WWAlertsHistory').draggable({
  281. stop: function () {
  282. let windowWidth = $('#map').width();
  283. let panelWidth = $('#WWAlertsHistory-list').width();
  284. let historyLoc = $('.WWAlertsHistory').position().left;
  285. if ((panelWidth + historyLoc) > windowWidth) {
  286. $('#WWAlertsHistory-list').css('left', Math.abs(windowWidth - (historyLoc + $('.WWAlertsHistory').width()) - panelWidth) * -1);
  287. }
  288. else
  289. $('#WWAlertsHistory-list').css('left', 'auto');
  290.  
  291. toastrSettings.historyLeftLoc = $('.WWAlertsHistory').position().left;
  292. toastrSettings.historyTopLoc = $('.WWAlertsHistory').position().top;
  293. saveSettings();
  294. }
  295. });
  296. }
  297. }
  298. catch (err) {
  299. console.log(err);
  300. }
  301. }
  302.  
  303. function initializeScriptUpdateInterface() {
  304. console.log("creating script update interface");
  305. injectCSS();
  306. var $section = $("<div>", { style: "padding:8px 16px", id: "wmeWWScriptUpdates" });
  307. $section.html([
  308. '<div id="WWSU-Container" class="fa" style="position:fixed; top:20%; left:40%; z-index:1000; display:none;">',
  309. '<div id="WWSU-Close" class="fa-close fa-lg"></div>',
  310. '<div class="modal-heading">',
  311. '<h2>Script Updates</h2>',
  312. '<h4><span id="WWSU-updateCount">0</span> of your scripts have updates</h4>',
  313. '</div>',
  314. '<div class="WWSU-updates-wrapper">',
  315. '<div id="WWSU-script-list">',
  316. '</div>',
  317. '<div id="WWSU-script-update-info">',
  318. '</div></div></div>'
  319. ].join(' '));
  320. $("#WazeMap").append($section.html());
  321.  
  322. $('#WWSU-Close').click(function () {
  323. $('#WWSU-Container').hide();
  324. });
  325.  
  326. $(document).on('click', '.WWSU-script-item', function () {
  327. $('.WWSU-script-item').removeClass("WWSU-active");
  328. $(this).addClass("WWSU-active");
  329. });
  330. }
  331.  
  332. function injectCSS() {
  333. let css = [
  334. '#WWSU-Container { position:relative; background-color:#fbfbfb; width:650px; height:375px; border-radius:8px; padding:20px; box-shadow: 0 22px 84px 0 rgba(87, 99, 125, 0.5); border:1px solid #ededed; }',
  335. '#WWSU-Close { color:#000000; background-color:#ffffff; border:1px solid #ececec; border-radius:10px; height:25px; width:25px; position: absolute; right:14px; top:10px; cursor:pointer; padding: 5px 0px 0px 5px;}',
  336. '#WWSU-Container .modal-heading,.WWSU-updates-wrapper { font-family: "Helvetica Neue", Helvetica, "Open Sans", sans-serif; } ',
  337. '.WWSU-updates-wrapper { height:350px; }',
  338. '#WWSU-script-list { float:left; width:175px; height:100%; padding-right:6px; margin-right:10px; overflow-y: auto; overflow-x: hidden; height:300px; }',
  339. '.WWSU-script-item { text-decoration: none; min-height:40px; display:flex; text-align: center; justify-content: center; align-items: center; margin:3px 3px 10px 3px; background-color:white; border-radius:8px; box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 1px 0.25px; transition:all 200ms ease-in-out; cursor:pointer;}',
  340. '.WWSU-script-item:hover { text-decoration: none; }',
  341. '.WWSU-active { transform: translate3d(5px, 0px, 0px); box-shadow: rgba(0, 0, 0, 0.4) 0px 3px 7px 0px; }',
  342. '#WWSU-script-update-info { width:auto; background-color:white; height:275px; overflow-y:auto; border-radius:8px; box-shadow: rgba(0, 0, 0, 0.09) 0px 6px 7px 0.09px; padding:15px; position:relative;}',
  343. '#WWSU-script-update-info div { display: none;}',
  344. '#WWSU-script-update-info div:target { display: block; }',
  345. `.WWAlertsHistory {display:${wwSettings.showAlertHistoryIcon ? 'block' : 'none'}; width:32px; height:32px; background-color: #F89406; position: absolute; top:35px; left:40px; border-radius: 10px; border: 2px solid; box-size: border-box; z-index: 1050;}`,
  346. '.WWAlertsHistory:hover #WWAlertsHistory-list{display:block;}',
  347. '.WWAlertsHistory > .fa-exclamation-triangle {position: absolute; left:50%; margin-left:-9px; margin-top:8px;}',
  348. '#WWAlertsHistory-list{display:none; position:absolute; top:28px; border:2px solid black; border-radius:10px; background-color:white; padding:4px; overflow-y:auto; max-height: 300px;}',
  349. '#WWAlertsHistory-list #toast-container-history > div {max-width:500px; min-width:500px; border-radius:10px;}',
  350. '#WWAlertsHistory-list > #toast-container-history{ position:static; }'
  351. ].join(' ');
  352. $('<style type="text/css">' + css + '</style>').appendTo('head');
  353. }
  354. function RestoreMissingWRule(){
  355. if(!W.Rule){
  356. W.Rule = OpenLayers.Class(OpenLayers.Rule, {
  357. getContext(feature) {
  358. return feature;
  359. },
  360.  
  361. CLASS_NAME: "Waze.Rule"
  362. });
  363. }
  364. }
  365.  
  366. function RestoreMissingSegmentFunctions() {
  367. if (W.model.segments.getObjectArray().length > 0) {
  368. wEvents.unregister("moveend", this, RestoreMissingSegmentFunctions);
  369. wEvents.unregister("zoomend", this, RestoreMissingSegmentFunctions);
  370. if (typeof W.model.segments.getObjectArray()[0].model.getDirection == "undefined")
  371. W.model.segments.getObjectArray()[0].__proto__.getDirection = function () { return (this.attributes.fwdDirection ? 1 : 0) + (this.attributes.revDirection ? 2 : 0); };
  372. if (typeof W.model.segments.getObjectArray()[0].model.isTollRoad == "undefined")
  373. W.model.segments.getObjectArray()[0].__proto__.isTollRoad = function () { return (this.attributes.fwdToll || this.attributes.revToll); };
  374. if (typeof W.model.segments.getObjectArray()[0].isLockedByHigherRank == "undefined")
  375. W.model.segments.getObjectArray()[0].__proto__.isLockedByHigherRank = function () { return !(!this.attributes.lockRank || !this.model.loginManager.isLoggedIn()) && this.getLockRank() > this.model.loginManager.user.getRank(); };
  376. if (typeof W.model.segments.getObjectArray()[0].isDrivable == "undefined")
  377. W.model.segments.getObjectArray()[0].__proto__.isDrivable = function () { let V = [5, 10, 16, 18, 19]; return !V.includes(this.attributes.roadType); };
  378. if (typeof W.model.segments.getObjectArray()[0].isWalkingRoadType == "undefined")
  379. W.model.segments.getObjectArray()[0].__proto__.isWalkingRoadType = function () { let x = [5, 10, 16]; return x.includes(this.attributes.roadType); };
  380. if (typeof W.model.segments.getObjectArray()[0].isRoutable == "undefined")
  381. W.model.segments.getObjectArray()[0].__proto__.isRoutable = function () { let P = [1, 2, 7, 6, 3]; return P.includes(this.attributes.roadType); };
  382. if (typeof W.model.segments.getObjectArray()[0].isInBigJunction == "undefined")
  383. W.model.segments.getObjectArray()[0].__proto__.isInBigJunction = function () { return this.isBigJunctionShort() || this.hasFromBigJunction() || this.hasToBigJunction(); };
  384. if (typeof W.model.segments.getObjectArray()[0].isBigJunctionShort == "undefined")
  385. W.model.segments.getObjectArray()[0].__proto__.isBigJunctionShort = function () { return null != this.attributes.crossroadID; };
  386. if (typeof W.model.segments.getObjectArray()[0].hasFromBigJunction == "undefined")
  387. W.model.segments.getObjectArray()[0].__proto__.hasFromBigJunction = function (e) { return null != e ? this.attributes.fromCrossroads.includes(e) : this.attributes.fromCrossroads.length > 0; };
  388. if (typeof W.model.segments.getObjectArray()[0].hasToBigJunction == "undefined")
  389. W.model.segments.getObjectArray()[0].__proto__.hasToBigJunction = function (e) { return null != e ? this.attributes.toCrossroads.includes(e) : this.attributes.toCrossroads.length > 0; };
  390. if (typeof W.model.segments.getObjectArray()[0].getRoundabout == "undefined")
  391. W.model.segments.getObjectArray()[0].__proto__.getRoundabout = function () { return this.isInRoundabout() ? this.model.junctions.getObjectById(this.attributes.junctionID) : null; };
  392. }
  393. }
  394.  
  395. function RestoreMissingNodeFunctions() {
  396. if (W.model.nodes.getObjectArray().length > 0) {
  397. wEvents.unregister("moveend", this, RestoreMissingNodeFunctions);
  398. wEvents.unregister("zoomend", this, RestoreMissingNodeFunctions);
  399. if (typeof W.model.nodes.getObjectArray()[0].areConnectionsEditable == "undefined")
  400. W.model.nodes.getObjectArray()[0].__proto__.areConnectionsEditable = function () { var e = this.model.segments.getByIds(this.attributes.segIDs); return e.length === this.attributes.segIDs.length && e.every(function (e) { return e.canEditConnections(); }); };
  401. }
  402. }
  403. /* jshint ignore:start */
  404. function RestoreMissingOLKMLSupport() {
  405. if (!OpenLayers.Format.KML) {
  406. OpenLayers.Format.KML = OpenLayers.Class(OpenLayers.Format.XML, {
  407. namespaces: { kml: "http://www.opengis.net/kml/2.2", gx: "http://www.google.com/kml/ext/2.2" }, kmlns: "http://earth.google.com/kml/2.0", placemarksDesc: "No description available", foldersName: "OL export", foldersDesc: "Exported on " + new Date, extractAttributes: !0, kvpAttributes: !1, extractStyles: !1, extractTracks: !1, trackAttributes: null, internalns: null, features: null, styles: null, styleBaseUrl: "", fetched: null, maxDepth: 0, initialize: function (a) {
  408. this.regExes =
  409. { trimSpace: /^\s*|\s*$/g, removeSpace: /\s*/g, splitSpace: /\s+/, trimComma: /\s*,\s*/g, kmlColor: /(\w{2})(\w{2})(\w{2})(\w{2})/, kmlIconPalette: /root:\/\/icons\/palette-(\d+)(\.\w+)/, straightBracket: /\$\[(.*?)\]/g }; this.externalProjection = new OpenLayers.Projection("EPSG:4326"); OpenLayers.Format.XML.prototype.initialize.apply(this, [a])
  410. }, read: function (a) { this.features = []; this.styles = {}; this.fetched = {}; return this.parseData(a, { depth: 0, styleBaseUrl: this.styleBaseUrl }) }, parseData: function (a, b) {
  411. "string" == typeof a &&
  412. (a = OpenLayers.Format.XML.prototype.read.apply(this, [a])); for (var c = ["Link", "NetworkLink", "Style", "StyleMap", "Placemark"], d = 0, e = c.length; d < e; ++d) { var f = c[d], g = this.getElementsByTagNameNS(a, "*", f); if (0 != g.length) switch (f.toLowerCase()) { case "link": case "networklink": this.parseLinks(g, b); break; case "style": this.extractStyles && this.parseStyles(g, b); break; case "stylemap": this.extractStyles && this.parseStyleMaps(g, b); break; case "placemark": this.parseFeatures(g, b) } } return this.features
  413. }, parseLinks: function (a,
  414. b) { if (b.depth >= this.maxDepth) return !1; var c = OpenLayers.Util.extend({}, b); c.depth++; for (var d = 0, e = a.length; d < e; d++) { var f = this.parseProperty(a[d], "*", "href"); f && !this.fetched[f] && (this.fetched[f] = !0, (f = this.fetchLink(f)) && this.parseData(f, c)) } }, fetchLink: function (a) { if (a = OpenLayers.Request.GET({ url: a, async: !1 })) return a.responseText }, parseStyles: function (a, b) { for (var c = 0, d = a.length; c < d; c++) { var e = this.parseStyle(a[c]); e && (this.styles[(b.styleBaseUrl || "") + "#" + e.id] = e) } }, parseKmlColor: function (a) {
  415. var b =
  416. null; a && (a = a.match(this.regExes.kmlColor)) && (b = { color: "#" + a[4] + a[3] + a[2], opacity: parseInt(a[1], 16) / 255 }); return b
  417. }, parseStyle: function (a) {
  418. for (var b = {}, c = ["LineStyle", "PolyStyle", "IconStyle", "BalloonStyle", "LabelStyle"], d, e, f = 0, g = c.length; f < g; ++f)if (d = c[f], e = this.getElementsByTagNameNS(a, "*", d)[0]) switch (d.toLowerCase()) {
  419. case "linestyle": d = this.parseProperty(e, "*", "color"); if (d = this.parseKmlColor(d)) b.strokeColor = d.color, b.strokeOpacity = d.opacity; (d = this.parseProperty(e, "*", "width")) && (b.strokeWidth =
  420. d); break; case "polystyle": d = this.parseProperty(e, "*", "color"); if (d = this.parseKmlColor(d)) b.fillOpacity = d.opacity, b.fillColor = d.color; "0" == this.parseProperty(e, "*", "fill") && (b.fillColor = "none"); "0" == this.parseProperty(e, "*", "outline") && (b.strokeWidth = "0"); break; case "iconstyle": var h = parseFloat(this.parseProperty(e, "*", "scale") || 1); d = 32 * h; var i = 32 * h, j = this.getElementsByTagNameNS(e, "*", "Icon")[0]; if (j) {
  421. var k = this.parseProperty(j, "*", "href"); if (k) {
  422. var l = this.parseProperty(j, "*", "w"), m = this.parseProperty(j,
  423. "*", "h"); OpenLayers.String.startsWith(k, "http://maps.google.com/mapfiles/kml") && (!l && !m) && (m = l = 64, h /= 2); l = l || m; m = m || l; l && (d = parseInt(l) * h); m && (i = parseInt(m) * h); if (m = k.match(this.regExes.kmlIconPalette)) l = m[1], m = m[2], k = this.parseProperty(j, "*", "x"), j = this.parseProperty(j, "*", "y"), k = "http://maps.google.com/mapfiles/kml/pal" + l + "/icon" + (8 * (j ? 7 - j / 32 : 7) + (k ? k / 32 : 0)) + m; b.graphicOpacity = 1; b.externalGraphic = k
  424. }
  425. } if (e = this.getElementsByTagNameNS(e, "*", "hotSpot")[0]) k = parseFloat(e.getAttribute("x")), j = parseFloat(e.getAttribute("y")),
  426. l = e.getAttribute("xunits"), "pixels" == l ? b.graphicXOffset = -k * h : "insetPixels" == l ? b.graphicXOffset = -d + k * h : "fraction" == l && (b.graphicXOffset = -d * k), e = e.getAttribute("yunits"), "pixels" == e ? b.graphicYOffset = -i + j * h + 1 : "insetPixels" == e ? b.graphicYOffset = -(j * h) + 1 : "fraction" == e && (b.graphicYOffset = -i * (1 - j) + 1); b.graphicWidth = d; b.graphicHeight = i; break; case "balloonstyle": (e = OpenLayers.Util.getXmlNodeValue(e)) && (b.balloonStyle = e.replace(this.regExes.straightBracket, "${$1}")); break; case "labelstyle": if (d = this.parseProperty(e,
  427. "*", "color"), d = this.parseKmlColor(d)) b.fontColor = d.color, b.fontOpacity = d.opacity
  428. }!b.strokeColor && b.fillColor && (b.strokeColor = b.fillColor); if ((a = a.getAttribute("id")) && b) b.id = a; return b
  429. }, parseStyleMaps: function (a, b) {
  430. for (var c = 0, d = a.length; c < d; c++)for (var e = a[c], f = this.getElementsByTagNameNS(e, "*", "Pair"), e = e.getAttribute("id"), g = 0, h = f.length; g < h; g++) {
  431. var i = f[g], j = this.parseProperty(i, "*", "key"); (i = this.parseProperty(i, "*", "styleUrl")) && "normal" == j && (this.styles[(b.styleBaseUrl || "") + "#" + e] = this.styles[(b.styleBaseUrl ||
  432. "") + i])
  433. }
  434. }, parseFeatures: function (a, b) {
  435. for (var c = [], d = 0, e = a.length; d < e; d++) {
  436. var f = a[d], g = this.parseFeature.apply(this, [f]); if (g) {
  437. this.extractStyles && (g.attributes && g.attributes.styleUrl) && (g.style = this.getStyle(g.attributes.styleUrl, b)); if (this.extractStyles) { var h = this.getElementsByTagNameNS(f, "*", "Style")[0]; if (h && (h = this.parseStyle(h))) g.style = OpenLayers.Util.extend(g.style, h) } if (this.extractTracks) {
  438. if ((f = this.getElementsByTagNameNS(f, this.namespaces.gx, "Track")) && 0 < f.length) g = { features: [], feature: g },
  439. this.readNode(f[0], g), 0 < g.features.length && c.push.apply(c, g.features)
  440. } else c.push(g)
  441. } else throw "Bad Placemark: " + d;
  442. } this.features = this.features.concat(c)
  443. }, readers: {
  444. kml: { when: function (a, b) { b.whens.push(OpenLayers.Date.parse(this.getChildValue(a))) }, _trackPointAttribute: function (a, b) { var c = a.nodeName.split(":").pop(); b.attributes[c].push(this.getChildValue(a)) } }, gx: {
  445. Track: function (a, b) {
  446. var c = { whens: [], points: [], angles: [] }; if (this.trackAttributes) {
  447. var d; c.attributes = {}; for (var e = 0, f = this.trackAttributes.length; e <
  448. f; ++e)d = this.trackAttributes[e], c.attributes[d] = [], d in this.readers.kml || (this.readers.kml[d] = this.readers.kml._trackPointAttribute)
  449. } this.readChildNodes(a, c); if (c.whens.length !== c.points.length) throw Error("gx:Track with unequal number of when (" + c.whens.length + ") and gx:coord (" + c.points.length + ") elements."); var g = 0 < c.angles.length; if (g && c.whens.length !== c.angles.length) throw Error("gx:Track with unequal number of when (" + c.whens.length + ") and gx:angles (" + c.angles.length + ") elements."); for (var h,
  450. i, e = 0, f = c.whens.length; e < f; ++e) {
  451. h = b.feature.clone(); h.fid = b.feature.fid || b.feature.id; i = c.points[e]; h.geometry = i; "z" in i && (h.attributes.altitude = i.z); this.internalProjection && this.externalProjection && h.geometry.transform(this.externalProjection, this.internalProjection); if (this.trackAttributes) { i = 0; for (var j = this.trackAttributes.length; i < j; ++i)h.attributes[d] = c.attributes[this.trackAttributes[i]][e] } h.attributes.when = c.whens[e]; h.attributes.trackId = b.feature.id; g && (i = c.angles[e], h.attributes.heading =
  452. parseFloat(i[0]), h.attributes.tilt = parseFloat(i[1]), h.attributes.roll = parseFloat(i[2])); b.features.push(h)
  453. }
  454. }, coord: function (a, b) { var c = this.getChildValue(a).replace(this.regExes.trimSpace, "").split(/\s+/), d = new OpenLayers.Geometry.Point(c[0], c[1]); 2 < c.length && (d.z = parseFloat(c[2])); b.points.push(d) }, angles: function (a, b) { var c = this.getChildValue(a).replace(this.regExes.trimSpace, "").split(/\s+/); b.angles.push(c) }
  455. }
  456. }, parseFeature: function (a) {
  457. for (var b = ["MultiGeometry", "Polygon", "LineString", "Point"],
  458. c, d, e, f = 0, g = b.length; f < g; ++f)if (c = b[f], this.internalns = a.namespaceURI ? a.namespaceURI : this.kmlns, d = this.getElementsByTagNameNS(a, this.internalns, c), 0 < d.length) { if (b = this.parseGeometry[c.toLowerCase()]) e = b.apply(this, [d[0]]), this.internalProjection && this.externalProjection && e.transform(this.externalProjection, this.internalProjection); else throw new TypeError("Unsupported geometry type: " + c); break } var h; this.extractAttributes && (h = this.parseAttributes(a)); c = new OpenLayers.Feature.Vector(e, h); a = a.getAttribute("id") ||
  459. a.getAttribute("name"); null != a && (c.fid = a); return c
  460. }, getStyle: function (a, b) { var c = OpenLayers.Util.removeTail(a), d = OpenLayers.Util.extend({}, b); d.depth++; d.styleBaseUrl = c; !this.styles[a] && !OpenLayers.String.startsWith(a, "#") && d.depth <= this.maxDepth && !this.fetched[c] && (c = this.fetchLink(c)) && this.parseData(c, d); return OpenLayers.Util.extend({}, this.styles[a]) }, parseGeometry: {
  461. point: function (a) {
  462. var b = this.getElementsByTagNameNS(a, this.internalns, "coordinates"), a = []; if (0 < b.length) var c = b[0].firstChild.nodeValue,
  463. c = c.replace(this.regExes.removeSpace, ""), a = c.split(","); b = null; if (1 < a.length) 2 == a.length && (a[2] = null), b = new OpenLayers.Geometry.Point(a[0], a[1], a[2]); else throw "Bad coordinate string: " + c; return b
  464. }, linestring: function (a, b) {
  465. var c = this.getElementsByTagNameNS(a, this.internalns, "coordinates"), d = null; if (0 < c.length) {
  466. for (var c = this.getChildValue(c[0]), c = c.replace(this.regExes.trimSpace, ""), c = c.replace(this.regExes.trimComma, ","), d = c.split(this.regExes.splitSpace), e = d.length, f = Array(e), g, h, i = 0; i < e; ++i)if (g =
  467. d[i].split(","), h = g.length, 1 < h) 2 == g.length && (g[2] = null), f[i] = new OpenLayers.Geometry.Point(g[0], g[1], g[2]); else throw "Bad LineString point coordinates: " + d[i]; if (e) d = b ? new OpenLayers.Geometry.LinearRing(f) : new OpenLayers.Geometry.LineString(f); else throw "Bad LineString coordinates: " + c;
  468. } return d
  469. }, polygon: function (a) {
  470. var a = this.getElementsByTagNameNS(a, this.internalns, "LinearRing"), b = a.length, c = Array(b); if (0 < b) for (var d = 0, e = a.length; d < e; ++d)if (b = this.parseGeometry.linestring.apply(this, [a[d], !0])) c[d] =
  471. b; else throw "Bad LinearRing geometry: " + d; return new OpenLayers.Geometry.Polygon(c)
  472. }, multigeometry: function (a) { for (var b, c = [], d = a.childNodes, e = 0, f = d.length; e < f; ++e)a = d[e], 1 == a.nodeType && (b = this.parseGeometry[(a.prefix ? a.nodeName.split(":")[1] : a.nodeName).toLowerCase()]) && c.push(b.apply(this, [a])); return new OpenLayers.Geometry.Collection(c) }
  473. }, parseAttributes: function (a) {
  474. var b = {}, c = a.getElementsByTagName("ExtendedData"); c.length && (b = this.parseExtendedData(c[0])); for (var d, e, f, a = a.childNodes, c = 0, g =
  475. a.length; c < g; ++c)if (d = a[c], 1 == d.nodeType && (e = d.childNodes, 1 <= e.length && 3 >= e.length)) { switch (e.length) { case 1: f = e[0]; break; case 2: f = e[0]; e = e[1]; f = 3 == f.nodeType || 4 == f.nodeType ? f : e; break; default: f = e[1] }if (3 == f.nodeType || 4 == f.nodeType) if (d = d.prefix ? d.nodeName.split(":")[1] : d.nodeName, f = OpenLayers.Util.getXmlNodeValue(f)) f = f.replace(this.regExes.trimSpace, ""), b[d] = f } return b
  476. }, parseExtendedData: function (a) {
  477. var b = {}, c, d, e, f, g = a.getElementsByTagName("Data"); c = 0; for (d = g.length; c < d; c++) {
  478. e = g[c]; f = e.getAttribute("name");
  479. var h = {}, i = e.getElementsByTagName("value"); i.length && (h.value = this.getChildValue(i[0])); this.kvpAttributes ? b[f] = h.value : (e = e.getElementsByTagName("displayName"), e.length && (h.displayName = this.getChildValue(e[0])), b[f] = h)
  480. } a = a.getElementsByTagName("SimpleData"); c = 0; for (d = a.length; c < d; c++)h = {}, e = a[c], f = e.getAttribute("name"), h.value = this.getChildValue(e), this.kvpAttributes ? b[f] = h.value : (h.displayName = f, b[f] = h); return b
  481. }, parseProperty: function (a, b, c) {
  482. var d, a = this.getElementsByTagNameNS(a, b, c); try { d = OpenLayers.Util.getXmlNodeValue(a[0]) } catch (e) {
  483. d =
  484. null
  485. } return d
  486. }, write: function (a) { OpenLayers.Util.isArray(a) || (a = [a]); for (var b = this.createElementNS(this.kmlns, "kml"), c = this.createFolderXML(), d = 0, e = a.length; d < e; ++d)c.appendChild(this.createPlacemarkXML(a[d])); b.appendChild(c); return OpenLayers.Format.XML.prototype.write.apply(this, [b]) }, createFolderXML: function () {
  487. var a = this.createElementNS(this.kmlns, "Folder"); if (this.foldersName) { var b = this.createElementNS(this.kmlns, "name"), c = this.createTextNode(this.foldersName); b.appendChild(c); a.appendChild(b) } this.foldersDesc &&
  488. (b = this.createElementNS(this.kmlns, "description"), c = this.createTextNode(this.foldersDesc), b.appendChild(c), a.appendChild(b)); return a
  489. }, createPlacemarkXML: function (a) {
  490. var b = this.createElementNS(this.kmlns, "name"); b.appendChild(this.createTextNode(a.style && a.style.label ? a.style.label : a.attributes.name || a.id)); var c = this.createElementNS(this.kmlns, "description"); c.appendChild(this.createTextNode(a.attributes.description || this.placemarksDesc)); var d = this.createElementNS(this.kmlns, "Placemark"); null !=
  491. a.fid && d.setAttribute("id", a.fid); d.appendChild(b); d.appendChild(c); b = this.buildGeometryNode(a.geometry); d.appendChild(b); a.attributes && (a = this.buildExtendedData(a.attributes)) && d.appendChild(a); return d
  492. }, buildGeometryNode: function (a) { var b = a.CLASS_NAME, b = this.buildGeometry[b.substring(b.lastIndexOf(".") + 1).toLowerCase()], c = null; b && (c = b.apply(this, [a])); return c }, buildGeometry: {
  493. point: function (a) { var b = this.createElementNS(this.kmlns, "Point"); b.appendChild(this.buildCoordinatesNode(a)); return b }, multipoint: function (a) {
  494. return this.buildGeometry.collection.apply(this,
  495. [a])
  496. }, linestring: function (a) { var b = this.createElementNS(this.kmlns, "LineString"); b.appendChild(this.buildCoordinatesNode(a)); return b }, multilinestring: function (a) { return this.buildGeometry.collection.apply(this, [a]) }, linearring: function (a) { var b = this.createElementNS(this.kmlns, "LinearRing"); b.appendChild(this.buildCoordinatesNode(a)); return b }, polygon: function (a) {
  497. for (var b = this.createElementNS(this.kmlns, "Polygon"), a = a.components, c, d, e = 0, f = a.length; e < f; ++e)c = 0 == e ? "outerBoundaryIs" : "innerBoundaryIs",
  498. c = this.createElementNS(this.kmlns, c), d = this.buildGeometry.linearring.apply(this, [a[e]]), c.appendChild(d), b.appendChild(c); return b
  499. }, multipolygon: function (a) { return this.buildGeometry.collection.apply(this, [a]) }, collection: function (a) { for (var b = this.createElementNS(this.kmlns, "MultiGeometry"), c, d = 0, e = a.components.length; d < e; ++d)(c = this.buildGeometryNode.apply(this, [a.components[d]])) && b.appendChild(c); return b }
  500. }, buildCoordinatesNode: function (a) {
  501. var b = this.createElementNS(this.kmlns, "coordinates"),
  502. c; if (c = a.components) { for (var d = c.length, e = Array(d), f = 0; f < d; ++f)a = c[f], e[f] = this.buildCoordinates(a); c = e.join(" ") } else c = this.buildCoordinates(a); c = this.createTextNode(c); b.appendChild(c); return b
  503. }, buildCoordinates: function (a) { this.internalProjection && this.externalProjection && (a = a.clone(), a.transform(this.internalProjection, this.externalProjection)); return a.x + "," + a.y }, buildExtendedData: function (a) {
  504. var b = this.createElementNS(this.kmlns, "ExtendedData"), c; for (c in a) if (a[c] && "name" != c && "description" !=
  505. c && "styleUrl" != c) { var d = this.createElementNS(this.kmlns, "Data"); d.setAttribute("name", c); var e = this.createElementNS(this.kmlns, "value"); if ("object" == typeof a[c]) { if (a[c].value && e.appendChild(this.createTextNode(a[c].value)), a[c].displayName) { var f = this.createElementNS(this.kmlns, "displayName"); f.appendChild(this.getXMLDoc().createCDATASection(a[c].displayName)); d.appendChild(f) } } else e.appendChild(this.createTextNode(a[c])); d.appendChild(e); b.appendChild(d) } return this.isSimpleContent(b) ? null : b
  506. },
  507. CLASS_NAME: "OpenLayers.Format.KML"
  508. });
  509. }
  510. }
  511. /* jshint ignore:end */
  512. function Geometry() {
  513. //Converts to "normal" GPS coordinates
  514. this.ConvertTo4326 = function (lon, lat) {
  515. let projI = new OpenLayers.Projection("EPSG:900913");
  516. let projE = new OpenLayers.Projection("EPSG:4326");
  517. return (new OpenLayers.LonLat(lon, lat)).transform(projI, projE);
  518. };
  519.  
  520. this.ConvertTo900913 = function (lon, lat) {
  521. let projI = new OpenLayers.Projection("EPSG:900913");
  522. let projE = new OpenLayers.Projection("EPSG:4326");
  523. return (new OpenLayers.LonLat(lon, lat)).transform(projE, projI);
  524. };
  525.  
  526. //Converts the Longitudinal offset to an offset in 4326 gps coordinates
  527. this.CalculateLongOffsetGPS = function (longMetersOffset, lon, lat) {
  528. let R = 6378137; //Earth's radius
  529. let dLon = longMetersOffset / (R * Math.cos(Math.PI * lat / 180)); //offset in radians
  530. let lon0 = dLon * (180 / Math.PI); //offset degrees
  531.  
  532. return lon0;
  533. };
  534.  
  535. //Converts the Latitudinal offset to an offset in 4326 gps coordinates
  536. this.CalculateLatOffsetGPS = function (latMetersOffset, lat) {
  537. let R = 6378137; //Earth's radius
  538. let dLat = latMetersOffset / R;
  539. let lat0 = dLat * (180 / Math.PI); //offset degrees
  540.  
  541. return lat0;
  542. };
  543.  
  544. /**
  545. * Checks if the given lon & lat
  546. * @function WazeWrap.Geometry.isGeometryInMapExtent
  547. * @param {lon, lat} object
  548. */
  549. this.isLonLatInMapExtent = function (lonLat) {
  550. return lonLat && W.map.getExtent().containsLonLat(lonLat);
  551. };
  552.  
  553. /**
  554. * Checks if the given geometry point is on screen
  555. * @function WazeWrap.Geometry.isGeometryInMapExtent
  556. * @param {OpenLayers.Geometry.Point} Geometry Point we are checking if it is in the extent
  557. */
  558. this.isGeometryInMapExtent = function (geometry) {
  559. return geometry && geometry.getBounds &&
  560. W.map.getExtent().intersectsBounds(geometry.getBounds());
  561. };
  562.  
  563. /**
  564. * Calculates the distance between given points, returned in meters
  565. * @function WazeWrap.Geometry.calculateDistance
  566. * @param {OpenLayers.Geometry.Point} An array of OpenLayers.Geometry.Point with which to measure the total distance. A minimum of 2 points is needed.
  567. */
  568. this.calculateDistance = function (pointArray) {
  569. if (pointArray.length < 2)
  570. return 0;
  571.  
  572. let line = new OpenLayers.Geometry.LineString(pointArray);
  573. let length = line.getGeodesicLength(W.map.getProjectionObject());
  574. return length; //multiply by 3.28084 to convert to feet
  575. };
  576.  
  577. /**
  578. * Finds the closest on-screen drivable segment to the given point, ignoring PLR and PR segments if the options are set
  579. * @function WazeWrap.Geometry.findClosestSegment
  580. * @param {OpenLayers.Geometry.Point} The given point to find the closest segment to
  581. * @param {boolean} If true, Parking Lot Road segments will be ignored when finding the closest segment
  582. * @param {boolean} If true, Private Road segments will be ignored when finding the closest segment
  583. **/
  584. this.findClosestSegment = function (mygeometry, ignorePLR, ignoreUnnamedPR) {
  585. let onscreenSegments = WazeWrap.Model.getOnscreenSegments();
  586. let minDistance = Infinity;
  587. let closestSegment;
  588.  
  589. for (var s in onscreenSegments) {
  590. if (!onscreenSegments.hasOwnProperty(s))
  591. continue;
  592.  
  593. let segmentType = onscreenSegments[s].attributes.roadType;
  594. if (segmentType === 10 || segmentType === 16 || segmentType === 18 || segmentType === 19) //10 ped boardwalk, 16 stairway, 18 railroad, 19 runway, 3 freeway
  595. continue;
  596.  
  597. if (ignorePLR && segmentType === 20) //PLR
  598. continue;
  599.  
  600. if (ignoreUnnamedPR && segmentType === 17) {
  601. var nm = WazeWrap.Model.getStreetName(onscreenSegments[s].attributes.primaryStreetID);
  602. if (nm === null || nm == "") //PR
  603. continue;
  604. }
  605.  
  606. let distanceToSegment = mygeometry.distanceTo(onscreenSegments[s].getOLGeometry(), { details: true });
  607.  
  608. if (distanceToSegment.distance < minDistance) {
  609. minDistance = distanceToSegment.distance;
  610. closestSegment = onscreenSegments[s];
  611. closestSegment.closestPoint = new OpenLayers.Geometry.Point(distanceToSegment.x1, distanceToSegment.y1);
  612. }
  613. }
  614. return closestSegment;
  615. };
  616. }
  617.  
  618. function Model() {
  619.  
  620. this.getPrimaryStreetID = function (segmentID) {
  621. return W.model.segments.getObjectById(segmentID).attributes.primaryStreetID;
  622. };
  623.  
  624. this.getStreetName = function (primaryStreetID) {
  625. return W.model.streets.getObjectById(primaryStreetID).attributes.name;
  626. };
  627.  
  628. this.getCityID = function (primaryStreetID) {
  629. return W.model.streets.getObjectById(primaryStreetID).attributes.cityID;
  630. };
  631.  
  632. this.getCityName = function (primaryStreetID) {
  633. return W.model.cities.getObjectById(this.getCityID(primaryStreetID)).attributes.name;
  634. };
  635.  
  636. this.getStateName = function (primaryStreetID) {
  637. return W.model.states.getObjectById(this.getStateID(primaryStreetID)).attributes.name;
  638. };
  639.  
  640. this.getStateID = function (primaryStreetID) {
  641. return W.model.cities.getObjectById(this.getCityID(primaryStreetID)).attributes.stateID;
  642. };
  643.  
  644. this.getCountryID = function (primaryStreetID) {
  645. return W.model.cities.getObjectById(this.getCityID(primaryStreetID)).attributes.CountryID;
  646. };
  647.  
  648. this.getCountryName = function (primaryStreetID) {
  649. return W.model.countries.getObjectById(this.getCountryID(primaryStreetID)).attributes.name;
  650. };
  651.  
  652. this.getCityNameFromSegmentObj = function (segObj) {
  653. return this.getCityName(segObj.attributes.primaryStreetID);
  654. };
  655.  
  656. this.getStateNameFromSegmentObj = function (segObj) {
  657. return this.getStateName(segObj.attributes.primaryStreetID);
  658. };
  659. this.getObjectModel = function (obj){
  660. return obj?.attributes?.wazeFeature?._wmeObject;
  661. };
  662.  
  663. /**
  664. * Returns an array of segment IDs for all segments that make up the roundabout the given segment is part of
  665. * @function WazeWrap.Model.getAllRoundaboutSegmentsFromObj
  666. * @param {Segment object (Waze/Feature/Vector/Segment)} The roundabout segment
  667. **/
  668. this.getAllRoundaboutSegmentsFromObj = function (segObj) {
  669. let modelObj = {};
  670. if(typeof WazeWrap.getSelectedFeatures()[0].WW !== 'undefined')
  671. modelObj = segObj.WW.getObjectModel();
  672. else
  673. modelObj = segObj.attributes.wazeFeature._wmeObject;
  674. if (modelObj.attributes.junctionID === null)
  675. return null;
  676.  
  677. return W.model.junctions.objects[modelObj.attributes.junctionID].attributes.segIDs;
  678. };
  679.  
  680. /**
  681. * Returns an array of all junction nodes that make up the roundabout
  682. * @function WazeWrap.Model.getAllRoundaboutJunctionNodesFromObj
  683. * @param {Segment object (Waze/Feature/Vector/Segment)} The roundabout segment
  684. **/
  685. this.getAllRoundaboutJunctionNodesFromObj = function (segObj) {
  686. let RASegs = this.getAllRoundaboutSegmentsFromObj(segObj);
  687. let RAJunctionNodes = [];
  688. for (i = 0; i < RASegs.length; i++)
  689. RAJunctionNodes.push(W.model.nodes.objects[W.model.segments.getObjectById(RASegs[i]).attributes.toNodeID]);
  690.  
  691. return RAJunctionNodes;
  692. };
  693.  
  694. /**
  695. * Checks if the given segment ID is a part of a roundabout
  696. * @function WazeWrap.Model.isRoundaboutSegmentID
  697. * @param {integer} The segment ID to check
  698. **/
  699. this.isRoundaboutSegmentID = function (segmentID) {
  700. return W.model.segments.getObjectById(segmentID).attributes.junctionID !== null
  701. };
  702.  
  703. /**
  704. * Checks if the given segment object is a part of a roundabout
  705. * @function WazeWrap.Model.isRoundaboutSegmentID
  706. * @param {Segment object (Waze/Feature/Vector/Segment)} The segment object to check
  707. **/
  708. this.isRoundaboutSegmentObj = function (segObj) {
  709. let modelObj = {};
  710. if(typeof WazeWrap.getSelectedFeatures()[0].WW !== 'undefined')
  711. modelObj = segObj.WW.getObjectModel();
  712. else
  713. modelObj = segObj.attributes.wazeFeature._wmeObject;
  714. return modelObj.attributes.junctionID !== null;
  715. };
  716.  
  717. /**
  718. * Returns an array of all segments in the current extent
  719. * @function WazeWrap.Model.getOnscreenSegments
  720. **/
  721. this.getOnscreenSegments = function () {
  722. let segments = W.model.segments.objects;
  723. let mapExtent = W.map.getExtent();
  724. let onScreenSegments = [];
  725. let seg;
  726.  
  727. for (var s in segments) {
  728. if (!segments.hasOwnProperty(s))
  729. continue;
  730.  
  731. seg = W.model.segments.getObjectById(s);
  732. if (mapExtent.intersectsBounds(seg.getOLGeometry().getBounds()))
  733. onScreenSegments.push(seg);
  734. }
  735. return onScreenSegments;
  736. };
  737.  
  738. /**
  739. * Defers execution of a callback function until the WME map and data
  740. * model are ready. Call this function before calling a function that
  741. * causes a map and model reload, such as W.map.moveTo(). After the
  742. * move is completed the callback function will be executed.
  743. * @function WazeWrap.Model.onModelReady
  744. * @param {Function} callback The callback function to be executed.
  745. * @param {Boolean} now Whether or not to call the callback now if the
  746. * model is currently ready.
  747. * @param {Object} context The context in which to call the callback.
  748. */
  749. this.onModelReady = function (callback, now, context) {
  750. var deferModelReady = function () {
  751. return $.Deferred(function (dfd) {
  752. var resolve = function () {
  753. dfd.resolve();
  754. W.model.events.unregister('mergeend', null, resolve);
  755. };
  756. W.model.events.register('mergeend', null, resolve);
  757. }).promise();
  758. };
  759. var deferMapReady = function () {
  760. return $.Deferred(function (dfd) {
  761. var resolve = function () {
  762. dfd.resolve();
  763. W.app.layout.model.off('operationDone', resolve);
  764. };
  765. W.app.layout.model.on('operationDone', resolve);
  766. }).promise();
  767. };
  768.  
  769. if (typeof callback === 'function') {
  770. context = context || callback;
  771. if (now && WazeWrap.Util.mapReady() && WazeWrap.Util.modelReady()) {
  772. callback.call(context);
  773. } else {
  774. $.when(deferMapReady() && deferModelReady()).
  775. then(function () {
  776. callback.call(context);
  777. });
  778. }
  779. }
  780. };
  781.  
  782. /**
  783. * Retrives a route from the Waze Live Map.
  784. * @class
  785. * @name WazeWrap.Model.RouteSelection
  786. * @param firstSegment The segment to use as the start of the route.
  787. * @param lastSegment The segment to use as the destination for the route.
  788. * @param {Array|Function} callback A function or array of funcitons to be
  789. * executed after the route
  790. * is retrieved. 'This' in the callback functions will refer to the
  791. * RouteSelection object.
  792. * @param {Object} options A hash of options for determining route. Valid
  793. * options are:
  794. * fastest: {Boolean} Whether or not the fastest route should be used.
  795. * Default is false, which selects the shortest route.
  796. * freeways: {Boolean} Whether or not to avoid freeways. Default is false.
  797. * dirt: {Boolean} Whether or not to avoid dirt roads. Default is false.
  798. * longtrails: {Boolean} Whether or not to avoid long dirt roads. Default
  799. * is false.
  800. * uturns: {Boolean} Whether or not to allow U-turns. Default is true.
  801. * @return {WazeWrap.Model.RouteSelection} The new RouteSelection object.
  802. * @example: // The following example will retrieve a route from the Live Map and select the segments in the route.
  803. * selection = W.selectionManager.selectedItems;
  804. * myRoute = new WazeWrap.Model.RouteSelection(selection[0], selection[1], function(){this.selectRouteSegments();}, {fastest: true});
  805. */
  806. this.RouteSelection = function (firstSegment, lastSegment, callback, options) {
  807. var i,
  808. n,
  809. start = this.getSegmentCenterLonLat(firstSegment),
  810. end = this.getSegmentCenterLonLat(lastSegment);
  811. this.options = {
  812. fastest: options && options.fastest || false,
  813. freeways: options && options.freeways || false,
  814. dirt: options && options.dirt || false,
  815. longtrails: options && options.longtrails || false,
  816. uturns: options && options.uturns || true
  817. };
  818. this.requestData = {
  819. from: 'x:' + start.x + ' y:' + start.y + ' bd:true',
  820. to: 'x:' + end.x + ' y:' + end.y + ' bd:true',
  821. returnJSON: true,
  822. returnGeometries: true,
  823. returnInstructions: false,
  824. type: this.options.fastest ? 'HISTORIC_TIME' : 'DISTANCE',
  825. clientVersion: '4.0.0',
  826. timeout: 60000,
  827. nPaths: 3,
  828. options: this.setRequestOptions(this.options)
  829. };
  830. this.callbacks = [];
  831. if (callback) {
  832. if (!(callback instanceof Array)) {
  833. callback = [callback];
  834. }
  835. for (i = 0, n = callback.length; i < n; i++) {
  836. if ('function' === typeof callback[i]) {
  837. this.callbacks.push(callback[i]);
  838. }
  839. }
  840. }
  841. this.routeData = null;
  842. this.getRouteData();
  843. };
  844.  
  845. this.RouteSelection.prototype =
  846. /** @lends WazeWrap.Model.RouteSelection.prototype */ {
  847.  
  848. /**
  849. * Formats the routing options string for the ajax request.
  850. * @private
  851. * @param {Object} options Object containing the routing options.
  852. * @return {String} String containing routing options.
  853. */
  854. setRequestOptions: function (options) {
  855. return 'AVOID_TOLL_ROADS:' + (options.tolls ? 't' : 'f') + ',' +
  856. 'AVOID_PRIMARIES:' + (options.freeways ? 't' : 'f') + ',' +
  857. 'AVOID_TRAILS:' + (options.dirt ? 't' : 'f') + ',' +
  858. 'AVOID_LONG_TRAILS:' + (options.longtrails ? 't' : 'f') + ',' +
  859. 'ALLOW_UTURNS:' + (options.uturns ? 't' : 'f');
  860. },
  861.  
  862. /**
  863. * Gets the center of a segment in LonLat form.
  864. * @private
  865. * @param segment A Waze model segment object.
  866. * @return {OpenLayers.LonLat} The LonLat object corresponding to the
  867. * center of the segment.
  868. */
  869. getSegmentCenterLonLat: function (segment) {
  870. var x, y, componentsLength, midPoint;
  871. if (segment) {
  872. componentsLength = segment.getOLGeometry().components.length;
  873. midPoint = Math.floor(componentsLength / 2);
  874. if (componentsLength % 2 === 1) {
  875. x = segment.getOLGeometry().components[midPoint].x;
  876. y = segment.getOLGeometry().components[midPoint].y;
  877. } else {
  878. x = (segment.getOLGeometry().components[midPoint - 1].x +
  879. segment.getOLGeometry().components[midPoint].x) / 2;
  880. y = (segment.getOLGeometry().components[midPoint - 1].y +
  881. segment.getOLGeometry().components[midPoint].y) / 2;
  882. }
  883. return new OpenLayers.Geometry.Point(x, y).
  884. transform(W.map.getProjectionObject(), 'EPSG:4326');
  885. }
  886.  
  887. },
  888.  
  889. /**
  890. * Gets the route from Live Map and executes any callbacks upon success.
  891. * @private
  892. * @returns The ajax request object. The responseJSON property of the
  893. * returned object
  894. * contains the route information.
  895. *
  896. */
  897. getRouteData: function () {
  898. var i,
  899. n,
  900. that = this;
  901. return $.ajax({
  902. dataType: 'json',
  903. url: this.getURL(),
  904. data: this.requestData,
  905. dataFilter: function (data, dataType) {
  906. return data.replace(/NaN/g, '0');
  907. },
  908. success: function (data) {
  909. that.routeData = data;
  910. for (i = 0, n = that.callbacks.length; i < n; i++) {
  911. that.callbacks[i].call(that);
  912. }
  913. }
  914. });
  915. },
  916.  
  917. /**
  918. * Extracts the IDs from all segments on the route.
  919. * @private
  920. * @return {Array} Array containing an array of segment IDs for
  921. * each route alternative.
  922. */
  923. getRouteSegmentIDs: function () {
  924. var i, j, route, len1, len2, segIDs = [],
  925. routeArray = [],
  926. data = this.routeData;
  927. if ('undefined' !== typeof data.alternatives) {
  928. for (i = 0, len1 = data.alternatives.length; i < len1; i++) {
  929. route = data.alternatives[i].response.results;
  930. for (j = 0, len2 = route.length; j < len2; j++) {
  931. routeArray.push(route[j].path.segmentId);
  932. }
  933. segIDs.push(routeArray);
  934. routeArray = [];
  935. }
  936. } else {
  937. route = data.response.results;
  938. for (i = 0, len1 = route.length; i < len1; i++) {
  939. routeArray.push(route[i].path.segmentId);
  940. }
  941. segIDs.push(routeArray);
  942. }
  943. return segIDs;
  944. },
  945.  
  946. /**
  947. * Gets the URL to use for the ajax request based on country.
  948. * @private
  949. * @return {String} Relative URl to use for route ajax request.
  950. */
  951. getURL: function () {
  952. if (W.model.countries.getObjectById(235) || W.model.countries.getObjectById(40)) {
  953. return '/RoutingManager/routingRequest';
  954. } else if (W.model.countries.getObjectById(106)) {
  955. return '/il-RoutingManager/routingRequest';
  956. } else {
  957. return '/row-RoutingManager/routingRequest';
  958. }
  959. },
  960.  
  961. /**
  962. * Selects all segments on the route in the editor.
  963. * @param {Integer} routeIndex The index of the alternate route.
  964. * Default route to use is the first one, which is 0.
  965. */
  966. selectRouteSegments: function (routeIndex) {
  967. var i, n, seg,
  968. segIDs = this.getRouteSegmentIDs()[Math.floor(routeIndex) || 0],
  969. segments = [];
  970. if ('undefined' === typeof segIDs) {
  971. return;
  972. }
  973. for (i = 0, n = segIDs.length; i < n; i++) {
  974. seg = W.model.segments.getObjectById(segIDs[i]);
  975. if ('undefined' !== seg) {
  976. segments.push(seg);
  977. }
  978. }
  979. return WazeWrap.selectFeatures(segments);
  980. }
  981. };
  982. }
  983.  
  984. function User() {
  985. /**
  986. * Returns the "normalized" (1 based) user rank/level
  987. */
  988. this.Rank = function () {
  989. return W.loginManager.user.getRank() + 1;
  990. };
  991.  
  992. /**
  993. * Returns the current user's username
  994. */
  995. this.Username = function () {
  996. return W.loginManager.user.getUsername();
  997. };
  998.  
  999. /**
  1000. * Returns if the user is a CM (in any country)
  1001. */
  1002. this.isCM = function () {
  1003. // Temporary fix for WME change. Going forward, the property will be under attributes.
  1004. if (W.loginManager.user.editableCountryIDs) {
  1005. return W.loginManager.user.editableCountryIDs.length > 0;
  1006. }
  1007. return W.loginManager.user.attributes.editableCountryIDs.length > 0
  1008. };
  1009.  
  1010. /**
  1011. * Returns if the user is an Area Manager (in any country)
  1012. */
  1013. this.isAM = function () {
  1014. // Temporary fix for WME change. Going forward, the property will be under attributes.
  1015. return W.loginManager.user.isAreaManager || W.loginManager.user.attributes.isAreaManager;
  1016. };
  1017. }
  1018.  
  1019. function Require() {
  1020. this.DragElement = function () {
  1021. var myDragElement = OpenLayers.Class({
  1022. started: !1,
  1023. stopDown: !0,
  1024. dragging: !1,
  1025. touch: !1,
  1026. last: null,
  1027. start: null,
  1028. lastMoveEvt: null,
  1029. oldOnselectstart: null,
  1030. interval: 0,
  1031. timeoutId: null,
  1032. forced: !1,
  1033. active: !1,
  1034. viewPortDiv: null,
  1035. initialize: function (e) {
  1036. this.map = e,
  1037. this.uniqueID = myDragElement.baseID--;
  1038. this.viewPortDiv = W.map.getViewport();
  1039. },
  1040. callback: function (e, t) {
  1041. if (this[e])
  1042. return this[e].apply(this, t)
  1043. },
  1044. dragstart: function (e) {
  1045. e.xy = new OpenLayers.Pixel(e.clientX - this.viewPortDiv.offsets[0], e.clientY - this.viewPortDiv.offsets[1]);
  1046. var t = !0;
  1047. return this.dragging = !1,
  1048. (OpenLayers.Event.isLeftClick(e) || OpenLayers.Event.isSingleTouch(e)) && (this.started = !0,
  1049. this.start = e.xy,
  1050. this.last = e.xy,
  1051. OpenLayers.Element.addClass(this.viewPortDiv, "olDragDown"),
  1052. this.down(e),
  1053. this.callback("down", [e.xy]),
  1054. OpenLayers.Event.stop(e),
  1055. this.oldOnselectstart || (this.oldOnselectstart = document.onselectstart ? document.onselectstart : OpenLayers.Function.True),
  1056. document.onselectstart = OpenLayers.Function.False,
  1057. t = !this.stopDown),
  1058. t
  1059. },
  1060. forceStart: function () {
  1061. var e = arguments.length > 0 && void 0 !== arguments[0] && arguments[0];
  1062. return this.started = !0,
  1063. this.endOnMouseUp = e,
  1064. this.forced = !0,
  1065. this.last = {
  1066. x: 0,
  1067. y: 0
  1068. },
  1069. this.callback("force")
  1070. },
  1071. forceEnd: function () {
  1072. if (this.forced)
  1073. return this.endDrag()
  1074. },
  1075. dragmove: function (e) {
  1076. return this.viewPortDiv.offsets && (e.xy = new OpenLayers.Pixel(e.clientX - this.viewPortDiv.offsets[0], e.clientY - this.viewPortDiv.offsets[1])),
  1077. this.lastMoveEvt = e,
  1078. !this.started || this.timeoutId || e.xy.x === this.last.x && e.xy.y === this.last.y || (this.interval > 0 && (this.timeoutId = window.setTimeout(OpenLayers.Function.bind(this.removeTimeout, this), this.interval)),
  1079. this.dragging = !0,
  1080. this.move(e),
  1081. this.oldOnselectstart || (this.oldOnselectstart = document.onselectstart,
  1082. document.onselectstart = OpenLayers.Function.False),
  1083. this.last = e.xy),
  1084. !0
  1085. },
  1086. dragend: function (e) {
  1087. if (e.xy = new OpenLayers.Pixel(e.clientX - this.viewPortDiv.offsets[0], e.clientY - this.viewPortDiv.offsets[1]),
  1088. this.started) {
  1089. var t = this.start !== this.last;
  1090. this.endDrag(),
  1091. this.up(e),
  1092. this.callback("up", [e.xy]),
  1093. t && this.callback("done", [e.xy])
  1094. }
  1095. return !0
  1096. },
  1097. endDrag: function () {
  1098. this.started = !1,
  1099. this.dragging = !1,
  1100. this.forced = !1,
  1101. OpenLayers.Element.removeClass(this.viewPortDiv, "olDragDown"),
  1102. document.onselectstart = this.oldOnselectstart
  1103. },
  1104. down: function (e) { },
  1105. move: function (e) { },
  1106. up: function (e) { },
  1107. out: function (e) { },
  1108. mousedown: function (e) {
  1109. return this.dragstart(e)
  1110. },
  1111. touchstart: function (e) {
  1112. return this.touch || (this.touch = !0,
  1113. this.map.events.un({
  1114. mousedown: this.mousedown,
  1115. mouseup: this.mouseup,
  1116. mousemove: this.mousemove,
  1117. click: this.click,
  1118. scope: this
  1119. })),
  1120. this.dragstart(e)
  1121. },
  1122. mousemove: function (e) {
  1123. return this.dragmove(e)
  1124. },
  1125. touchmove: function (e) {
  1126. return this.dragmove(e)
  1127. },
  1128. removeTimeout: function () {
  1129. if (this.timeoutId = null,
  1130. this.dragging)
  1131. return this.mousemove(this.lastMoveEvt)
  1132. },
  1133. mouseup: function (e) {
  1134. if (!this.forced || this.endOnMouseUp)
  1135. return this.started ? this.dragend(e) : void 0
  1136. },
  1137. touchend: function (e) {
  1138. if (e.xy = this.last,
  1139. !this.forced)
  1140. return this.dragend(e)
  1141. },
  1142. click: function (e) {
  1143. return this.start === this.last
  1144. },
  1145. activate: function (e) {
  1146. this.$el = e,
  1147. this.active = !0;
  1148. var t = $(this.viewPortDiv);
  1149. return this.$el.on("mousedown.drag-" + this.uniqueID, $.proxy(this.mousedown, this)),
  1150. this.$el.on("touchstart.drag-" + this.uniqueID, $.proxy(this.touchstart, this)),
  1151. t.on("mouseup.drag-" + this.uniqueID, $.proxy(this.mouseup, this)),
  1152. t.on("mousemove.drag-" + this.uniqueID, $.proxy(this.mousemove, this)),
  1153. t.on("touchmove.drag-" + this.uniqueID, $.proxy(this.touchmove, this)),
  1154. t.on("touchend.drag-" + this.uniqueID, $.proxy(this.touchend, this))
  1155. },
  1156. deactivate: function () {
  1157. return this.active = !1,
  1158. this.$el.off(".drag-" + this.uniqueID),
  1159. $(this.viewPortDiv).off(".drag-" + this.uniqueID),
  1160. this.touch = !1,
  1161. this.started = !1,
  1162. this.forced = !1,
  1163. this.dragging = !1,
  1164. this.start = null,
  1165. this.last = null,
  1166. OpenLayers.Element.removeClass(this.viewPortDiv, "olDragDown")
  1167. },
  1168. adjustXY: function (e) {
  1169. var t = OpenLayers.Util.pagePosition(this.viewPortDiv);
  1170. return e.xy.x -= t[0],
  1171. e.xy.y -= t[1]
  1172. },
  1173. CLASS_NAME: "W.Handler.DragElement"
  1174. });
  1175. myDragElement.baseID = 0;
  1176. return myDragElement;
  1177. };
  1178.  
  1179. this.DivIcon = OpenLayers.Class({
  1180. className: null,
  1181. $div: null,
  1182. events: null,
  1183. initialize: function (e, t) {
  1184. this.className = e,
  1185. this.moveWithTransform = !!t,
  1186. this.$div = $("<div />").addClass(e),
  1187. this.div = this.$div.get(0),
  1188. this.imageDiv = this.$div.get(0);
  1189. },
  1190. destroy: function () {
  1191. this.erase(),
  1192. this.$div = null;
  1193. },
  1194. clone: function () {
  1195. return new i(this.className);
  1196. },
  1197. draw: function (e) {
  1198. return this.moveWithTransform ? (this.$div.css({
  1199. transform: "translate(" + e.x + "px, " + e.y + "px)"
  1200. }),
  1201. this.$div.css({
  1202. position: "absolute"
  1203. })) : this.$div.css({
  1204. position: "absolute",
  1205. left: e.x,
  1206. top: e.y
  1207. }),
  1208. this.$div.get(0);
  1209. },
  1210. moveTo: function (e) {
  1211. null !== e && (this.px = e),
  1212. null === this.px ? this.display(!1) : this.moveWithTransform ? this.$div.css({
  1213. transform: "translate(" + this.px.x + "px, " + this.px.y + "px)"
  1214. }) : this.$div.css({
  1215. left: this.px.x,
  1216. top: this.px.y
  1217. });
  1218. },
  1219. erase: function () {
  1220. this.$div.remove();
  1221. },
  1222. display: function (e) {
  1223. this.$div.toggle(e);
  1224. },
  1225. isDrawn: function () {
  1226. return !!this.$div.parent().length;
  1227. },
  1228. bringToFront: function () {
  1229. if (this.isDrawn()) {
  1230. var e = this.$div.parent();
  1231. this.$div.detach().appendTo(e);
  1232. }
  1233. },
  1234. forceReflow: function () {
  1235. return this.$div.get(0).offsetWidth;
  1236. },
  1237. CLASS_NAME: "W.DivIcon"
  1238. });
  1239. this.Icon = OpenLayers.Class({
  1240. url: null,
  1241. size: null,
  1242. offset: null,
  1243. calculateOffset: null,
  1244. imageDiv: null,
  1245. px: null,
  1246. initialize: function(a,b,c,d){
  1247. this.url=a;
  1248. this.size=b||{w: 20,h: 20};
  1249. this.offset=c||{x: -(this.size.w/2),y: -(this.size.h/2)};
  1250. this.calculateOffset=d;
  1251. a = OpenLayers.Util.createUniqueID("OL_Icon_");
  1252. var div = this.imageDiv = OpenLayers.Util.createAlphaImageDiv(a);
  1253. $(div.firstChild).removeClass('olAlphaImg'); // LEAVE THIS LINE TO PREVENT WME-HARDHATS SCRIPT FROM TURNING ALL ICONS INTO HARDHAT WAZERS --MAPOMATIC
  1254. },
  1255. destroy: function(){ this.erase();OpenLayers.Event.stopObservingElement(this.imageDiv.firstChild);this.imageDiv.innerHTML="";this.imageDiv=null; },
  1256. clone: function(){ return new OpenLayers.Icon(this.url,this.size,this.offset,this.calculateOffset); },
  1257. setSize: function(a){ null!==a&&(this.size=a); this.draw(); },
  1258. setUrl: function(a){ null!==a&&(this.url=a); this.draw(); },
  1259. draw: function(a){
  1260. OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,null,this.size,this.url,"absolute");
  1261. this.moveTo(a);
  1262. return this.imageDiv;
  1263. },
  1264. erase: function(){ null!==this.imageDiv&&null!==this.imageDiv.parentNode && OpenLayers.Element.remove(this.imageDiv); },
  1265. setOpacity: function(a){ OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,null,null,null,null,null,null,a); },
  1266. moveTo: function(a){
  1267. null!==a&&(this.px=a);
  1268. null!==this.imageDiv&&(null===this.px?this.display(!1): (
  1269. this.calculateOffset&&(this.offset=this.calculateOffset(this.size)),
  1270. OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,{x: this.px.x+this.offset.x,y: this.px.y+this.offset.y})
  1271. ));
  1272. },
  1273. display: function(a){ this.imageDiv.style.display=a?"": "none"; },
  1274. isDrawn: function(){ return this.imageDiv&&this.imageDiv.parentNode&&11!=this.imageDiv.parentNode.nodeType; },
  1275. CLASS_NAME: "OpenLayers.Icon"
  1276. });
  1277.  
  1278. }
  1279.  
  1280. function Util() {
  1281. /**
  1282. * Function to defer function execution until an element is present on
  1283. * the page.
  1284. * @function WazeWrap.Util.waitForElement
  1285. * @param {String} selector The CSS selector string or a jQuery object
  1286. * to find before executing the callback.
  1287. * @param {Function} callback The function to call when the page
  1288. * element is detected.
  1289. * @param {Object} [context] The context in which to call the callback.
  1290. */
  1291. this.waitForElement = function (selector, callback, context) {
  1292. let jqObj;
  1293. if (!selector || typeof callback !== 'function')
  1294. return;
  1295.  
  1296. jqObj = typeof selector === 'string' ?
  1297. $(selector) : selector instanceof $ ? selector : null;
  1298.  
  1299. if (!jqObj.length) {
  1300. window.requestAnimationFrame(function () {
  1301. WazeWrap.Util.waitForElement(selector, callback, context);
  1302. });
  1303. } else
  1304. callback.call(context || callback);
  1305. };
  1306.  
  1307. /**
  1308. * Function to track the ready state of the map.
  1309. * @function WazeWrap.Util.mapReady
  1310. * @return {Boolean} Whether or not a map operation is pending or
  1311. * undefined if the function has not yet seen a map ready event fired.
  1312. */
  1313. this.mapReady = function () {
  1314. var mapReady = true;
  1315. W.app.layout.model.on('operationPending', function () {
  1316. mapReady = false;
  1317. });
  1318. W.app.layout.model.on('operationDone', function () {
  1319. mapReady = true;
  1320. });
  1321.  
  1322. return function () {
  1323. return mapReady;
  1324. };
  1325. }();
  1326.  
  1327. /**
  1328. * Function to track the ready state of the model.
  1329. * @function WazeWrap.Util.modelReady
  1330. * @return {Boolean} Whether or not the model has loaded objects or
  1331. * undefined if the function has not yet seen a model ready event fired.
  1332. */
  1333. this.modelReady = function () {
  1334. var modelReady = true;
  1335. W.model.events.register('mergestart', null, function () {
  1336. modelReady = false;
  1337. });
  1338. W.model.events.register('mergeend', null, function () {
  1339. modelReady = true;
  1340. });
  1341. return function () {
  1342. return modelReady;
  1343. };
  1344. }();
  1345.  
  1346. /**
  1347. * Returns orthogonalized geometry for the given geometry and threshold
  1348. * @function WazeWrap.Util.OrthogonalizeGeometry
  1349. * @param {OpenLayers.Geometry} The OpenLayers.Geometry to orthogonalize
  1350. * @param {integer} threshold to use for orthogonalization - the higher the threshold, the more nodes that will be removed
  1351. * @return {OpenLayers.Geometry } Orthogonalized geometry
  1352. **/
  1353. this.OrthogonalizeGeometry = function (geometry, threshold = 12) {
  1354. let nomthreshold = threshold, // degrees within right or straight to alter
  1355. lowerThreshold = Math.cos((90 - nomthreshold) * Math.PI / 180),
  1356. upperThreshold = Math.cos(nomthreshold * Math.PI / 180);
  1357.  
  1358. function Orthogonalize() {
  1359. var nodes = geometry,
  1360. points = nodes.slice(0, -1).map(function (n) {
  1361. let p = n.clone().transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
  1362. p.y = lat2latp(p.y);
  1363. return p;
  1364. }),
  1365. corner = { i: 0, dotp: 1 },
  1366. epsilon = 1e-4,
  1367. i, j, score, motions;
  1368.  
  1369. // Triangle
  1370. if (nodes.length === 4) {
  1371. for (i = 0; i < 1000; i++) {
  1372. motions = points.map(calcMotion);
  1373.  
  1374. var tmp = addPoints(points[corner.i], motions[corner.i]);
  1375. points[corner.i].x = tmp.x;
  1376. points[corner.i].y = tmp.y;
  1377.  
  1378. score = corner.dotp;
  1379. if (score < epsilon)
  1380. break;
  1381. }
  1382.  
  1383. var n = points[corner.i];
  1384. n.y = latp2lat(n.y);
  1385. let pp = n.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
  1386.  
  1387. let id = nodes[corner.i].id;
  1388. for (i = 0; i < nodes.length; i++) {
  1389. if (nodes[i].id != id)
  1390. continue;
  1391.  
  1392. nodes[i].x = pp.x;
  1393. nodes[i].y = pp.y;
  1394. }
  1395.  
  1396. return nodes;
  1397. } else {
  1398. var best,
  1399. originalPoints = nodes.slice(0, -1).map(function (n) {
  1400. let p = n.clone().transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
  1401. p.y = lat2latp(p.y);
  1402. return p;
  1403. });
  1404. score = Infinity;
  1405.  
  1406. for (i = 0; i < 1000; i++) {
  1407. motions = points.map(calcMotion);
  1408. for (j = 0; j < motions.length; j++) {
  1409. let tmp = addPoints(points[j], motions[j]);
  1410. points[j].x = tmp.x;
  1411. points[j].y = tmp.y;
  1412. }
  1413. var newScore = squareness(points);
  1414. if (newScore < score) {
  1415. best = [].concat(points);
  1416. score = newScore;
  1417. }
  1418. if (score < epsilon)
  1419. break;
  1420. }
  1421.  
  1422. points = best;
  1423.  
  1424. for (i = 0; i < points.length; i++) {
  1425. // only move the points that actually moved
  1426. if (originalPoints[i].x !== points[i].x || originalPoints[i].y !== points[i].y) {
  1427. let n = points[i];
  1428. n.y = latp2lat(n.y);
  1429. let pp = n.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
  1430.  
  1431. let id = nodes[i].id;
  1432. for (j = 0; j < nodes.length; j++) {
  1433. if (nodes[j].id != id)
  1434. continue;
  1435.  
  1436. nodes[j].x = pp.x;
  1437. nodes[j].y = pp.y;
  1438. }
  1439. }
  1440. }
  1441.  
  1442. // remove empty nodes on straight sections
  1443. for (i = 0; i < points.length; i++) {
  1444. let dotp = normalizedDotProduct(i, points);
  1445. if (dotp < -1 + epsilon) {
  1446. id = nodes[i].id;
  1447. for (j = 0; j < nodes.length; j++) {
  1448. if (nodes[j].id != id)
  1449. continue;
  1450.  
  1451. nodes[j] = false;
  1452. }
  1453. }
  1454. }
  1455.  
  1456. return nodes.filter(item => item !== false);
  1457. }
  1458.  
  1459. function calcMotion(b, i, array) {
  1460. let a = array[(i - 1 + array.length) % array.length],
  1461. c = array[(i + 1) % array.length],
  1462. p = subtractPoints(a, b),
  1463. q = subtractPoints(c, b),
  1464. scale, dotp;
  1465.  
  1466. scale = 2 * Math.min(euclideanDistance(p, { x: 0, y: 0 }), euclideanDistance(q, { x: 0, y: 0 }));
  1467. p = normalizePoint(p, 1.0);
  1468. q = normalizePoint(q, 1.0);
  1469.  
  1470. dotp = filterDotProduct(p.x * q.x + p.y * q.y);
  1471.  
  1472. // nasty hack to deal with almost-straight segments (angle is closer to 180 than to 90/270).
  1473. if (array.length > 3) {
  1474. if (dotp < -0.707106781186547)
  1475. dotp += 1.0;
  1476. } else if (dotp && Math.abs(dotp) < corner.dotp) {
  1477. corner.i = i;
  1478. corner.dotp = Math.abs(dotp);
  1479. }
  1480.  
  1481. return normalizePoint(addPoints(p, q), 0.1 * dotp * scale);
  1482. }
  1483. };
  1484.  
  1485. function lat2latp(lat) {
  1486. return 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * (Math.PI / 180) / 2));
  1487. }
  1488.  
  1489. function latp2lat(a) {
  1490. return 180 / Math.PI * (2 * Math.atan(Math.exp(a * Math.PI / 180)) - Math.PI / 2);
  1491. }
  1492.  
  1493. function squareness(points) {
  1494. return points.reduce(function (sum, val, i, array) {
  1495. let dotp = normalizedDotProduct(i, array);
  1496.  
  1497. dotp = filterDotProduct(dotp);
  1498. return sum + 2.0 * Math.min(Math.abs(dotp - 1.0), Math.min(Math.abs(dotp), Math.abs(dotp + 1)));
  1499. }, 0);
  1500. }
  1501.  
  1502. function normalizedDotProduct(i, points) {
  1503. let a = points[(i - 1 + points.length) % points.length],
  1504. b = points[i],
  1505. c = points[(i + 1) % points.length],
  1506. p = subtractPoints(a, b),
  1507. q = subtractPoints(c, b);
  1508.  
  1509. p = normalizePoint(p, 1.0);
  1510. q = normalizePoint(q, 1.0);
  1511.  
  1512. return p.x * q.x + p.y * q.y;
  1513. }
  1514.  
  1515. function subtractPoints(a, b) {
  1516. return { x: a.x - b.x, y: a.y - b.y };
  1517. }
  1518.  
  1519. function addPoints(a, b) {
  1520. return { x: a.x + b.x, y: a.y + b.y };
  1521. }
  1522.  
  1523. function euclideanDistance(a, b) {
  1524. let x = a.x - b.x, y = a.y - b.y;
  1525. return Math.sqrt((x * x) + (y * y));
  1526. }
  1527.  
  1528. function normalizePoint(point, scale) {
  1529. let vector = { x: 0, y: 0 };
  1530. let length = Math.sqrt(point.x * point.x + point.y * point.y);
  1531. if (length !== 0) {
  1532. vector.x = point.x / length;
  1533. vector.y = point.y / length;
  1534. }
  1535.  
  1536. vector.x *= scale;
  1537. vector.y *= scale;
  1538.  
  1539. return vector;
  1540. }
  1541.  
  1542. function filterDotProduct(dotp) {
  1543. if (lowerThreshold > Math.abs(dotp) || Math.abs(dotp) > upperThreshold)
  1544. return dotp;
  1545.  
  1546. return 0;
  1547. }
  1548.  
  1549. this.isDisabled = function (nodes) {
  1550. let points = nodes.slice(0, -1).map(function (n) {
  1551. let p = n.toLonLat().transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
  1552. return { x: p.lat, y: p.lon };
  1553. });
  1554.  
  1555. return squareness(points);
  1556. };
  1557.  
  1558. return Orthogonalize();
  1559. };
  1560.  
  1561. /**
  1562. * Returns the general location of the segment queried
  1563. * @function WazeWrap.Util.findSegment
  1564. * @param {OpenLayers.Geometry} The server to search on. The current server can be obtained from W.app.getAppRegionCode()
  1565. * @param {integer} The segment ID to search for
  1566. * @return {OpenLayers.Geometry.Point} A point at the general location of the segment, null if the segment is not found
  1567. **/
  1568. this.findSegment = async function (server, segmentID) {
  1569. let apiURL = location.origin;
  1570. switch (server) {
  1571. case 'row':
  1572. apiURL += '/row-Descartes/app/HouseNumbers?ids=';
  1573. break;
  1574. case 'il':
  1575. apiURL += '/il-Descartes/app/HouseNumbers?ids=';
  1576. break;
  1577. case 'usa':
  1578. default:
  1579. apiURL += '/Descartes/app/HouseNumbers?ids=';
  1580. }
  1581. let response, result = null;
  1582. try {
  1583. response = await $.get(`${apiURL + segmentID}`);
  1584. if (response && response.editAreas.objects.length > 0) {
  1585. let segGeoArea = response.editAreas.objects[0].geometry.coordinates[0];
  1586. let ringGeo = [];
  1587. for (let i = 0; i < segGeoArea.length - 1; i++)
  1588. ringGeo.push(new OpenLayers.Geometry.Point(segGeoArea[i][0], segGeoArea[i][1]));
  1589. if (ringGeo.length > 0) {
  1590. let ring = new OpenLayers.Geometry.LinearRing(ringGeo);
  1591. result = ring.getCentroid();
  1592. }
  1593. }
  1594. }
  1595. catch (err) {
  1596. console.log(err);
  1597. }
  1598.  
  1599. return result;
  1600. };
  1601.  
  1602. /**
  1603. * Returns the location of the venue queried
  1604. * @function WazeWrap.Util.findVenue
  1605. * @param {OpenLayers.Geometry} The server to search on. The current server can be obtained from W.app.getAppRegionCode()
  1606. * @param {integer} The venue ID to search for
  1607. * @return {OpenLayers.Geometry.Point} A point at the location of the venue, null if the venue is not found
  1608. **/
  1609. this.findVenue = async function (server, venueID) {
  1610. let apiURL = location.origin;
  1611. switch (server) {
  1612. case 'row':
  1613. apiURL += '/row-SearchServer/mozi?max_distance_kms=&lon=-84.22637&lat=39.61097&format=PROTO_JSON_FULL&venue_id=';
  1614. break;
  1615. case 'il':
  1616. apiURL += '/il-SearchServer/mozi?max_distance_kms=&lon=-84.22637&lat=39.61097&format=PROTO_JSON_FULL&venue_id=';
  1617. break;
  1618. case 'usa':
  1619. default:
  1620. apiURL += '/SearchServer/mozi?max_distance_kms=&lon=-84.22637&lat=39.61097&format=PROTO_JSON_FULL&venue_id=';
  1621. }
  1622. let response, result = null;
  1623. try {
  1624. response = await $.get(`${apiURL + venueID}`);
  1625. if (response && response.venue) {
  1626. result = new OpenLayers.Geometry.Point(response.venue.location.x, response.venue.location.y);
  1627. }
  1628. }
  1629. catch (err) {
  1630. console.log(err);
  1631. }
  1632.  
  1633. return result;
  1634. };
  1635. }
  1636.  
  1637. function Events() {
  1638. const eventMap = {
  1639. 'moveend': { register: function (p1, p2, p3) { wEvents.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { wEvents.unregister(p1, p2, p3); } },
  1640. 'zoomend': { register: function (p1, p2, p3) { wEvents.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { wEvents.unregister(p1, p2, p3); } },
  1641. 'mousemove': { register: function (p1, p2, p3) { wEvents.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { wEvents.unregister(p1, p2, p3); } },
  1642. 'mouseup': { register: function (p1, p2, p3) { wEvents.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { wEvents.unregister(p1, p2, p3); } },
  1643. 'mousedown': { register: function (p1, p2, p3) { wEvents.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { wEvents.unregister(p1, p2, p3); } },
  1644. 'changelayer': { register: function (p1, p2, p3) { wEvents.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { wEvents.unregister(p1, p2, p3); } },
  1645. 'selectionchanged': { register: function (p1, p2, p3) { W.selectionManager.events.register(p1, p2, p3) }, unregister: function (p1, p2, p3) { W.selectionManager.events.unregister(p1, p2, p3) } },
  1646. 'afterundoaction': { register: function (p1, p2, p3) { W.model.actionManager.events.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { W.model.actionManager.events.unregister(p1, p2, p3); } },
  1647. 'afterclearactions': { register: function (p1, p2, p3) { W.model.actionManager.events.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { W.model.actionManager.events.unregister(p1, p2, p3); } },
  1648. 'afteraction': { register: function (p1, p2, p3) { W.model.actionManager.events.register(p1, p2, p3); }, unregister: function (p1, p2, p3) { W.model.actionManager.events.unregister(p1, p2, p3); } },
  1649. 'change:editingHouseNumbers': { register: function (p1, p2) { W.editingMediator.on(p1, p2); }, unregister: function (p1, p2) { W.editingMediator.off(p1, p2); } },
  1650. 'change:mode': { register: function (p1, p2) { W.app.bind(p1, p2); }, unregister: function (p1, p2) { W.app.unbind(p1, p2); } },
  1651. 'change:isImperial': { register: function (p1, p2) { W.prefs.on(p1, p2); }, unregister: function (p1, p2) { W.prefs.off(p1, p2); } }
  1652. };
  1653.  
  1654. var eventHandlerList = {};
  1655.  
  1656. this.register = function (event, context, handler, errorHandler) {
  1657. if (typeof eventHandlerList[event] == "undefined")
  1658. eventHandlerList[event] = [];
  1659.  
  1660. let newHandler = function () {
  1661. try {
  1662. handler(...arguments);
  1663. }
  1664. catch (err) {
  1665. console.error(`Error thrown in: ${handler.name}\n ${err}`);
  1666. if (errorHandler)
  1667. errorHandler(err);
  1668. }
  1669. };
  1670.  
  1671. eventHandlerList[event].push({ origFunc: handler, newFunc: newHandler });
  1672. if (event === 'change:editingHouseNumbers' || event === 'change:mode' || event === 'change:isImperial')
  1673. eventMap[event].register(event, newHandler);
  1674. else
  1675. eventMap[event].register(event, context, newHandler);
  1676. };
  1677.  
  1678. this.unregister = function (event, context, handler) {
  1679. let unregHandler;
  1680. if (eventHandlerList && eventHandlerList[event]) { //Must check in case a script is trying to unregister before registering an eventhandler and one has not yet been created
  1681. for (let i = 0; i < eventHandlerList[event].length; i++) {
  1682. if (eventHandlerList[event][i].origFunc.toString() == handler.toString())
  1683. unregHandler = eventHandlerList[event][i].newFunc;
  1684. }
  1685. if (typeof unregHandler != "undefined") {
  1686. if (event === 'change:editingHouseNumbers' || event === 'change:mode' || event === 'change:isImperial')
  1687. eventMap[event].unregister(event, unregHandler);
  1688. else
  1689. eventMap[event].unregister(event, context, unregHandler);
  1690. }
  1691. }
  1692. };
  1693.  
  1694. }
  1695.  
  1696. function Interface() {
  1697. /**
  1698. * Generates id for message bars.
  1699. * @private
  1700. */
  1701. var getNextID = function () {
  1702. let id = 1;
  1703. return function () {
  1704. return id++;
  1705. };
  1706. }();
  1707.  
  1708. /**
  1709. * Creates a keyboard shortcut for the supplied callback event
  1710. * @function WazeWrap.Interface.Shortcut
  1711. * @param {string}
  1712. * @param {string}
  1713. * @param {string}
  1714. * @param {string}
  1715. * @param {string}
  1716. * @param {function}
  1717. * @param {object}
  1718. * @param {integer} The segment ID to search for
  1719. * @return {OpenLayers.Geometry.Point} A point at the general location of the segment, null if the segment is not found
  1720. **/
  1721. this.Shortcut = class Shortcut {
  1722. constructor(name, desc, group, title, shortcut, callback, scope) {
  1723. if ('string' === typeof name && name.length > 0 && 'string' === typeof shortcut && 'function' === typeof callback) {
  1724. this.name = name;
  1725. this.desc = desc;
  1726. this.group = group || this.defaults.group;
  1727. this.title = title;
  1728. this.callback = callback;
  1729. this.shortcut = {};
  1730. if (shortcut.length > 0)
  1731. this.shortcut[shortcut] = name;
  1732. if ('object' !== typeof scope)
  1733. this.scope = null;
  1734. else
  1735. this.scope = scope;
  1736. this.groupExists = false;
  1737. this.actionExists = false;
  1738. this.eventExists = false;
  1739. this.defaults = { group: 'default' };
  1740.  
  1741. return this;
  1742. }
  1743. }
  1744.  
  1745. /**
  1746. * Determines if the shortcut's action already exists.
  1747. * @private
  1748. */
  1749. doesGroupExist() {
  1750. this.groupExists = 'undefined' !== typeof W.accelerators.Groups[this.group] &&
  1751. undefined !== typeof W.accelerators.Groups[this.group].members;
  1752. return this.groupExists;
  1753. }
  1754.  
  1755. /**
  1756. * Determines if the shortcut's action already exists.
  1757. * @private
  1758. */
  1759. doesActionExist() {
  1760. this.actionExists = 'undefined' !== typeof W.accelerators.Actions[this.name];
  1761. return this.actionExists;
  1762. }
  1763.  
  1764. /**
  1765. * Determines if the shortcut's event already exists.
  1766. * @private
  1767. */
  1768. doesEventExist() {
  1769. this.eventExists = 'undefined' !== typeof W.accelerators.events.dispatcher._events[this.name] &&
  1770. W.accelerators.events.dispatcher._events[this.name].length > 0 &&
  1771. this.callback === W.accelerators.events.dispatcher._events[this.name][0].func &&
  1772. this.scope === W.accelerators.events.dispatcher._events[this.name][0].obj;
  1773. return this.eventExists;
  1774. }
  1775.  
  1776. /**
  1777. * Creates the shortcut's group.
  1778. * @private
  1779. */
  1780. createGroup() {
  1781. W.accelerators.Groups[this.group] = [];
  1782. W.accelerators.Groups[this.group].members = [];
  1783.  
  1784. if (this.title && !I18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group]) {
  1785. I18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group] = [];
  1786. I18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group].description = this.title;
  1787. I18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group].members = [];
  1788. }
  1789. }
  1790.  
  1791. /**
  1792. * Registers the shortcut's action.
  1793. * @private
  1794. */
  1795. addAction() {
  1796. if (this.title)
  1797. I18n.translations[I18n.currentLocale()].keyboard_shortcuts.groups[this.group].members[this.name] = this.desc;
  1798. W.accelerators.addAction(this.name, { group: this.group });
  1799. }
  1800.  
  1801. /**
  1802. * Registers the shortcut's event.
  1803. * @private
  1804. */
  1805. addEvent() {
  1806. W.accelerators.events.register(this.name, this.scope, this.callback);
  1807. }
  1808.  
  1809. /**
  1810. * Registers the shortcut's keyboard shortcut.
  1811. * @private
  1812. */
  1813. registerShortcut() {
  1814. W.accelerators._registerShortcuts(this.shortcut);
  1815. }
  1816.  
  1817. /**
  1818. * Adds the keyboard shortcut to the map.
  1819. * @return {WazeWrap.Interface.Shortcut} The keyboard shortcut.
  1820. */
  1821. add() {
  1822. /* If the group is not already defined, initialize the group. */
  1823. if (!this.doesGroupExist()) {
  1824. this.createGroup();
  1825. }
  1826.  
  1827. /* Clear existing actions with same name */
  1828. if (this.doesActionExist()) {
  1829. W.accelerators.Actions[this.name] = null;
  1830. }
  1831. this.addAction();
  1832.  
  1833. /* Register event only if it's not already registered */
  1834. if (!this.doesEventExist()) {
  1835. this.addEvent();
  1836. }
  1837.  
  1838. /* Finally, register the shortcut. */
  1839. this.registerShortcut();
  1840. return this;
  1841. }
  1842.  
  1843. /**
  1844. * Removes the keyboard shortcut from the map.
  1845. * @return {WazeWrap.Interface.Shortcut} The keyboard shortcut.
  1846. */
  1847. remove() {
  1848. if (this.doesEventExist()) {
  1849. W.accelerators.events.unregister(this.name, this.scope, this.callback);
  1850. }
  1851. if (this.doesActionExist()) {
  1852. delete W.accelerators.Actions[this.name];
  1853. }
  1854. //remove shortcut?
  1855. return this;
  1856. }
  1857.  
  1858. /**
  1859. * Changes the keyboard shortcut and applies changes to the map.
  1860. * @return {WazeWrap.Interface.Shortcut} The keyboard shortcut.
  1861. */
  1862. change(shortcut) {
  1863. if (shortcut) {
  1864. this.shortcut = {};
  1865. this.shortcut[shortcut] = this.name;
  1866. this.registerShortcut();
  1867. }
  1868. return this;
  1869. }
  1870. }
  1871.  
  1872. /**
  1873. * Creates a tab in the side panel
  1874. * @function WazeWrap.Interface.Tab
  1875. * @param {string}
  1876. * @param {string}
  1877. * @param {function}
  1878. * @param {string}
  1879. **/
  1880. this.Tab = async function Tab(name, content, callback, labelText) {
  1881. if(!labelText)
  1882. labelText = name;
  1883. const {tabLabel, tabPane} = W.userscripts.registerSidebarTab(name);
  1884. tabLabel.innerHTML = labelText;
  1885. tabPane.innerHTML = content;
  1886. await W.userscripts.waitForElementConnected(tabPane);
  1887. if('function' === typeof callback)
  1888. callback();
  1889.  
  1890. }
  1891.  
  1892. /**
  1893. * Creates a checkbox in the layer menu
  1894. * @function WazeWrap.Interface.AddLayerCheckbox
  1895. * @param {string}
  1896. * @param {string}
  1897. * @param {boolean}
  1898. * @param {function}
  1899. * @param {object}
  1900. * @param {Layer object}
  1901. **/
  1902. this.AddLayerCheckbox = function (group, checkboxText, checked, callback, layer) {
  1903. group = group.toLowerCase();
  1904. let normalizedText = checkboxText.toLowerCase().replace(/\s/g, '_');
  1905. let checkboxID = "layer-switcher-item_" + normalizedText;
  1906. let groupPrefix = 'layer-switcher-group_';
  1907. let groupClass = groupPrefix + group.toLowerCase();
  1908. sessionStorage[normalizedText] = checked;
  1909.  
  1910. let CreateParentGroup = function (groupChecked) {
  1911. let groupList = $('.layer-switcher').find('.list-unstyled.togglers');
  1912. let checkboxText = group.charAt(0).toUpperCase() + group.substr(1);
  1913. let newLI = $('<li class="group">');
  1914. newLI.html([
  1915. '<div class="layer-switcher-toggler-tree-category">',
  1916. '<i class="toggle-category w-icon-caret-down" data-group-id="GROUP_' + group.toUpperCase() + '"></i>',
  1917. '<wz-toggle-switch class="' + groupClass + ' hydrated" id="' + groupClass + '" ' + (groupChecked ? 'checked' : '') + '>',
  1918. '<label class="label-text" for="' + groupClass + '">' + checkboxText + '</label>',
  1919. '</div>',
  1920. '</li></ul>'
  1921. ].join(' '));
  1922.  
  1923. groupList.append(newLI);
  1924. $('#' + groupClass).change(function () { sessionStorage[groupClass] = this.checked; });
  1925. };
  1926.  
  1927. if (group !== "issues" && group !== "places" && group !== "road" && group !== "display") //"non-standard" group, check its existence
  1928. if ($('.' + groupClass).length === 0) { //Group doesn't exist yet, create it
  1929. let isParentChecked = (typeof sessionStorage[groupClass] == "undefined" ? true : sessionStorage[groupClass] == 'true');
  1930. CreateParentGroup(isParentChecked); //create the group
  1931. sessionStorage[groupClass] = isParentChecked;
  1932. }
  1933.  
  1934. var buildLayerItem = function (isChecked) {
  1935. let groupChildren = $(".collapsible-GROUP_" + group.toUpperCase());
  1936. let $li = $('<li>');
  1937. $li.html([
  1938. '<wz-checkbox id="' + checkboxID + '" class="hydrated">',
  1939. checkboxText,
  1940. '</wz-checkbox>',
  1941. ].join(' '));
  1942.  
  1943. groupChildren.append($li);
  1944. $('#' + checkboxID).prop('checked', isChecked);
  1945. $('#' + checkboxID).change(function () { callback(this.checked); sessionStorage[normalizedText] = this.checked; });
  1946. if (!$('#' + groupClass).prop('checked')) {
  1947. $('#' + checkboxID).prop('disabled', true);
  1948. if (typeof layer === 'undefined')
  1949. callback(false);
  1950. else {
  1951. if ($.isArray(layer))
  1952. $.each(layer, (k, v) => { v.setVisibility(false); });
  1953. else
  1954. layer.setVisibility(false);
  1955. }
  1956. }
  1957.  
  1958. $('#' + groupClass).change(function () {
  1959. $('#' + checkboxID).prop('disabled', !this.checked);
  1960. if (typeof layer === 'undefined')
  1961. callback(!this.checked ? false : sessionStorage[normalizedText] == 'true');
  1962. else {
  1963. if ($.isArray(layer))
  1964. $.each(layer, (k, v) => { v.setVisibility(this.checked); });
  1965. else
  1966. layer.setVisibility(this.checked);
  1967. }
  1968. });
  1969. };
  1970.  
  1971. buildLayerItem(checked);
  1972. };
  1973.  
  1974. /**
  1975. * Shows the script update window with the given update text
  1976. * @function WazeWrap.Interface.ShowScriptUpdate
  1977. * @param {string}
  1978. * @param {string}
  1979. * @param {string}
  1980. * @param {string}
  1981. * @param {string}
  1982. **/
  1983. this.ShowScriptUpdate = function (scriptName, version, updateHTML, greasyforkLink = "", forumLink = "") {
  1984. let settings;
  1985. function loadSettings() {
  1986. var loadedSettings = $.parseJSON(localStorage.getItem("WWScriptUpdate"));
  1987. var defaultSettings = {
  1988. ScriptUpdateHistory: {},
  1989. };
  1990. settings = loadedSettings ? loadedSettings : defaultSettings;
  1991. for (var prop in defaultSettings) {
  1992. if (!settings.hasOwnProperty(prop))
  1993. settings[prop] = defaultSettings[prop];
  1994. }
  1995. }
  1996.  
  1997. function saveSettings() {
  1998. if (localStorage) {
  1999. var localsettings = {
  2000. ScriptUpdateHistory: settings.ScriptUpdateHistory,
  2001. };
  2002.  
  2003. localStorage.setItem("WWScriptUpdate", JSON.stringify(localsettings));
  2004. }
  2005. }
  2006.  
  2007. loadSettings();
  2008.  
  2009. if ((updateHTML && updateHTML.length > 0) && (typeof settings.ScriptUpdateHistory[scriptName] === "undefined" || settings.ScriptUpdateHistory[scriptName] != version)) {
  2010. let currCount = $('.WWSU-script-item').length;
  2011. let divID = (scriptName + ("" + version)).toLowerCase().replace(/[^a-z-_0-9]/g, '');
  2012. $('#WWSU-script-list').append(`<a href="#${divID}" class="WWSU-script-item ${currCount === 0 ? 'WWSU-active' : ''}">${scriptName}</a>`); //add the script's tab
  2013. $("#WWSU-updateCount").html(parseInt($("#WWSU-updateCount").html()) + 1); //increment the total script updates value
  2014. let install = "", forum = "";
  2015. if (greasyforkLink != "")
  2016. install = `<a href="${greasyforkLink}" target="_blank">Greasyfork</a>`;
  2017. if (forumLink != "")
  2018. forum = `<a href="${forumLink}" target="_blank">Forum</a>`;
  2019. let footer = "";
  2020. if (forumLink != "" || greasyforkLink != "") {
  2021. footer = `<span class="WWSUFooter" style="margin-bottom:2px; display:block;">${install}${(greasyforkLink != "" && forumLink != "") ? " | " : ""}${forum}</span>`;
  2022. }
  2023. $('#WWSU-script-update-info').append(`<div id="${divID}"><span><h3>${version}</h3><br>${updateHTML}</span>${footer}</div>`);
  2024. $('#WWSU-Container').show();
  2025. if (currCount === 0)
  2026. $('#WWSU-script-list').find("a")[0].click();
  2027. settings.ScriptUpdateHistory[scriptName] = version;
  2028. saveSettings();
  2029. }
  2030. };
  2031. }
  2032.  
  2033. function Alerts() {
  2034. this.success = function (scriptName, message) {
  2035. $(wazedevtoastr.success(message, scriptName)).clone().prependTo('#WWAlertsHistory-list > .toast-container-wazedev').find('.toast-close-button').remove();
  2036. }
  2037.  
  2038. this.info = function (scriptName, message, disableTimeout, disableClickToClose, timeOut) {
  2039. let options = {};
  2040. if (disableTimeout)
  2041. options.timeOut = 0;
  2042. else if (timeOut)
  2043. options.timeOut = timeOut;
  2044.  
  2045. if (disableClickToClose)
  2046. options.tapToDismiss = false;
  2047. $(wazedevtoastr.info(message, scriptName, options)).clone().prependTo('#WWAlertsHistory-list > .toast-container-wazedev').find('.toast-close-button').remove();
  2048. }
  2049.  
  2050. this.warning = function (scriptName, message) {
  2051. $(wazedevtoastr.warning(message, scriptName)).clone().prependTo('#WWAlertsHistory-list > .toast-container-wazedev').find('.toast-close-button').remove();
  2052. }
  2053.  
  2054. this.error = function (scriptName, message) {
  2055. $(wazedevtoastr.error(message, scriptName)).clone().prependTo('#WWAlertsHistory-list > .toast-container-wazedev').find('.toast-close-button').remove();
  2056. }
  2057.  
  2058. this.debug = function (scriptName, message) {
  2059. wazedevtoastr.debug(message, scriptName);
  2060. }
  2061.  
  2062. this.prompt = function (scriptName, message, defaultText = '', okFunction, cancelFunction) {
  2063. wazedevtoastr.prompt(message, scriptName, { promptOK: okFunction, promptCancel: cancelFunction, PromptDefaultInput: defaultText });
  2064. }
  2065.  
  2066. this.confirm = function (scriptName, message, okFunction, cancelFunction, okBtnText = "Ok", cancelBtnText = "Cancel") {
  2067. wazedevtoastr.confirm(message, scriptName, { confirmOK: okFunction, confirmCancel: cancelFunction, ConfirmOkButtonText: okBtnText, ConfirmCancelButtonText: cancelBtnText });
  2068. }
  2069.  
  2070. this.ScriptUpdateMonitor = class {
  2071. #lastVersionChecked = '0';
  2072. #scriptName;
  2073. #currentVersion;
  2074. #downloadUrl;
  2075. #metaUrl;
  2076. #metaRegExp;
  2077. #GM_xmlhttpRequest;
  2078. #intervalChecker = null;
  2079. /**
  2080. * Creates an instance of ScriptUpdateMonitor.
  2081. * @param {string} scriptName The name of your script. Used as the alert title and in console error messages.
  2082. * @param {string|number} currentVersion The current installed version of the script.
  2083. * @param {string} downloadUrl The download URL of the script. If using Greasy Fork, the URL should end with ".user.js".
  2084. * @param {object} GM_xmlhttpRequest A reference to the GM_xmlhttpRequest function used by your script.
  2085. * This is used to obtain the latest script version number from the server.
  2086. * @param {string} [metaUrl] The URL to a page containing the latest script version number.
  2087. * Optional for Greasy Fork scripts (uses download URL path, replacing ".user.js" with ".meta.js").
  2088. * @param {RegExp} [metaRegExp] A regular expression with a single capture group to extract the
  2089. * version number from the metaUrl page. e.g. /@version\s+(.+)/i. Required if metaUrl is specified.
  2090. * Ignored if metaUrl is a falsy value.
  2091. * @memberof ScriptUpdateMonitor
  2092. */
  2093. constructor(scriptName, currentVersion, downloadUrl, GM_xmlhttpRequest, metaUrl = null, metaRegExp = null) {
  2094. this.#scriptName = scriptName;
  2095. this.#currentVersion = currentVersion;
  2096. this.#downloadUrl = downloadUrl;
  2097. this.#GM_xmlhttpRequest = GM_xmlhttpRequest;
  2098. this.#metaUrl = metaUrl;
  2099. this.#metaRegExp = metaRegExp || /@version\s+(.+)/i;
  2100. this.#validateParameters();
  2101. }
  2102. /**
  2103. * Starts checking for script updates at a specified interval.
  2104. *
  2105. * @memberof ScriptUpdateMonitor
  2106. * @param {number} [intervalHours = 2] The interval, in hours, to check for script updates. Default is 2. Minimum is 1.
  2107. * @param {boolean} [checkImmediately = true] If true, checks for a script update immediately when called. Default is true.
  2108. */
  2109. start(intervalHours = 2, checkImmediately = true) {
  2110. if (intervalHours < 1) {
  2111. throw new Error('Parameter intervalHours must be at least 1');
  2112. }
  2113. if (!this.#intervalChecker) {
  2114. if (checkImmediately) this.#postAlertIfNewReleaseAvailable();
  2115. // Use the arrow function here to bind the "this" context to the ScriptUpdateMonitor object.
  2116. this.#intervalChecker = setInterval(() => this.#postAlertIfNewReleaseAvailable(), intervalHours * 60 * 60 * 1000);
  2117. }
  2118. }
  2119. /**
  2120. * Stops checking for script updates.
  2121. *
  2122. * @memberof ScriptUpdateMonitor
  2123. */
  2124. stop() {
  2125. if (this.#intervalChecker) {
  2126. clearInterval(this.#intervalChecker);
  2127. this.#intervalChecker = null;
  2128. }
  2129. }
  2130. #validateParameters() {
  2131. if (this.#metaUrl) {
  2132. if (!this.#metaRegExp) {
  2133. throw new Error('metaRegExp must be defined if metaUrl is defined.');
  2134. }
  2135. if (!(this.#metaRegExp instanceof RegExp)) {
  2136. throw new Error('metaUrl must be a regular expression.');
  2137. }
  2138. } else {
  2139. if (!/\.user\.js$/.test(this.#downloadUrl)) {
  2140. throw new Error('Invalid downloadUrl paramenter. Must end with ".user.js" [', this.#downloadUrl, ']');
  2141. }
  2142. this.#metaUrl = this.#downloadUrl.replace(/\.user\.js$/, '.meta.js');
  2143. }
  2144. }
  2145. async #postAlertIfNewReleaseAvailable() {
  2146. const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))
  2147. let latestVersion;
  2148. try {
  2149. let tries = 1;
  2150. const maxTries = 3;
  2151. while (tries <= maxTries) {
  2152. latestVersion = await this.#fetchLatestReleaseVersion();
  2153. if (latestVersion === 503) {
  2154. // Greasy Fork returns a 503 error when too many requests are sent quickly.
  2155. // Pause and try again.
  2156. if (tries < maxTries) {
  2157. console.log(`${this.#scriptName}: Checking for latest version again (retry #${tries})`);
  2158. await sleep(1000);
  2159. } else {
  2160. console.error(`${this.#scriptName}: Failed to check latest version #. Too many 503 status codes returned.`);
  2161. }
  2162. tries += 1;
  2163. } else if (latestVersion.status) {
  2164. console.error(`${this.#scriptName}: Error while checking for latest version.`, latestVersion);
  2165. return;
  2166. } else {
  2167. break;
  2168. }
  2169. }
  2170. } catch (ex) {
  2171. console.error(`${this.#scriptName}: Error while checking for latest version.`, ex);
  2172. return;
  2173. }
  2174. if (latestVersion > this.#currentVersion && latestVersion > (this.#lastVersionChecked || '0')) {
  2175. this.#lastVersionChecked = latestVersion;
  2176. this.#clearPreviousAlerts();
  2177. this.#postNewVersionAlert(latestVersion);
  2178. }
  2179. }
  2180. #postNewVersionAlert(newVersion) {
  2181. const message = `<a href="${this.#downloadUrl}" target = "_blank">Version ${
  2182. newVersion}</a> is available.<br>Update now to get the latest features and fixes.`;
  2183. WazeWrap.Alerts.info(this.#scriptName, message, true, false);
  2184. }
  2185. #fetchLatestReleaseVersion() {
  2186. const metaUrl = this.#metaUrl;
  2187. const metaRegExp = this.#metaRegExp;
  2188. return new Promise((resolve, reject) => {
  2189. this.#GM_xmlhttpRequest({
  2190. nocache: true,
  2191. revalidate: true,
  2192. url: metaUrl,
  2193. onload(res) {
  2194. if (res.status === 503) {
  2195. resolve(503);
  2196. } else if (res.status === 200) {
  2197. const versionMatch = res.responseText.match(metaRegExp);
  2198. if (versionMatch?.length !== 2) {
  2199. throw new Error(`Invalid RegExp expression (${metaRegExp}) or version # could not be found at this URL: ${metaUrl}`);
  2200. }
  2201. resolve(res.responseText.match(metaRegExp)[1]);
  2202. } else {
  2203. resolve(res);
  2204. }
  2205. },
  2206. onerror(res) {
  2207. reject(res);
  2208. }
  2209. });
  2210. });
  2211. }
  2212. #clearPreviousAlerts() {
  2213. $('.toast-container-wazedev .toast-info:visible').toArray().forEach(elem => {
  2214. const $alert = $(elem);
  2215. const title = $alert.find('.toast-title').text();
  2216. if (title === this.#scriptName) {
  2217. const message = $alert.find('.toast-message').text();
  2218. if (/version .* is available/i.test(message)) {
  2219. // Force a click to make the alert go away.
  2220. $alert.click();
  2221. }
  2222. }
  2223. });
  2224. }
  2225. }
  2226. }
  2227. function Remote(){
  2228. function sendPOST(scriptName, scriptSettings){
  2229. return new Promise(function (resolve, reject) {
  2230. var xhr = new XMLHttpRequest();
  2231. xhr.open("POST", "https://wazedev.com:8443", true);
  2232. xhr.setRequestHeader('Content-Type', 'application/json');
  2233. xhr.onreadystatechange = function(e) {
  2234. if (xhr.readyState === 4) {
  2235. if (xhr.status === 200)
  2236. resolve(true)
  2237. else
  2238. reject(false)
  2239. }
  2240. }
  2241. xhr.send(JSON.stringify({
  2242. userID: W.loginManager.user.getID().toString(),
  2243. pin: wwSettings.editorPIN,
  2244. script: scriptName,
  2245. settings: scriptSettings
  2246. }));
  2247. });
  2248. }
  2249.  
  2250. this.SaveSettings = async function(scriptName, scriptSettings){
  2251. if(wwSettings.editorPIN === ""){
  2252. console.error("Editor PIN not set");
  2253. return null;
  2254. }
  2255. if(scriptName === ""){
  2256. console.error("No script name provided");
  2257. return null;
  2258. }
  2259. try{
  2260. return await sendPOST(scriptName, scriptSettings);
  2261. /*let result = await $.ajax({
  2262. url: 'https://wazedev.com:8443',
  2263. type: 'POST',
  2264. contentType: 'application/json',
  2265. data: JSON.stringify({
  2266. userID: W.loginManager.user.id,
  2267. pin: wwSettings.editorPIN,
  2268. script: scriptName,
  2269. settings: scriptSettings
  2270. })}
  2271. );
  2272. return result;*/
  2273. }
  2274. catch(err){
  2275. console.log(err);
  2276. return null;
  2277. }
  2278. }
  2279. this.RetrieveSettings = async function(script){
  2280. if(wwSettings.editorPIN === ""){
  2281. console.error("Editor PIN not set");
  2282. return null;
  2283. }
  2284. if(script === ""){
  2285. console.error("No script name provided");
  2286. return null;
  2287. }
  2288. try{
  2289. let response = await fetch(`https://wazedev.com/userID/${W.loginManager.user.getID()}/PIN/${wwSettings.editorPIN}/script/${script}`);
  2290. response = await response.json();
  2291. return response;
  2292. }
  2293. catch(err){
  2294. console.log(err);
  2295. return null;
  2296. }
  2297. }
  2298. }
  2299.  
  2300. function String() {
  2301. this.toTitleCase = function (str) {
  2302. return str.replace(/(?:^|\s)\w/g, function (match) {
  2303. return match.toUpperCase();
  2304. });
  2305. };
  2306. }
  2307. }.call(this));