WazeWrapLib dev

WazeWrapLib for development purposes

当前为 2025-04-11 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/532551/1569457/WazeWrapLib%20dev.js

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