WazeWrap Testing

Test

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/471457/1251523/WazeWrap%20Testing.js

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址