Tidy up your Dashboard

Tidy Up Your Dashboard is a Userscript which brings along a lot of features for improving the user experience on Warlight.

当前为 2017-06-19 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Tidy up your Dashboard
  3. // @namespace https://gf.qytechs.cn/users/10154
  4. // @grant none
  5. // @run-at document-start
  6. // @match https://www.warlight.net/*
  7. // @exclude /.*[Mm][Uu][Ll][Tt][Ii][Pp][Ll][Aa][Yy][Ee][Rr]\?([Gg][Aa][Mm][Ee][Ii][Dd]|[Cc][Rr][Ee][Aa][Tt][Ee][Gg][Aa][Mm][Ee]).*/
  8. // @exclude /.*[Ss][Ii][Nn][Gg][Ll][Ee][Pp][Ll][Aa][Yy][Ee][Rr]\?([Ll][Ee][Vv][Ee][Ll]|[Ee][Dd][Ii][Tt][Ll][Ee][Vv][Ee][Ll]|[Cc][Uu][Ss][Tt][Oo][Mm][Gg][Aa][Mm][Ee]|[Pp][Rr][Ee][Vv][Ii][Ee][Ww][Mm][Aa][Pp]).*/
  9. // @exclude /.*[Uu][Nn][Ii][Tt][Yy]=1.*/
  10. // @description Tidy Up Your Dashboard is a Userscript which brings along a lot of features for improving the user experience on Warlight.
  11. // @version 1.15.2
  12. // @icon http://i.imgur.com/XzA5qMO.png
  13. // @require https://code.jquery.com/jquery-1.11.2.min.js
  14. // @require https://code.jquery.com/ui/1.11.3/jquery-ui.min.js
  15. // @require https://cdn.bootcss.com/datatables/1.10.10/js/jquery.dataTables.min.js
  16. // @require https://cdn.bootcss.com/datatables/1.10.10/js/dataTables.bootstrap.js
  17. // @require https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js
  18. // ==/UserScript==
  19. window.timeUserscriptStart = new Date().getTime();
  20. var version = "1.15.2";
  21. this.$$$ = jQuery.noConflict(true);
  22.  
  23. var logData = "";
  24. function log(entry) {
  25. var time = moment(new Date()).format('h:mm:ss');
  26. logData += `\n${time} | ${entry}`;
  27. }
  28. function logError(entry) {
  29. var time = moment(new Date()).format('h:mm:ss');
  30. logData += `\n${time} | ${entry}`;
  31. }
  32. //ctrl+shift+2
  33. $$$(document).keydown(function(e){
  34. if( e.which === 50 && e.ctrlKey && e.shiftKey ){
  35. getLog()
  36. }
  37. });
  38.  
  39. window.logDialog = undefined;
  40. window.getLog = function() {
  41. if(logDialog) {
  42. logDialog.html(`<textarea style="height:100%;width:100%">${logData}</textarea>`)
  43. logDialog.dialog('open')
  44. } else {
  45. logDialog = $$$(`<div style="overflow:hidden"><textarea style="height:100%;width:100%">${logData}</textarea></div>`).dialog({
  46. width: 800,
  47. title: "Userscript log",
  48. height: 400});
  49. }
  50. }
  51. window.onerror = windowError
  52.  
  53. function windowError(message, source, lineno, colno, error) {
  54. logError(`Error on line ${lineno} col ${colno} in ${source}`)
  55. logError(`${JSON.stringify(error)} ${message}`)
  56. if(typeof $().dialog == "function") {
  57. window.wlerror(message, source, lineno, colno, error)
  58. }
  59. }
  60.  
  61. if(pageIsDashboard()) {
  62. createSelector("#MainSiteWrapper", "display: none")
  63. createSelector("body", "overflow: hidden")
  64. }
  65.  
  66. setupDatabase()
  67. log("indexedDB setup complete")
  68.  
  69. if (document.readyState == 'complete' || document.readyState == 'interactive') {
  70. log("Readystate complete|interactive")
  71. DOM_ContentReady();
  72. } else {
  73. window.document.addEventListener("DOMContentLoaded", DOM_ContentReady);
  74. log("Readystate loading")
  75. }
  76.  
  77. //$(document).ready(DOM_ContentReady)
  78.  
  79.  
  80. function checkVersion() {
  81. Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "version", function(v) {
  82. var currentVersion = v != undefined ? v.value: undefined
  83. log("Current version " + currentVersion)
  84. if (currentVersion == version) {
  85. //Script Up to date
  86.  
  87. } else if (currentVersion == undefined) {
  88. //Script new installed
  89. addDefaultBookmark();
  90. setupSettingsDatabase();
  91. } else {
  92. setUserInvalid()
  93. //Script Updated
  94.  
  95. //$("label[for='showPrivateNotesOnProfile']").addClass('newSetting');
  96.  
  97. //showPopup(".userscript-show");
  98.  
  99. // window.setTimeout(function() {
  100. // warlight_shared_viewmodels_AlertVM.DoPopup("Tidy up Your Dashboard was sucessfully updated to version " + version + "! Check out the forum thread to see what changed.");
  101. // }, 1000)
  102. }
  103.  
  104. addVersionLabel()
  105. if(sessionStorage.getItem("showUserscriptMenu")) {
  106. showUserscriptMenu();
  107. sessionStorage.removeItem("showUserscriptMenu")
  108. }
  109. })
  110. Database.update(Database.Table.Settings, {name: "version", value: version}, undefined, function() {
  111. })
  112. }
  113.  
  114. setupImages();
  115. window.userscriptSettings = [
  116. {
  117. id: 'scrollGames',
  118. text: 'Fixed Window with scrollable Games',
  119. selected: true,
  120. title: 'Dashboard',
  121. addBreak: false,
  122. help: 'This Option displays My-, Open-, Coin-Games in a scrollable box, which removes lots of unesessary scrolling. You can find tabs to switch between the different type of games. '
  123. },
  124. {
  125. id: 'hideMyGamesIcons',
  126. text: 'Hide Icons in "My Games"',
  127. selected: false,
  128. title: '',
  129. addBreak: false,
  130. help: 'This Option hides Game-Icons like ( <img src="https://d2wcw7vp66n8b3.cloudfront.net/Images/GameInfoIcons/Teams.png">,<img src="https://d2wcw7vp66n8b3.cloudfront.net/Images/GameInfoIcons/ManualDistribution.png"> , etc) in "My Games"'
  131. },
  132. {
  133. id: 'autoRefreshOnFocus',
  134. text: 'Automatically refresh Games on Tab-Focus',
  135. selected: true,
  136. title: '',
  137. addBreak: false,
  138. help: 'This Option automatically refreshes your Games after switching back to Warlight from a different tab / program. This only applies if Warlight was idle for 30 or more seconds.'
  139. },
  140. {
  141. id: 'highlightTournaments',
  142. text: 'Highlight Tournament invites',
  143. selected: false,
  144. title: '',
  145. addBreak: false,
  146. },
  147. {
  148. id: 'hideRightColumn',
  149. text: 'Hide Right Column',
  150. selected: false,
  151. title: '',
  152. addBreak: false,
  153. help: 'This Option hides the right column completely and leaves you alone with My-, Open- and Coin-Games.'
  154. },
  155. {
  156. id: 'hidePromotedGames',
  157. text: 'Hide Promoted Games',
  158. selected: false,
  159. title: '',
  160. addBreak: false,
  161. help: 'This Option hides the Promoted Games on the Dashboard'
  162. },
  163. {
  164. id: 'showOpenGamesTab',
  165. text: 'Show Open Games Tab in Menu Bar',
  166. selected: false,
  167. title: 'Global',
  168. addBreak: false,
  169. help: 'This Option displays a link to the "Open Games" site right next to the "Past Games" Link.'
  170. },
  171. {
  172. id: 'hideCoinsGlobally',
  173. text: 'Hide Coins Globally',
  174. selected: false,
  175. title: '',
  176. addBreak: false,
  177. help: 'This Option removes everything from Warlight related to Coins'
  178. },
  179. {
  180. id: 'showPrivateNotesOnProfile',
  181. text: 'Show Private Notes on Profile',
  182. selected: true,
  183. title: '',
  184. addBreak: false,
  185. help: 'This Option will show you your Private Notes which you made on a player directly on their Profile page. You can find them on the left side under the profile picture.'
  186. },
  187. {
  188. id: 'unlinkDashboard',
  189. text: 'Link Dashboard to "old" My-Games Site',
  190. selected: false,
  191. title: '',
  192. addBreak: false,
  193. help: 'This Option links the Dashboard to the "old" My-Games Site'
  194. },
  195. {
  196. id: 'useDefaultBootLabel',
  197. text: 'Use the Default Boot Time Label',
  198. selected: false,
  199. title: 'Advanced',
  200. addBreak: false
  201. },
  202. {
  203. id: 'hideRefreshButton',
  204. text: 'Hide Refresh Button',
  205. selected: false,
  206. title: '',
  207. addBreak: false,
  208. help: 'Hide the Refresh Button. You can still refresh with R'
  209. },
  210. {
  211. id: 'hideOffTopic',
  212. text: 'Automatically hide Off-topic threads',
  213. selected: false,
  214. title: '',
  215. addBreak: false,
  216. help: 'This Option automatically hides all Off-topic threads everytime you visit the "All Forum Posts"-Page'
  217. },
  218. {
  219. id: 'disableHideThreadOnDashboard',
  220. text: 'Disable right-click on the Forum Table',
  221. selected: false,
  222. title: '',
  223. addBreak: false,
  224. help: 'This Option will allow you right-click Forum Thread on the Dashboard and use the Default Options.'
  225. },
  226. {
  227. id: 'hideCreateRandomGameForm',
  228. text: 'Hide Randomized Bonuses Game Form',
  229. selected: false,
  230. title: '',
  231. addBreak: false,
  232. help: 'This Option will hide the Randomized Bonuses Game Form which is located on the Profile Page.'
  233. },
  234. {
  235. id: 'burningHot',
  236. text: 'Disable burning words',
  237. selected: false,
  238. title: '',
  239. addBreak: false,
  240. help: 'Certain words will receive a flame affect.'
  241. },
  242. {
  243. id: 'showSnow',
  244. text: 'Show Snow',
  245. selected: false,
  246. title: '',
  247. addBreak: false,
  248. help: 'Shows the snow animation on all sites'
  249. },
  250. {
  251. id: 'snowLight',
  252. text: 'Reduce the number of Snowflakes',
  253. selected: false,
  254. title: '',
  255. addBreak: false,
  256. help: 'Reduce the number of Snowflakes for a better performance'
  257. }
  258. ];
  259.  
  260. window.filters = [
  261. {
  262. id: "disableAll",
  263. text: "Disable All Filters",
  264. selected: false,
  265. type: "checkbox"
  266. },
  267. {
  268. id: "",
  269. text: "<div style='display:inline-block;height:30px; width: 10px'> </div>",
  270. selected: false,
  271. type: "custom"
  272. },
  273. {
  274. id: "hideTeam",
  275. text: "Hide Team Games",
  276. selected: false,
  277. type: "checkbox"
  278. },
  279. {
  280. id: "hideCommanderGames",
  281. text: "Hide Games with Commanders",
  282. selected: false,
  283. type: "checkbox"
  284. },
  285. {
  286. id: "hideFFA",
  287. text: "Hide FFA Games",
  288. selected: false,
  289. type: "checkbox"
  290. },
  291. {
  292. id: "hideNoneCommanderGames",
  293. text: "Hide Games without Commanders",
  294. selected: false,
  295. type: "checkbox"
  296. },
  297. {
  298. id: "hide1v1",
  299. text: "Hide 1 v 1 Games",
  300. selected: false,
  301. type: "checkbox"
  302. },
  303. {
  304. id: "hideManualDistribution",
  305. text: "Hide Manual Distribution Games",
  306. selected: false,
  307. type: "checkbox"
  308. },
  309. {
  310. id: "hideNoSplit",
  311. text: "Hide No-Split Games",
  312. selected: false,
  313. type: "checkbox"
  314. },
  315. {
  316. id: "hideAutoDistribution",
  317. text: "Hide Auto Distribution Games",
  318. selected: false,
  319. type: "checkbox"
  320. },
  321. {
  322. id: "hideLocalDeployments",
  323. text: "Hide Local Deployment Games",
  324. selected: false,
  325. type: "checkbox"
  326. },
  327. {
  328. id: "hideCustomScenario",
  329. text: "Hide Custom Scenario Games",
  330. selected: false,
  331. type: "checkbox"
  332. },
  333. {
  334. id: "hideLuck",
  335. text: "<label for='hideLuck' style='width:169px'>Hide Luck greater than</label><input type='text' id='hideLuck' class='number'>",
  336. selected: false,
  337. type: "custom"
  338. },
  339. {
  340. id: "hideNonCustomScenario",
  341. text: "Hide Non-Custom Scenario Games",
  342. selected: false,
  343. type: "checkbox"
  344. },
  345. {
  346. id: "hideKeyword",
  347. text: '<label for="hideKeyword" style="width:115px">Hide Keywords<img src="' + IMAGES.QUESTION + '" class="help-icon" onclick="showFilterHelp(\'You can separate multiple Keywords with a comma. Each keyword must have 3 or more letters. The Keyword-Filter searches for case insensitive matches in the complete game title.<br>Example: The keyword ´Rop´ removes the game ´Europe 3v3´\', this)"></label><br><input type="text" id="hideKeyword" style="width: 95%;margin-left: 6px;"><hr>',
  348. selected: false,
  349. type: "custom",
  350. },
  351. {
  352. id: "hidePractice",
  353. text: "Hide Practice Games",
  354. selected: false,
  355. type: "checkbox"
  356. },
  357. {
  358. id: "hideNonPractice",
  359. text: "Hide Non-Practice Games",
  360. selected: false,
  361. type: "checkbox"
  362. },
  363. {
  364. id: "limitPlayers",
  365. text: '<label>Limit Amount of Players</label><br><div class="filter-small"><label for="hideMinPlayers" style="width:25px">Min </label><input class="number" type="text" id="hideMinPlayers">Players<br><label for="hideMaxPlayers" style="width:25px">Max </label><input class="number" type="text" id="hideMaxPlayers">Players</div>',
  366. selected: false,
  367. type: "custom"
  368. },
  369. {
  370. id: "hideBootTime",
  371. text: '<label>Hide Boot Time lower than</label><br><div class="filter-small"><label for="hideRealTimeBootTime" style="width:100px">Realtime: </label><input class="number" type="text" id="hideRealTimeBootTime">minute(s)<br><label for="hideMinPlayers" style="width:100px">Multiday: </label><input class="number" type="text" id="hideMultiDayBootTimeDays"> day(s) and <input class="number" type="text" id="hideMultiDayBootTimeHours"> hour(s)</div>',
  372. selected: false,
  373. type: "custom"
  374. }
  375. ];
  376.  
  377.  
  378. window.showGamesActive = "ShowMyGames";
  379.  
  380. window.openGames = [];
  381. window.wlerror = function(){}
  382. function DOM_ContentReady() {
  383. log("DOM content ready")
  384. window.wlerror = window.onerror
  385. window.onerror = windowError
  386. window.timeDomContentReady = new Date().getTime();
  387. log("Time DOM content ready " + (timeDomContentReady - timeUserscriptStart) / 1000)
  388. log("DOM content ready")
  389. $.fn.outerHTML = function (s) {
  390. return s ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html();
  391. };
  392. window.WLError = function(a, b) {
  393. logError(a)
  394. null == a && (a = "");
  395. console.log("WLError: " + a + ", silent=" + b); - 1 != a.indexOf("NotAuth") ? location.reload() : -1 != a.indexOf("WarLight Server returned CouldNotConnect") ? CNCDialog() : -1 == a.indexOf("TopLine is not defined") && -1 == a.indexOf("_TPIHelper") && -1 == a.indexOf("Syntax error, unrecognized expression: a[href^=http://]:not([href*=") && -1 == a.indexOf("y2_cc2242") && -1 == a.indexOf("Error calling method on NPObject") && (-1 != a.indexOf("WARLIGHTERROR48348927984712893471394") ? a = "ServerError" : -1 !=
  396. a.indexOf("WARLIGHTHEAVYLOAD48348927984712893471394") && (a = "HeavyLoad"), ReportError(a), b || PopErrorDialog(a))
  397. }
  398. $.fn.getsFiltered = function (openGamesFilters) {
  399. var game = this[0];
  400. if(game) {
  401. if (openGamesFilters["hideMaxPlayers"] <= 100 && $(game).numOfPlayers() > openGamesFilters["hideMaxPlayers"]) return true;
  402. if (openGamesFilters["hideMinPlayers"] <= 100 && $(game).numOfPlayers() < openGamesFilters["hideMinPlayers"]) return true;
  403. if (openGamesFilters["hideLuck"] < 100 && game.SettingsOpt.LuckModifier * 100 > openGamesFilters["hideLuck"]) return true;
  404. if (openGamesFilters["hideFFA"] && $(game).numOfTeams() == 0 && $(game).numOfPlayers() > 2) return true;
  405. if (openGamesFilters["hideTeam"] && $(game).numOfTeams() > 0) return true;
  406. if (openGamesFilters["hide1v1"] && $(game).numOfPlayers() == 2) return true;
  407. if (openGamesFilters["hideCustomScenario"] && game.SettingsOpt.DistributionMode === -3) return true;
  408. if (openGamesFilters["hideNonCustomScenario"] && game.SettingsOpt.DistributionMode !== -3) return true;
  409. if (openGamesFilters["hideCommanderGames"] && game.SettingsOpt.HasCommanders) return true;
  410. if (openGamesFilters["hideNoneCommanderGames"] && !game.SettingsOpt.HasCommanders) return true;
  411. if (openGamesFilters["hidePractice"] && !game.SettingsOpt.RankedGame) return true;
  412. if (openGamesFilters["hideNoSplit"] && game.SettingsOpt.NoSplit) return true;
  413. if (openGamesFilters["hideLocalDeployments"] && game.SettingsOpt.LocalDeployments) return true;
  414. if (openGamesFilters["hideNonPractice"] && game.SettingsOpt.RankedGame) return true;
  415. if (openGamesFilters["hideManualDistribution"] && !game.SettingsOpt.AutoDistribution) return true;
  416. if (openGamesFilters["hideAutoDistribution"] && game.SettingsOpt.AutoDistribution) return true;
  417. if (openGamesFilters["hideKeyword"] && openGamesFilters["hideKeyword"].length > 0 && $(game).containsKeyword(openGamesFilters)) return true;
  418. if (openGamesFilters["hideRealTimeBootTime"] > 0 && game.RealTimeGame && game.DirectBoot._totalMilliseconds < openGamesFilters["hideRealTimeBootTime"]) return true;
  419. if (openGamesFilters["hideMultiDayBootTimeInMs"] > 0 && !game.RealTimeGame && game.DirectBoot._totalMilliseconds < openGamesFilters["hideMultiDayBootTimeInMs"]) return true;
  420. }
  421.  
  422. return false;
  423. };
  424.  
  425. $.fn.numOfPlayers = function () {
  426. var game = this[0];
  427. return game.Players.length + game.OpenSeats.length;
  428.  
  429. };
  430.  
  431. $.fn.playerJoined = function () {
  432. var game = this[0];
  433. var playerJoined = false;
  434. var id = warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID;
  435. $.each(game.Players, function (key, player) {
  436. if (player.PlayerID == id) {
  437. playerJoined = true;
  438. }
  439. });
  440. return playerJoined;
  441. };
  442.  
  443. $.fn.markJoined = function () {
  444. var game = this[0];
  445. game.Name += '##joined##';
  446. return game;
  447. };
  448.  
  449. $.fn.numOfTeams = function () {
  450. var game = this[0];
  451. var teams = 0;
  452. if (game.AtStartDivideIntoTeamsOfIfOpenGame > 0) return $(game).numOfPlayers() / game.AtStartDivideIntoTeamsOfIfOpenGame;
  453. if (Math.max.apply(Math, game.OpenSeats) == -1) return 0;
  454. var maxTeam = Math.max.apply(Math, game.OpenSeats);
  455. $.each(game.Players, function (key, player) {
  456. if (player.Team > maxTeam) {
  457. maxTeam = player.Team;
  458. };
  459. });
  460. return maxTeam + 1;
  461. }
  462.  
  463. $.fn.containsKeyword = function (openGamesFilters) {
  464. var game = this[0];
  465. var keywords = openGamesFilters["hideKeyword"].split(",");
  466. var title = game._nameLowered || game.Name.toLowerCase();
  467. var filtered = false;
  468. $.each(keywords, function (key, keyword) {
  469. if (title.indexOf(keyword.trim().toLowerCase()) >= 0) {
  470. filtered = true;
  471. }
  472. })
  473. return filtered;
  474.  
  475. };
  476.  
  477. $.fn.settingIsEnabled = function (setting) {
  478. var selected = false;
  479. $.each(userscriptSettings, function (key, set) {
  480. if (set.id == setting) {
  481. selected = set.selected;
  482. }
  483. });
  484. return selected;
  485. };
  486. try {
  487. $.extend( $$$.fn.dataTableExt.oSort, {
  488. "rank-pre": function ( a ) {
  489. return a.match(/([0-9]*)/)[1] || 9999;
  490. },
  491.  
  492. "rank-asc": function( a, b ) {
  493. return a < b;
  494. },
  495.  
  496. "rank-desc": function(a,b) {
  497. return a > b;
  498. }
  499. } );
  500. $.extend( $$$.fn.dataTableExt.oSort, {
  501. "numeric-comma-pre": function ( a ) {
  502. return Number(a.replace(/,/g, ""))
  503. },
  504.  
  505. "numeric-comma-asc": function( a, b ) {
  506. return a < b;
  507. },
  508.  
  509. "numeric-comma-desc": function(a,b) {
  510. return a > b;
  511. }
  512. } );
  513. } catch(e) {
  514. log(e)
  515. }
  516. addCSS(`
  517. input.unityId {
  518. width: 100%;
  519. box-sizing: border-box;
  520. height: 30px;
  521. text-align: center;
  522. font-size: 10px;
  523. }
  524. h3.unityId {
  525. text-align: center;
  526. margin-top: 5px;
  527. }
  528. `)
  529. $(document).click(function(e) {
  530. if(e.shiftKey && e.ctrlKey) {
  531. e.preventDefault();
  532. var aTag = $(e.target).closest("a");
  533. var href = aTag.attr("href")
  534. if(href != undefined && (id = href.match(/(gameid=|level\?id=|level=)([0-9]*)/i))) {
  535. var title = $("<h3>").text("Game Link").addClass("unityId")
  536. var input = $("<input>").attr("value", href).addClass("unityId")
  537. $('<div/>').prepend(title).append(input).dialog()
  538. $("input.unityId").select()
  539. var ctrlKey = 17,
  540. cmdKey = 91,
  541. cKey = 67,
  542. xKey = 88;
  543.  
  544. $(".unityId").keydown(function(e) {
  545. if ((e.ctrlKey || e.cmdKey) && (e.keyCode == xKey || e.keyCode == cKey)) {
  546. window.setTimeout(function() {
  547. $(".ui-dialog-content").dialog("close");
  548. }, 100)
  549. }
  550. })
  551. }
  552. }
  553. });
  554. if(pageIsNewThread()) {
  555. $("[onclick='undoIgnore()']").closest("th").remove();
  556. $(".checkbox").closest("td").remove()
  557. }
  558. if(document.getElementById("MyGamesFilter") != null) {
  559. document.getElementById("MyGamesFilter").onchange = null
  560. }
  561. $("#MyGamesFilter").on("change", function() {
  562. var customFilter = $(this).val()
  563. Database.update(Database.Table.Settings, {name: "customFilter", value: customFilter}, undefined, function() {
  564. refreshMyGames();
  565. })
  566. })
  567.  
  568. if(pageIsDashboard()) {
  569. $("body").append("<div class='loader' style=' background: black;position: fixed;left: 0;right: 0;top: 75px;bottom: 0;z-index: 100;'></div>")
  570. $("#MainSiteWrapper").show();
  571. window.lastRefresh;
  572. window.myGamesTable = $("#MyGamesTable");
  573. window.openGamesTable = $("#OpenGamesTable");
  574. window.promotedGamesTable = $("#PromotedGamesTable");
  575. window.lastClick = new Date();
  576. }
  577. if(pageIsThread()) {
  578. setupTextarea()
  579. }
  580. if(pageIsMapPage() && mapIsPublic()) {
  581. var id = location.href.match(/[^\d]*([\d]*)/)[1]
  582. $("#MainSiteContent ul").append(`<li><a href="https://www.warlight.net/RateMap?ID=${id}" target="_blank">Rate Map</a></li>`)
  583. }
  584.  
  585. if (pageIsForumThread() || pageIsClanForumThread()) {
  586. //Show Open Games Link
  587. $("[href='#Reply']").after(" | <a style='cursor:pointer' onclick='bookmarkForumThread()'>Bookmark</a>")
  588. $("#PostReply").after(" | <a style='cursor:pointer' onclick='bookmarkForumThread()'>Bookmark</a>")
  589. $(".region a[href='/Profile?p=2211733141']:contains('Muli')").closest("td").find("a:contains('Report')").before("<br><a href='https://www.warlight.net/Forum/106092-mulis-userscript-tidy-up-dashboard'><font color='#FFAE51' size='1'>Script Creator</font></a><br>")
  590. setupAWPWorldTour()
  591. }
  592.  
  593. if (pageIsTournament()) {
  594. window.setTimeout(function() {
  595. setupTournamentFindMe()
  596. setupPlayerDataTable()
  597. }, 50)
  598. $("#HostLabel").after(" | <a style='cursor:pointer' onclick='bookmarkTournament()'>Bookmark</a>");
  599. $("#HostLabel").css("display", "inline-block")
  600. $("#LeftToStartMessage").text(" | " + $("#LeftToStartMessage").text())
  601. createSelector("#LeftToStartMessage:before", "content: ' | '")
  602. createSelector("#ChatContainer", "clear:both")
  603. $("input").on("keypress keyup keydown", function(e) {e.stopPropagation()})
  604.  
  605. }
  606.  
  607. if (pageIsCommonGames()) {
  608. window.$ = $$$
  609. setupCommonGamesDataTable()
  610. }
  611.  
  612. if(pageIsTournamentOverview()) {
  613. setupTournamentDecline();
  614. setupTournamentTableStyles();
  615. setupTournamentDataCheck();
  616. $(window).resize(function () {
  617. setTournamentTableHeight();
  618. });
  619. $(window).on("scroll",function(){$(window).scrollTop(0)})
  620. }
  621.  
  622. if(pageIsLadderOverview()) {
  623. setupLadderClotOverview()
  624. }
  625.  
  626. if(pageIsMapsPage()) {
  627. setupMapSearch()
  628. }
  629.  
  630. if(pageIsLevelPlayLog()) {
  631. setupPlayerAttempDataTable();
  632. }
  633. if(pageIsLevelOverview()) {
  634. setupLevelBookmark();
  635. }
  636.  
  637. if(pageIsRealTimeLadder()) {
  638. setupRealTimeLadderPageTimer()
  639. }
  640.  
  641. if(pageIsDashboard() || pageIsRealTimeLadder()) {
  642. window.setInterval(setRTLadderTime, 1000)
  643. window.setInterval(setMyGamesTimeLeft, 1000)
  644. $(window).on("mousewheel", function() {
  645. $(".ui-tooltip").hide()
  646. })
  647. //Make player boxes also clickable
  648. $.each($(".GameRow"), function(key, row) {
  649. var href = $(this).find("a").attr("href");
  650. var children = $(this).find("td:nth-of-type(2) > span:nth-of-type(1)");
  651. var style = "display: inline-block;max-width: 400px;margin: 4px 0px;float: none;position: relative;font-size:10pt!important;white-space:normal;height:initial";
  652.  
  653. children.wrapInner("<a/>").children(0).unwrap().attr("style", style).attr("href", href)
  654. })
  655. }
  656.  
  657. if(pageIsProfile()) {
  658. createSelector(".profileBox", "background-image: url(\'https://d2wcw7vp66n8b3.cloudfront.net/Images/ProfileSpeedBackground.png\'); background-repeat: no-repeat; text-align: left; padding:10px;margin-top: 12px;")
  659.  
  660. //setupManagerLeague();
  661. foldProfileStats()
  662. }
  663. setupExtendedTwitch();
  664. window.setInterval(function(){
  665. setupExtendedTwitch();
  666. }, 60000);
  667. StartLivestream()
  668.  
  669. Database.init(function() {
  670. console.log("init")
  671. if(pageIsDashboard()) {
  672. warlight_shared_viewmodels_WaitDialogVM.Start("Tidying Up...")
  673. }
  674. setIsMember();
  675. window.setTimeout(validateUser, 2000);
  676. setGlobalStyles();
  677. setupUserscriptMenu();
  678. setupBookmarkMenu();
  679. checkVersion();
  680. main();
  681. setupSnowflakes()
  682. })
  683.  
  684. }
  685.  
  686.  
  687. function main() {
  688. log("Running main")
  689. if(pageIsForumOverview()) {
  690. ifSettingIsEnabled("hideOffTopic", function() {
  691. hideOffTopicThreads()
  692. })
  693. formatHiddenThreads();
  694. }
  695. if(pageIsCommunityLevels()) {
  696. setupCommunityLevels()
  697. }
  698.  
  699. if(pageIsForumOverview() || pageIsSubForum()) {
  700. setupSpammersBeGone()
  701. }
  702. ifSettingIsEnabled("unlinkDashboard", function() {
  703. $("#MultiPlayerBtn").attr('href', 'https://www.warlight.net/MultiPlayer?MyGames=1');
  704. $("#SubTabRow td > a[href='/MultiPlayer/']").attr('href', 'https://www.warlight.net/MultiPlayer?MyGames=1');
  705. })
  706. if (pageIsMultiplayer()) {
  707. //Show Open Games Link
  708. ifSettingIsEnabled('showOpenGamesTab', function() {
  709. showOpenGamesLink();
  710. })
  711. setupDashboardSearch();
  712. }
  713. if(pageIsProfile() && $("#BlackListImage").length > 0) {
  714. ifSettingIsEnabled('showPrivateNotesOnProfile', function() {
  715. loadPrivateNotes();
  716. })
  717. }
  718. if(pageIsTournamentOverview()){
  719. log("loading torunament data")
  720. loadTournamentData();
  721. }
  722. if(pageIsTournament()) {
  723. updateTournamentData()
  724. $("#JoinBtn").on("click", updateTournamentData)
  725. }
  726. if(pageIsBlacklistPage()) {
  727. $("#MainSiteContent ul").before(`<span id="numBlacklisted">You have <b>${$("#MainSiteContent ul li:visible").length}</b> players on your blacklist.</span>`)
  728. window.setInterval(function() {
  729. $("#numBlacklisted").replaceWith(`<span id="numBlacklisted">You have <b>${$("#MainSiteContent ul li:visible").length}</b> players on your blacklist.</span>`)
  730. }, 500)
  731. }
  732. setupRandomizedBonuses();
  733. if(pageIsPointsPage()) {
  734. Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "totalPoints", function(res) {
  735. if(res) {
  736. $("#MainSiteContent table:first").before(`<br><span>In total, you've earned <b>${res.value.toLocaleString("en")}</b> points.</span>`)
  737. } else {
  738. $("#MainSiteContent table:first").before(`<br><span>Visit the Dashboard once to see how many points you've earned in total.</span>`)
  739. }
  740. })
  741. }
  742. if (pageIsDashboard()) {
  743. window.StringTools.htmlEscape = function (a) {
  744. if (a.indexOf("##joined##") >= 0) {
  745. a = a.replace("##joined##", "");
  746. return htmlEscape(a) + '<img style="display:inline-block;height:16px;width:16px;margin-left:10px;z-index:10;cursor:default" src="https://i.imgur.com/6akgXa7.png" title="You already joined this game">';
  747. } else {
  748. return htmlEscape(a);
  749. }
  750.  
  751. }
  752. hideBlacklistedThreads();
  753. setupBasicDashboardStyles();
  754. setupCustomSort(function() {
  755. Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "customFilter", function(f) {
  756. var filter = (f && f.value) ? f.value : 4;
  757. $("#MyGamesFilter").val(filter)
  758. refreshMyGames();
  759. })
  760. });
  761. ifSettingIsEnabled('hideCoinsGlobally', function() {
  762. hideCoinsGlobally()
  763. })
  764. ifSettingIsEnabled('useDefaultBootLabel', function() {
  765. createSelector(".BootTimeLabel", "z-index:50;");
  766. }, function() {
  767. createSelector(".BootTimeLabel", "color:white !important;font-weight:normal!important;font-style:italic;font-size:13px!important;z-index:50;");
  768. })
  769.  
  770. ifSettingIsEnabled("hideRefreshButton", function() {
  771. createSelector("#refreshAll", "display: none");
  772. })
  773.  
  774. ifSettingIsEnabled("highlightTournaments", function() {
  775. createSelector("#MyTournamentsTable tbody", "background:#4C4C33;");
  776. })
  777.  
  778. ifOneOrMoreIsEnabled(["hidePromotedGames", "hideCoinsGlobally"], function() {
  779. createSelector("#PromotedGamesTable", "display:none");
  780. })
  781.  
  782. ifSettingIsEnabled("hideMyGamesIcons", function() {
  783. createSelector("#MyGamesTable td div img, #MyGamesTable td div a img", "display:none;");
  784. })
  785.  
  786. ifSettingIsEnabled("scrollGames", function() {
  787. setupFixedWindowWithScrollableGames();
  788. }, function() {
  789. createSelector(".SideColumn", "padding-top: 22px;")
  790. createSelector("body", "overflow: auto")
  791. createSelector("#MainSiteContent > table", "width: 100%;max-width: 1400px;")
  792. addCSS(`
  793. @media (max-width: 1050px) {
  794. #MyGamesTable > thead > tr * {
  795. font-size: 14px;
  796. }
  797. #MyGamesTable > thead > tr > td > div:nth-of-type(1) {
  798. margin-top: 5px!important;
  799. display: block;
  800. float: left;
  801. padding-right: 5px;
  802. }
  803. }
  804.  
  805. @media (max-width: 750px) {
  806. #MyGamesTable > thead > tr > td > div:nth-of-type(1) {
  807. display:none;
  808. }
  809. }`)
  810. }, function() {
  811. setupRightColumn(true);
  812. refreshOpenGames();
  813. setupOpenGamesFilter();
  814. })
  815.  
  816. ifSettingIsEnabled("hideRightColumn", function() {
  817. hideRightColumn();
  818. })
  819.  
  820. $("label[for='MultiDayRadio']").on("click", function () {
  821. registerGameTabClick()
  822.  
  823. });
  824.  
  825. $("label[for='RealTimeRadio']").on("click", function () {
  826. registerGameTabClick()
  827. });
  828.  
  829. $("label[for='BothRadio']").on("click", function () {
  830. registerGameTabClick()
  831. });
  832.  
  833. $(window).resize(function () {
  834. ifSettingIsEnabled("scrollGames", function() {
  835. refreshSingleColumnSize();
  836. }, undefined, function() {
  837. makePopupVisible()
  838. })
  839. });
  840.  
  841. window.setTimeout(setupRefreshFunction, 00);
  842. updateTotalPointsEarned()
  843.  
  844. } else {
  845. ifSettingIsEnabled('hideCoinsGlobally', function() {
  846. hideCoinsGlobally();
  847. })
  848. }
  849. setupBurn();
  850. }
  851.  
  852. function setupSettingsDatabase() {
  853. if(WLJSDefined()){
  854. warlight_shared_viewmodels_WaitDialogVM.Start("Setting up Muli's Userscript...")
  855. }
  856. var promises = [];
  857. $.each(userscriptSettings, function(key, set) {
  858. promises[key] = $.Deferred();
  859. var setting = {
  860. name: set.id,
  861. value: set.selected
  862. }
  863. Database.update(Database.Table.Settings, setting, undefined, function() {
  864. promises[key].resolve();
  865. })
  866. })
  867. $.when.apply($, promises).done(function () {
  868. sessionStorage.setItem("showUserscriptMenu", true)
  869. window.setTimeout(window.location.reload(), 2000)
  870. })
  871. }
  872.  
  873. function hideCoinsGlobally() {
  874. $("#CoinsBtn").parent().next().css('left', 512);
  875. $("#CoinsBtn").parent().next().next().css('left', 635);
  876. $("#CoinsBtn").parent().next().next().next().css('left', 740);
  877.  
  878. $("#LeaderboardTable").prev().remove();
  879. $("#LeaderboardTable").css({
  880. opacity: 0,
  881. cursor: 'default'
  882. });
  883. $("#LeaderboardTable a").css('display', 'none');
  884. $(".TopRightBar").find("a[href='/Coins/']").css('display', 'none');
  885. $(".dropdown-menu a[href='/Coins/']").parent().remove()
  886.  
  887. $("a[href='/Win-Money']").css('display', 'none');
  888.  
  889. $("#OpenTournamentsTable").css('display', 'none');
  890. }
  891.  
  892. /**
  893. * Creates the Userscript-Menu
  894. */
  895. function setupUserscriptMenu() {
  896.  
  897. var inputs = '';
  898.  
  899. $.each(userscriptSettings, function (key, setting) {
  900. if (setting.title != '') {
  901. inputs += `<span class="title">${setting.title}</span><br>`;
  902. }
  903. var help = setting.help != undefined ? '<img src="' + IMAGES.QUESTION + '" class="help-icon" onclick=\'showSettingHelp("' + setting.id + '", this)\'>' : ''
  904. inputs += '<label for="_' + setting.id + '">' + setting.text + help + '</label>' + '<input type="checkbox" id="' + setting.id + '"><br>';
  905. if (setting.addBreak) {
  906. inputs += '<hr>';
  907. }
  908. });
  909.  
  910. inputs += '<div class="close-userscript">Close and Refresh</div>';
  911. $("body").append('<ul class="custom-menu"><div class="content"></div></ul>');
  912. $("body").append("<div class='overlay' style='display: none'></div><div class='popup popup600 userscript-show' style='display: none'><div class='head'>Change Userscript Settings " + GM_info.script.version + "<img class='close-popup-img' src='" + IMAGES.CROSS + "' height='25' width='25'></div>" + inputs + "</div>");
  913. $(".userscript-show").on("change", function () {
  914. storeSettingsVariables();
  915. });
  916. $("#TopRightDropDown .dropdown-divider").before('<li><div class="userscript-menu">Muli\'s Userscript</div></li>');
  917.  
  918. $(".userscript-menu").on("click", function () {
  919. showUserscriptMenu()
  920. });
  921.  
  922. $(".close-userscript").on("click", function () {
  923. $(".userscript-show").fadeOut();
  924. $(".overlay").fadeOut();
  925. location.reload();
  926. });
  927.  
  928. $(".close-popup-img").on("click", function () {
  929. $(".userscript-show").fadeOut();
  930. $(".overlay").fadeOut();
  931. $("embed#main").css('opacity', '1');
  932. });
  933. $("#hideRightColumn").after('<button id="sortTables">Sort Right Column Tables</button><br>')
  934. // $("#hideRightColumn").after('<button id="sortTables" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button"><span class="ui-button-text">Sort Right Column Tables</span></button>')
  935. createSelector("#sortTables","margin-top: 5px")
  936. $("#sortTables").on("click", function() {
  937. showSortTables()
  938. })
  939. $("#snowLight").after('<button id="resetHiddenThreads" style="float: left; margin: 10px 5px">Reset Hidden Threads</button>')
  940. $("#snowLight").after('<button id="exportSettings" style="float: left; margin: 10px 5px">Export Settings</button><br>')
  941. $("#snowLight").after('<button id="showImportSettings" style="float: left; margin: 10px 5px">Import Settings</button>')
  942. $("body").append("<div class='popup popup600 exportSettings-show' style='display: none'><div class='head'>Export Settings <img class='close-popup-img' src='" + IMAGES.CROSS + "' height='25' width='25'></div>Copy or download this text and save it somwhere on your computer!<br><br><textarea id='exportSettingsBox'></textarea><a id='downloadExportSettingsFile' href='' download='tuyd_settings.txt'>Download Text-File</a></div>");
  943. $("body").append("<div class='popup popup600 importSettings-show' style='display: none'><div class='head'>Export Settings <img class='close-popup-img' src='" + IMAGES.CROSS + "' height='25' width='25'></div><textarea id='importSettingsBox' placeholder='Copy settings here'></textarea><button id='importSettings'>Import Settings</button></div>");
  944. createSelector("#exportSettingsBox, #importSettingsBox", "width:100%; height: 300px")
  945. $("#exportSettings").on("click", function() {
  946. exportSettings();
  947. })
  948. $("#showImportSettings").on("click", function() {
  949. showPopup('.importSettings-show');
  950. })
  951. $("#importSettings").on("click", function() {
  952. importSettings();
  953. })
  954. $("#resetHiddenThreads").on("click", function() {
  955. window.undoIgnore();
  956. })
  957. getSortTables(function(tables){
  958. var tableCode = ''
  959. $.each(tables, function(key, table) {
  960. tableCode += '<div class="sortableLadder ' + (table.hidden ? 'tableSortHidden' : '') +'" data-name="' + table.name + '" data-tableId="' + table.id + '">' + table.name + '<div class="tableSortNavigation"><span class="tableSortUp">▲</span><span class="tableSortDown">▼</span><span class="tableSortHideShow"><img src="' + IMAGES.EYE + '"></span></div></div>'
  961. })
  962. createSelector(".sortableLadder", "border: 1px gray solid;margin: 5px;padding: 5px;background-color:rgb(25, 25, 25);")
  963. createSelector(".tableSortNavigation", "display: inline-block;float: right;margin-top: -2px;")
  964. createSelector(".tableSortNavigation span", "padding: 3px 10px; cursor: pointer")
  965. createSelector(".tableSortNavigation span:hover", "color: #C0D0FF")
  966. createSelector(".sortTableHighlight", "background-color: rgb(60, 60, 60)")
  967. createSelector(".tableSortHideShow img", "height: 10px")
  968.  
  969. createSelector(".tableSortHidden", "opacity: 0.2;")
  970.  
  971.  
  972.  
  973. $("body").append(' <div class="popup popup600" id="sortTablePopup" style="display:none;margin-top: 150px; width: 500px; margin-left: -282px;"><div class="head" style=" margin-top: 152px;width:560px;">Sort Tables<img class="close-popup-img" src="' + IMAGES.CROSS + '" height="25" width="25"></div>' + tableCode +' <div class="close-userscript" onclick="window.saveTableSort()">Save & Refresh</div></div>')
  974. $(".close-popup-img").unbind();
  975. $(".close-popup-img").on("click", function () {
  976. $(".popup").fadeOut();
  977. $(".overlay").fadeOut();
  978. });
  979.  
  980. $(".tableSortUp").on("click", function() {
  981. $(".sortTableHighlight").removeClass("sortTableHighlight")
  982. var table = $(this).closest(".sortableLadder")
  983. table.addClass("sortTableHighlight")
  984.  
  985. var prev = table.prev()
  986. table = table.detach()
  987. prev.before(table)
  988. })
  989.  
  990. $(".tableSortDown").on("click", function() {
  991. $(".sortTableHighlight").removeClass("sortTableHighlight")
  992. var table = $(this).closest(".sortableLadder")
  993. table.addClass("sortTableHighlight")
  994.  
  995. var next = table.next()
  996. table = table.detach()
  997. next.after(table)
  998. })
  999.  
  1000. $(".tableSortHideShow").on("click", function() {
  1001. $(".sortTableHighlight").removeClass("sortTableHighlight")
  1002. var table = $(this).closest(".sortableLadder")
  1003. table.addClass("sortTableHighlight")
  1004. table.toggleClass("tableSortHidden")
  1005. })
  1006.  
  1007. checkUserscriptMenuButtons();
  1008. })
  1009.  
  1010. }
  1011.  
  1012. function updateTotalPointsEarned() {
  1013. var pointsEarned = {
  1014. name: "totalPoints",
  1015. value: warlight_shared_points_PointValues.Get(warlight_shared_viewmodels_SignIn.get_CurrentPlayer().Level).RawPoints + warlight_shared_viewmodels_SignIn.get_CurrentPlayer().PointsThisLevel
  1016. }
  1017. Database.update(Database.Table.Settings, pointsEarned, undefined, function() {
  1018. })
  1019. }
  1020.  
  1021. function importSettings() {
  1022. var deferredCount = 0;
  1023. var resolvedCount = 0;
  1024. var clearPromises = [];
  1025. $.each(Database.Table, function(key, table) {
  1026. clearPromises[deferredCount++] = $.Deferred();
  1027. Database.clear(table, function() {
  1028. clearPromises[resolvedCount++].resolve();
  1029. })
  1030. })
  1031. warlight_shared_viewmodels_WaitDialogVM.Start("Importing Settings...")
  1032. $(".popup").fadeOut();
  1033. var settings = $("#importSettingsBox").val().trim();
  1034. // try {
  1035. // settings = JSON.parse((atob(settings)))
  1036. // for (x in settings) {
  1037. // localStorage.setItem(settings[x].id, decodeURI(settings[x].value))
  1038. // }
  1039. // window.location.reload();
  1040. // } catch (e) {
  1041. // log(e)
  1042. // warlight_shared_viewmodels_WaitDialogVM.Stop();
  1043. // $(".overlay").fadeOut();
  1044. // warlight_shared_viewmodels_AlertVM.DoPopup("There was an error importing the settings.");
  1045. // }
  1046. $.when.apply($, clearPromises).done(function () {
  1047. var deferredCount = 0;
  1048. var resolvedCount = 0;
  1049. var promises = [];
  1050. try {
  1051. settings = JSON.parse(atob(settings))
  1052. $.each(settings, function(key, data) {
  1053. var table = data.table
  1054. var content = data.data
  1055. $.each(content, function(key, value){
  1056. promises[deferredCount++] = $.Deferred();
  1057. Database.add(table, value, function() {
  1058. promises[resolvedCount++].resolve();
  1059. })
  1060. })
  1061. })
  1062. $.when.apply($, promises).done(function () {
  1063. window.location.reload();
  1064. })
  1065. } catch (e) {
  1066. log(e)
  1067. warlight_shared_viewmodels_WaitDialogVM.Stop();
  1068. $(".overlay").fadeOut();
  1069. warlight_shared_viewmodels_AlertVM.DoPopup("There was an error importing the settings.");
  1070. }
  1071. });
  1072. }
  1073.  
  1074. function exportSettings() {
  1075. var settings = [];
  1076. var deferredCount = 0;
  1077. var resolvedCount = 0;
  1078. var promises = [];
  1079. $.each(Database.Exports, function (key, table) {
  1080. promises[deferredCount++] = $.Deferred();
  1081. Database.readAll(table, function(data) {
  1082. settings.push({table: table, data: data})
  1083. promises[resolvedCount++].resolve();
  1084. })
  1085. })
  1086. $.when.apply($, promises).done(function () {
  1087. var settingsString = btoa(JSON.stringify(settings))
  1088. $("#exportSettingsBox").html(settingsString)
  1089. showPopup(".exportSettings-show");
  1090. $("#exportSettingsBox").focus();
  1091. $("#exportSettingsBox").select();
  1092. $("#downloadExportSettingsFile").click(function(){
  1093. this.href = "data:text/plain;charset=UTF-8," + settingsString;
  1094. });
  1095. });
  1096. }
  1097.  
  1098.  
  1099. function showUserscriptMenu() {
  1100. showPopup(".userscript-show")
  1101. $("#TopRightDropDown").fadeOut();
  1102. $("embed#main").attr('wmode', 'transparent');
  1103. $("embed#main").css('opacity', '0');
  1104. $("embed#main").attr('align', 'left');
  1105. }
  1106.  
  1107. function showPopup(selector) {
  1108. if($(selector).length > 0) {
  1109. $(".popup").fadeOut();
  1110. $(selector).fadeIn();
  1111. $(".overlay").fadeIn();
  1112. makePopupVisible();
  1113. }
  1114. }
  1115.  
  1116. function makePopupVisible() {
  1117. if($(".popup600:visible").offset() && $(".popup600:visible").offset().top + $(".popup600:visible").height() + 150 > $(window).height() || ($(".popup600:visible").offset() && $(".popup600:visible").offset().top < 100)) {
  1118. $(".popup600:visible").css("margin-top", $(window).height() - 250 - $(".popup600:visible").height())
  1119. $(".popup600:visible .head").css("margin-top", $(window).height() - 250 - $(".popup600:visible").height() + 2)
  1120. }
  1121. }
  1122.  
  1123. function getSortTables(callback) {
  1124. var defaultTables =
  1125. [
  1126. {id: "#BookmarkTable", name: "Bookmarks", hidden: false, order: 0},
  1127. {id: "#LeagueTable", name: "Community Events", hidden: false, order: 1},
  1128. {id: "#MyTournamentsTable", name: "Tournaments", hidden: false, order: 2},
  1129. {id: "#RealTimeLadderTable", name: "Real-Time Ladder", hidden: false, order: 3},
  1130. {id: "#MapOfTheWeekTable", name: "Map of the Week", hidden: false, order: 4},
  1131. {id: "#ForumTable", name: "Forum Posts", hidden: false, order: 5},
  1132. {id: "#ClanForumTable", name: "Clan Forum Posts", hidden: false, order: 6},
  1133. {id: "#BlogTable", name: "Recent Blog Posts", hidden: false, order: 7},
  1134. {id: "#LeaderboardTable", name: "Coin Leaderboard", hidden: false, order: 8}
  1135. ]
  1136. if($("#ShopTable").length > 0) {
  1137. defaultTables.push({id: "#ShopTable", name: "WarLight Shop", hidden: false, order: -1})
  1138. }
  1139. Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "tableSort", function(tableData) {
  1140. if(tableData && tableData.value.length > 3) {
  1141. var tables = tableData.value;
  1142. if($("#ShopTable").length > 0 && !arrayHasObjWithId(tables, "#ShopTable")) {
  1143. tables.push({id: "#ShopTable", name: "WarLight Shop", hidden: false, order: -1})
  1144. }
  1145. if(!arrayHasObjWithId(tables, "#LeagueTable")) {
  1146. tables.push( {id: "#LeagueTable", name: "Community Events", hidden: false, order: 1});
  1147. }
  1148. callback($(tables).sort(compareTable));
  1149. } else {
  1150. callback($(defaultTables).sort(compareTable))
  1151. }
  1152. })
  1153. }
  1154.  
  1155. function arrayHasObjWithId(arr, id) {
  1156. var found = false;
  1157. $.each(arr, function(key, val) {
  1158. if(val.id == id) {
  1159. found = true;
  1160. }
  1161. })
  1162. return found;
  1163. }
  1164.  
  1165. window.saveTableSort = function() {
  1166. var tables = []
  1167. $.each($("#sortTablePopup > div.sortableLadder"), function(key, table) {
  1168. var order = key
  1169. var id = $(table).attr('data-tableId')
  1170. var hidden = $(table).hasClass("tableSortHidden")
  1171. var name = $(table).attr('data-name')
  1172. tables.push({id: id, name: name, hidden: hidden, order: order})
  1173. })
  1174. var tableSort = {
  1175. name: "tableSort",
  1176. value: tables
  1177. }
  1178. Database.update(Database.Table.Settings, tableSort, undefined, function() {
  1179. $("#sortTablePopup").fadeOut();
  1180. $(".overlay").fadeOut();
  1181. refreshOpenGames();
  1182. })
  1183. }
  1184.  
  1185. function showSortTables() {
  1186. $(".popup").fadeOut();
  1187. showPopup("#sortTablePopup")
  1188. }
  1189.  
  1190. function compareTable(a,b) {
  1191. if (a.order < b.order)
  1192. return -1;
  1193. if (a.order > b.order)
  1194. return 1;
  1195. return 0;
  1196. }
  1197.  
  1198. function showInfo(text, x, y) {
  1199. window.setTimeout(function () {
  1200. if (!$(".custom-menu").is(':visible')) {
  1201. $(".custom-menu .content").html(text);
  1202. $(".custom-menu").finish().toggle(100).
  1203.  
  1204. // In the right position (the mouse)
  1205. css({
  1206. top: x + "px",
  1207. left: y + "px"
  1208. });
  1209. }
  1210.  
  1211. }, 10);
  1212. }
  1213.  
  1214. window.showSettingHelp = function (id, obj) {
  1215. var help = '';
  1216. $.each(userscriptSettings, function (key, setting) {
  1217. if (setting.id == id) {
  1218. help = setting.help;
  1219. }
  1220. });
  1221. var x = $(obj).offset().top;
  1222. var y = $(obj).offset().left;
  1223. showInfo(help, x, y);
  1224.  
  1225.  
  1226. }
  1227.  
  1228. function checkUserscriptMenuButtons() {
  1229. $.each(userscriptSettings, function (key, set) {
  1230. Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, set.id, function(setting) {
  1231. if(setting){
  1232. $("#" + setting.name).prop("checked", setting.value);
  1233. } else {
  1234. $("#" + set.id).prop("checked", set.selected);
  1235. }
  1236. })
  1237. });
  1238. }
  1239.  
  1240. function StickyTitles(stickies) {
  1241. var thisObj = this;
  1242. thisObj.load = function () {
  1243. stickies.each(function () {
  1244. var thisSticky = $(this).wrap('<div class="followWrap" />');
  1245. thisSticky.parent().height(thisSticky.outerHeight());
  1246. var pos = parseInt(thisSticky.offset().top, 10) - parseInt($(".showSide").offset().top, 10);
  1247. $.data(thisSticky[0], 'pos', pos);
  1248. });
  1249. $(".showSide").off("scroll.stickies").on("scroll.stickies", function () {
  1250. thisObj.scroll();
  1251. });
  1252. };
  1253.  
  1254. thisObj.scroll = function () {
  1255. stickies.each(function (i) {
  1256. var thisSticky = $(this),
  1257. nextSticky = stickies.eq(i + 1),
  1258. prevSticky = stickies.eq(i - 1),
  1259. pos = $.data(thisSticky[0], 'pos');
  1260. var showSide = $(".showSide");
  1261. if (pos <= showSide.scrollTop()) {
  1262. thisSticky.addClass("fixed");
  1263. if (nextSticky.length > 0 && thisSticky.offset().top >= $.data(nextSticky[0], 'pos') - thisSticky.outerHeight()) {
  1264. thisSticky.addClass("absolute").css("top", jQuery.data(nextSticky[0], 'pos') - thisSticky.outerHeight());
  1265. }
  1266. } else {
  1267. thisSticky.removeClass("fixed");
  1268. if (prevSticky.length > 0 && showSide.scrollTop() <= $.data(thisSticky[0], 'pos') - prevSticky.outerHeight()) {
  1269. prevSticky.removeClass("absolute").removeAttr("style");
  1270. }
  1271. }
  1272. });
  1273. }
  1274. }
  1275.  
  1276. /**
  1277. * Stores User-Settings to local Storage
  1278. */
  1279. function storeSettingsVariables() {
  1280. $.each(userscriptSettings, function (key, set) {
  1281. var isEnabled = $("#" + set.id).prop("checked");
  1282. var setting = {
  1283. name: set.id,
  1284. value: isEnabled
  1285. }
  1286. Database.update(Database.Table.Settings, setting, undefined, function() {
  1287. })
  1288. });
  1289.  
  1290. }
  1291.  
  1292. /**
  1293. * Refreshes Width & Height of Columns
  1294. */
  1295. function refreshSingleColumnSize() {
  1296. var showSide = $(".showSide");
  1297. var showGames = $(".showGames");
  1298. showSide.scrollTop(0);
  1299. /**
  1300. * Sticky Titles
  1301. */
  1302. $(".followMeBar").each(function () {
  1303. $(this).removeClass("fixed");
  1304. if ($(this).parent().hasClass("followWrap")) {
  1305. $(this).unwrap();
  1306. }
  1307. var thisSticky = $(this).wrap('<div class="followWrap" />');
  1308. thisSticky.parent().height(thisSticky.outerHeight());
  1309. var pos = parseInt(thisSticky.offset().top) - parseInt(showSide.offset().top);
  1310. $.data(thisSticky[0], 'pos', pos);
  1311. });
  1312. var width = $("#ForumTable").width();
  1313. createSelector(".followMeBar", "width:" + width + "px;");
  1314.  
  1315. showGames.find("table").css({
  1316. height: window.innerHeight - 150
  1317. });
  1318.  
  1319. //var height = showGames.find("table thead tr").height() + 30;
  1320. var height = 48;
  1321. createSelector(".showGames table tbody tr:first-of-type td", "padding-top:" + height + "px");
  1322.  
  1323.  
  1324. showSide.css({
  1325. height: window.innerHeight - 150
  1326. });
  1327. showGames.find("table tbody tr:first-of-type td").css("padding-top", height);
  1328. $(".showGames thead tr").width($(".showGames thead tr").closest("table").width()-30)
  1329. $(".showGames thead tr td div").unwrap();
  1330. }
  1331.  
  1332. /**
  1333. * Create a CSS selector
  1334. * @param name The name of the object, which the rules are applied to
  1335. * @param rules The CSS rules
  1336. */
  1337. function createSelector(name, rules) {
  1338. var style = document.createElement('style');
  1339. style.type = 'text/css';
  1340. document.getElementsByTagName('head')[0].appendChild(style);
  1341. if (!(style.sheet || {}).insertRule) {
  1342. (style.styleSheet || style.sheet).addRule(name, rules);
  1343. } else {
  1344. style.sheet.insertRule(name + "{" + rules + "}", 0);
  1345. }
  1346. }
  1347. /**
  1348. * Reloads all Games
  1349. */
  1350. function refreshAllGames(force) {
  1351. log("Reloading Games")
  1352. if ($(".popup").is(":visible") && !force) {
  1353. return;
  1354. }
  1355. ifSettingIsEnabled('scrollGames', function() {
  1356. openGamesTable.scrollTop(0);
  1357. myGamesTable.scrollTop(0);
  1358. promotedGamesTable.scrollTop(0);
  1359. })
  1360.  
  1361. $('table').css('overflow-y', 'hidden')
  1362. refreshMyGames();
  1363. refreshOpenGames();
  1364. refreshPromotedGames();
  1365. }
  1366.  
  1367. function setupCustomSort(cb) {
  1368. Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "customSort", function(sort) {
  1369. sortType = (sort != undefined && sort.value != undefined) ? sort.value : 1;
  1370. $("#myGamesSortContainer").remove();
  1371. var target;
  1372. ifSettingIsEnabled("scrollGames", function() {
  1373. target = $($("#MyGamesTable thead tr").find("*")[0]);
  1374. }, function() {
  1375. target = $($("#MyGamesTable thead tr td").find("*")[0]);
  1376. }, function() {
  1377. target.after('<div id="myGamesSortContainer" style="display:inline-block;float:right">Sort: <select id="myGamesSort" style="letter-spacing: 0px;margin-top: 5px;"> <option value="1" ' + (sortType == 1 ? 'selected' : '') + '>Default</option><option value="4" ' + (sortType == 4 ? 'selected' : '') + '>Default - Show time left</option> <option value="3" ' + (sortType == 3 ? 'selected' : '') +'>By time left</option><option value="2"' + (sortType == 2 ? 'selected' : '') +'>By time left - Ignore chat</option> </select></div>')
  1378. sessionStorage.setItem("customSort", sortType)
  1379.  
  1380. $("#myGamesSort").on("change", function() {
  1381. var sortType = $(this).val();
  1382. sessionStorage.setItem("customSort", sortType)
  1383. var sort = {
  1384. name: "customSort",
  1385. value: sortType
  1386. }
  1387. Database.update(Database.Table.Settings, sort, undefined, function() {
  1388.  
  1389. })
  1390. refreshMyGames();
  1391. })
  1392. if(sortType != 1) {
  1393. log("Reloading: custom sort set to " + sortType)
  1394. cb();
  1395. } else {
  1396. log("Not reloading: custom sort set to " + sortType)
  1397. }
  1398. })
  1399. })
  1400. }
  1401.  
  1402. function refreshMyGames(data) {
  1403. log("refreshing games")
  1404. myGamesTable.find("tbody").fadeTo('fast', 0.15);
  1405. var filter = $("#MyGamesFilter").val() || 4;
  1406. wljs_Jsutil.Post("?", "FilterChange=" + filter, function (a) {
  1407. var myGames = wljs_Jsutil.GamesFromDump(a);
  1408. renderMyGames(myGames)
  1409. });
  1410. }
  1411.  
  1412. Array.prototype.diff = function(a) {
  1413. return this.filter(function(i) {return a.indexOf(i) < 0;});
  1414. };
  1415.  
  1416. function renderMyGames(myGames) {
  1417. removeMyGames()
  1418. var sortType = sessionStorage.getItem("customSort")
  1419. if(sortType != 1 && sortType != 4) {
  1420. myGames.sort(gameSort)
  1421. }
  1422. var dueGames = myGames.filter(function(a) {
  1423. var game = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, a, warlight_shared_viewmodels_SignIn.get_CurrentPlayer())
  1424. return (game != null) && (game.UsOpt != null) && !game.UsOpt.HasCommittedOrders && (game.Game.State == 3 || game.Game.State == 5) && game.UsOpt.State == 2
  1425. })
  1426. if (myGames.length == 0) {
  1427. d.append('<tr><td colspan="2" style="color: #C1C1C1">' + warlight_shared_viewmodels_main_MultiPlayerDashboardVM.NoGamesHtml(0) + "</td></tr>");
  1428. } else {
  1429. //Render MyGames
  1430. for (var f = 0; f < myGames.length;) {
  1431. var g = myGames[f];
  1432. ++f;
  1433. g = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, g, warlight_shared_viewmodels_SignIn.get_CurrentPlayer());
  1434. d.append(warlight_shared_viewmodels_main_MultiPlayerDashboardVM.RenderGameHtml(warlight_shared_viewmodels_ConfigurationVM.Settings, g, null))
  1435. }
  1436. //Make player boxes also clickable
  1437. $.each($(".GameRow"), function(key, row) {
  1438. var href = $(this).find("a").attr("href");
  1439. var children = $(this).find("td:nth-of-type(2) > span:nth-of-type(1)");
  1440. var style = "display: inline-block;max-width: 400px;margin: 4px 0px;float: none;position: relative;font-size:10pt!important;white-space:normal;height:initial";
  1441.  
  1442. children.wrapInner("<a/>").children(0).unwrap().attr("style", style).attr("href", href)
  1443. })
  1444. //Setup time left in GameRow
  1445. if(sortType != 1) {
  1446. $.each(dueGames, function(key, game) {
  1447. var id = game.GameID
  1448. var timeLeft = Math.min(game.AutoBoot._totalMilliseconds, game.VoteToBoot._totalMilliseconds, game.DirectBoot._totalMilliseconds) - game.WaitingFor._totalMilliseconds
  1449. var bootTime = new Date().getTime() + parseInt(timeLeft)
  1450. $("[gameid='" + id + "']").find("td div + span").append(`<span data-boottime="${bootTime}" data-inline> (${getTimeLeft(timeLeft)} left)</span>`)
  1451.  
  1452. })
  1453. }
  1454. //Setup time left tooltip
  1455. $.each(myGames, function(key, game) {
  1456. var id = game.GameID
  1457. var timeLeft = Math.min(game.AutoBoot._totalMilliseconds, game.VoteToBoot._totalMilliseconds, game.DirectBoot._totalMilliseconds) - game.WaitingFor._totalMilliseconds;
  1458. var bootTime = new Date().getTime() + parseInt(timeLeft)
  1459. var label = $("[gameid='" + id + "']").find(".BootTimeLabel")
  1460.  
  1461. if(timeLeft > 0) {
  1462. label.attr("title", getTimeLeft(timeLeft, true) + " left")
  1463. } else {
  1464. var overTime = game.WaitingFor._totalMilliseconds - Math.min(game.AutoBoot._totalMilliseconds, game.VoteToBoot._totalMilliseconds, game.DirectBoot._totalMilliseconds);
  1465. label.attr("title", "Time over since " + getTimeLeft(overTime, true))
  1466. }
  1467. label.tooltip({ show: {delay: 100}, hide: 100 });
  1468. label.attr("data-boottime", bootTime)
  1469. })
  1470. //Setup NextGameId
  1471. var nextGameIds = [];
  1472. $.each(myGames, function(key, game) {
  1473. var id = game.GameID
  1474. if(gameCanBeNextGame(game)){
  1475. nextGameIds.push(id)
  1476. }
  1477. })
  1478. $.each(myGames, function(key, game) {
  1479. var id = game.GameID
  1480. if(nextGameIds.length > 0 && nextGameIds[0]) {
  1481. var ids = [];
  1482. var url = "https://www.warlight.net/MultiPlayer?GameID=" + id + (nextGameIds.length > 1 ? ("&NextGameIDs=" + nextGameIds.slice(1, nextGameIds.length).join()) : "");
  1483. $("[gameid='" + id + "'] td > a").attr("href", url)
  1484. nextGameIds.push(nextGameIds.shift())
  1485. }
  1486. })
  1487. }
  1488. myGamesTable.find("tbody").fadeTo('fast', 1, function () {
  1489. myGamesTable.css('overflow-y', 'scroll');
  1490. });
  1491. $(window).trigger('resize');
  1492. }
  1493.  
  1494. function removeMyGames() {
  1495. d = $("#MyGamesTable").children("tbody");
  1496. d.children().remove();
  1497. }
  1498.  
  1499. function setMyGamesTimeLeft() {
  1500. $.each($("[data-boottime]"), function(key, target) {
  1501. var timeLeft = $(target).attr("data-boottime") - new Date().getTime()
  1502. if($(target).is("[data-inline]")) {
  1503. $(target).text(` (${getTimeLeft(timeLeft)} left)`)
  1504. } else {
  1505. // $(target).tooltip( "option", "content", getTimeLeft(timeLeft, true) + " left")
  1506. }
  1507. })
  1508. }
  1509.  
  1510. function getTimeLeft(time, detailed) {
  1511. var hours1 = 1 * 60 * 60 * 1000
  1512. var hours5 = 5 * 60 * 60 * 1000
  1513. var days5 = 5 * 25 * 60 * 60 * 1000
  1514. var secs = time / 1000
  1515. var mins = secs / 60
  1516. var hours = mins / 60
  1517. var days = hours / 24
  1518. if(time < 0) {
  1519. return "Hurry up! No time"
  1520. } else if(time < hours1) {
  1521. var m = Math.round(Math.floor(mins) % 60);
  1522. var s = Math.round(Math.floor(secs) % 60);
  1523. return m > 0 ? (m + (m == 1 ? " minute " : " minutes ")) : "" + s + (s == 1 ? " second" : " seconds")
  1524. } else if(time < hours5) {
  1525. var m = Math.round(Math.floor(mins) % 60)
  1526. var h = Math.floor(hours);
  1527. return h + (h == 1 ? " hour " : " hours ") + m + (m == 1 ? " minute" : " minutes")
  1528. } else if(time < days5 && !detailed) {
  1529. var d = Math.floor(days)
  1530. var h = Math.round(Math.floor(hours) % 24)
  1531. return (d > 0 ? d + (d == 1 ? " day " : " days ") : "") + h + (h == 1 ? " hour" : " hours")
  1532. } else if(time >= days5 && !detailed) {
  1533. return Math.round(days) + " days "
  1534. } else if(detailed) {
  1535. var d = Math.floor(days)
  1536. var h = Math.round(Math.floor(hours) % 24)
  1537. var m = Math.round(Math.floor(mins) % 60)
  1538. return (d > 0 ? d + (d == 1 ? " day " : " days ") : "") + h + (h == 1 ? " hour " : " hours ") + m + (m == 1 ? " minute" : " minutes")
  1539. } else {
  1540. return "undefined left " + time
  1541. }
  1542. }
  1543.  
  1544. function gameSort(a,b){
  1545. var sortType = sessionStorage.getItem("customSort")
  1546. var gameA = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, a, warlight_shared_viewmodels_SignIn.get_CurrentPlayer())
  1547. var gameB = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, b, warlight_shared_viewmodels_SignIn.get_CurrentPlayer())
  1548. var aRealTime = gameA.Game.RealTimeGame
  1549. var aPlaying = (gameA.Game.State == 3 || gameA.Game.State == 5) && gameA.UsOpt.State == 2
  1550. var aPrio0 = gameA.Game.PrivateMessagesWaiting || gameA.Game.PublicChatWaiting || gameA.Game.TeamChatWaiting
  1551. var aPrio1 = gameA.Game.State == 2 && gameA.UsOpt.State == 1 //Waiting to join
  1552. var aPrio4 = gameA.Game.State == 2 && gameA.Game.WaitingForYouToStart //Waiting for you to start
  1553. var aPrio3 = aPlaying && !gameA.UsOpt.HasCommittedOrders //Your turn 3 = turn, 5 = picking
  1554. var aBootTime = Math.min(a.AutoBoot._totalMilliseconds, a.VoteToBoot._totalMilliseconds, a.DirectBoot._totalMilliseconds) - a.WaitingFor._totalMilliseconds
  1555.  
  1556. var bRealTime = gameB.Game.RealTimeGame
  1557. var bPlaying = (gameB.Game.State == 3 || gameB.Game.State == 5) && gameB.UsOpt.State == 2
  1558. var bPrio0 = gameB.Game.PrivateMessagesWaiting || gameB.Game.PublicChatWaiting || gameB.Game.TeamChatWaiting
  1559. var bPrio1 = gameB.Game.State == 2 && gameB.UsOpt.State == 1
  1560. var bPrio4 = gameB.Game.State == 2 && gameB.Game.WaitingForYouToStart
  1561. var bPrio3 = bPlaying && !gameB.UsOpt.HasCommittedOrders
  1562. var bBootTime = Math.min(b.AutoBoot._totalMilliseconds, b.VoteToBoot._totalMilliseconds, b.DirectBoot._totalMilliseconds) - b.WaitingFor._totalMilliseconds
  1563.  
  1564. if(aRealTime && !bRealTime) return -1;
  1565. if(bRealTime && !aRealTime) return 1;
  1566. if(sortType == 3) {
  1567. if(aPrio0 && !bPrio0) return -1;
  1568. if(bPrio0 && !aPrio0) return 1;
  1569. }
  1570.  
  1571. if(aPrio1 && !bPrio1) return -1;
  1572. if(bPrio1 && !aPrio1) return 1;
  1573.  
  1574. if(aPrio3 && !bPrio3) return -1;
  1575. if(bPrio3 && !aPrio3) return 1;
  1576. if(aPlaying && !bPlaying) return -1;
  1577. if(bPlaying && !aPlaying) return 1;
  1578.  
  1579. if(aPrio3 && bPrio3) return aBootTime - bBootTime;
  1580. if(aPrio4 && !bPrio4) return -1;
  1581. if(bPrio4 && !aPrio4) return 1;
  1582. return a.WaitingFor - b.WaitingFor
  1583. }
  1584.  
  1585. function gameCanBeNextGame(g) {
  1586. var game = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, g, warlight_shared_viewmodels_SignIn.get_CurrentPlayer())
  1587.  
  1588. if(game != null && game.Game != null && game.UsOpt != null) {
  1589. var playing = (game.Game.State == 3 || game.Game.State == 5) && game.UsOpt.State == 2
  1590. var prio0 = game.Game.PrivateMessagesWaiting || game.Game.PublicChatWaiting || game.Game.TeamChatWaiting
  1591. var prio1 = game.Game.State == 2 && game.UsOpt.State == 1 //Waiting to join
  1592. var prio3 = playing && !game.UsOpt.HasCommittedOrders //Your turn 3 = turn, 5 = picking
  1593. var prio4 = game.Game.State == 2 && game.Game.WaitingForYouToStart //Waiting for you to start
  1594.  
  1595. return prio0 || prio1 || prio3 || prio4
  1596. } else {
  1597. return false;
  1598. }
  1599. }
  1600.  
  1601.  
  1602. function refreshOpenGames() {
  1603. deletedMD = deletedRT = 0;
  1604. openGamesTable.find("tbody").fadeTo('fast', 0.15);
  1605. var page = $('<div />').load('https://www.warlight.net/MultiPlayer/ ', function () {
  1606. var data = page.find('#AllOpenGamesData').html();
  1607. $('#AllOpenGamesData').html(data);
  1608. WL_MPDash.OpenGamesCtrl.AllOpenGamesData = data
  1609. Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "openGamesFilters", function(filters) {
  1610. var openGamesFilters;
  1611. if(filters) {
  1612. openGamesFilters = filters.value;
  1613. }
  1614. var games;
  1615. if (openGamesFilters && openGamesFilters["disableAll"] != true) {
  1616. games = filterGames(wljs_Jsutil.GamesFromDump(data), openGamesFilters);
  1617. } else {
  1618. games = wljs_Jsutil.GamesFromDump(data);
  1619. }
  1620. $.each(games, function (key, game) {
  1621. if ($(game).playerJoined()) {
  1622. games[key] = $(game).markJoined();
  1623. }
  1624. });
  1625.  
  1626.  
  1627. wljs_AllOpenGames = WL_MPDash.OpenGamesCtrl.AllOpenGames = games;
  1628.  
  1629. var RealTimeLadderTable = page.find("#RealTimeLadderTable tbody tr:first-of-type").outerHTML();
  1630. $("#RealTimeLadderTable tbody tr:first-of-type")
  1631. $("#RealTimeLadderTable tbody tr:first-of-type").replaceWith(RealTimeLadderTable)
  1632.  
  1633. replaceAndFilterForumTable(page.find("#ForumTable").outerHTML());
  1634. $("#ClanForumTable").replaceWith(page.find("#ClanForumTable").outerHTML())
  1635. setupRightColumn()
  1636.  
  1637. updateOpenGamesCounter();
  1638.  
  1639. wljs_AllOpenGamesData = wljs_multiplayer_Ctrl_AllOpenGamesData = data;
  1640. var player = warlight_shared_viewmodels_SignIn.get_CurrentPlayer();
  1641. if ((new js.JQuery(this.BothRadio)).is(":checked")) {
  1642. player.OpenGamePreference = 1;
  1643. } else if ((new js.JQuery(this.MultiDayRadio)).is(":checked")) {
  1644. player.OpenGamePreference = 2;
  1645. } else if ((new js.JQuery(this.RealTimeRadio)).is(":checked")) {
  1646. player.OpenGamePreference = 3;
  1647. }
  1648. wljs_Jsutil.Post("/MultiPlayer/", "ChangePace=" + player.OpenGamePreference, function (a) {});
  1649.  
  1650.  
  1651. var a = $("#OpenGamesTable").children("tbody");
  1652. a.children().remove();
  1653.  
  1654. var gamesToShow = warlight_shared_viewmodels_main_MultiPlayerDashboardVM.GamesToShow(wljs_AllOpenGames, player.OpenGamePreference, 0 == this.ShowingAllOpenGames)
  1655. for (var b = 0; b < gamesToShow.length;) {
  1656. var game = gamesToShow[b];
  1657. b++;
  1658. game.get_IsLottery() && warlight_shared_viewmodels_main_MultiPlayerDashboardVM.get_HideLotteryGames() ||
  1659. (game = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 2, game, warlight_shared_viewmodels_SignIn.get_CurrentPlayer()), a.append(warlight_shared_viewmodels_main_MultiPlayerDashboardVM.RenderGameHtml(warlight_shared_viewmodels_ConfigurationVM.Settings, game, null)))
  1660. }
  1661. openGamesTable.find("tbody").fadeTo('fast', 1, function () {
  1662. openGamesTable.css('overflow-y', 'scroll');
  1663. });
  1664. addOpenGamesSuffix();
  1665. domRefresh();
  1666. })
  1667. });
  1668. }
  1669. var refreshingPromotedGames = false;
  1670. function refreshPromotedGames() {
  1671. if(!refreshingPromotedGames) {
  1672. refreshingPromotedGames = true;
  1673. promotedGamesTable.find("tbody").fadeTo('fast', 0.15);
  1674. var page = $('<div />').load('https://www.warlight.net/MultiPlayer/ ', function () {
  1675. var data = page.find('#MorePromotedGamesData').html();
  1676. $('#MorePromotedGamesData').html(data);
  1677. wljs_PromotedGames = wljs_Jsutil.GamesFromDump(data);
  1678. refreshingPromotedGames = false;
  1679. var a = $("#PromotedGamesTable").children("tbody");
  1680. a.children().remove();
  1681. for (var b = 0; b < wljs_PromotedGames.length;) {
  1682. var game = wljs_PromotedGames[b];
  1683. b++;
  1684. (game = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 2, game, warlight_shared_viewmodels_SignIn.get_CurrentPlayer()), a.append(warlight_shared_viewmodels_main_MultiPlayerDashboardVM.RenderGameHtml(warlight_shared_viewmodels_ConfigurationVM.Settings, game, null)))
  1685. }
  1686. domRefresh();
  1687. promotedGamesTable.find("tbody").fadeTo('fast', 1, function () {
  1688. promotedGamesTable.css('overflow-y', 'scroll');
  1689. });
  1690.  
  1691. });
  1692. } else {
  1693. log("refreshing promoted blocked")
  1694. }
  1695. }
  1696.  
  1697.  
  1698. /**
  1699. * Setups the refresh functionality
  1700. */
  1701. function setupRefreshFunction() {
  1702. lastRefresh = new Date();
  1703. var oldRefreshBtn = $("#RefreshBtn");
  1704. var oldRefreshBtn2 = $("#RefreshBtn2");
  1705. if (oldRefreshBtn.length) {
  1706. var newRefreshBtn = $("#refreshAll");
  1707. oldRefreshBtn.replaceWith(oldRefreshBtn.clone().removeAttr("id").attr("id", "refreshAll").attr("value", "Refresh (R)"));
  1708. newRefreshBtn.appendTo("body");
  1709. $("#refreshAll").on("click", function () {
  1710. if (new Date() - lastRefresh > 3000) {
  1711. lastRefresh = new Date();
  1712. log("Refresh by click")
  1713. refreshAllGames();
  1714. }
  1715. });
  1716. } else if (oldRefreshBtn2.length) {
  1717. var newRefreshBtn = $("#refreshAll");
  1718. oldRefreshBtn2.replaceWith(oldRefreshBtn2.clone().removeAttr("id").attr("id", "refreshAll").attr("value", "Refresh (R)"));
  1719. newRefreshBtn.appendTo("body");
  1720. $("#refreshAll").on("click", function () {
  1721. if (new Date() - lastRefresh > 3000) {
  1722. lastRefresh = new Date();
  1723. log("Refresh by click")
  1724. refreshAllGames();
  1725. }
  1726. });
  1727. }
  1728.  
  1729. $(".MainColumn").prepend($('#refreshAll'))
  1730.  
  1731. ifSettingIsEnabled('autoRefreshOnFocus', function() {
  1732. $(window).on('focus', function () {
  1733. if (new Date() - lastRefresh > 30000) {
  1734. lastRefresh = new Date();
  1735. log("Refresh by focus")
  1736. refreshAllGames();
  1737. }
  1738. });
  1739. })
  1740.  
  1741. $("body").keyup(function (event) {
  1742. // "R" is pressed
  1743. if (event.which == 82) {
  1744. if (new Date() - lastRefresh > 3000) {
  1745. lastRefresh = new Date();
  1746. log("Refresh by key r")
  1747. refreshAllGames();
  1748. }
  1749. }
  1750. });
  1751. }
  1752.  
  1753.  
  1754. function getDate(text) {
  1755. var date;
  1756.  
  1757. if (text.match(/[0-9]+ second/)) {
  1758. date = new Date() - 1000;
  1759.  
  1760. } else if (text.match(/[0-9]+ seconds/)) {
  1761. date = new Date() - text.match(/[0-9]+/) * 1000;
  1762.  
  1763. } else if (text.match(/[0-9]+ minute/)) {
  1764. date = new Date() - text.match(/[0-9]+/) * 1000 * 60;
  1765.  
  1766. } else if (text.match(/[0-9]+ minutes/)) {
  1767. date = new Date() - text.match(/[0-9]+/) * 1000 * 60;
  1768.  
  1769. } else if (text.match(/[0-9]+ hour/)) {
  1770. date = new Date() - text.match(/[0-9]+/) * 1000 * 60 * 59;
  1771.  
  1772. } else if (text.match(/[0-9]+ hours/)) {
  1773. date = new Date() - text.match(/[0-9]+/) * 1000 * 60 * 60;
  1774.  
  1775. } else if (text.match(/[0-9]+ day/)) {
  1776. date = new Date() - text.match(/[0-9]+/) * 1000 * 60 * 60 * 36;
  1777.  
  1778. } else if (text.match(/[0-9]+ days/)) {
  1779. date = new Date() - text.match(/[0-9]+/) * 1000 * 60 * 60 * 24;
  1780.  
  1781. } else if (text.match(/[0-9]+[\/][0-9]+[\/][0-9]+/)) {
  1782. var split = text.split('/');
  1783. date = new Date(split[2], split[0] - 1, split[1]);
  1784. date.setHours(0, 0, 0, 0);
  1785. }
  1786. return date;
  1787. }
  1788.  
  1789. function setGlobalStyles() {
  1790. $("tr:contains('WarLight Shop')").closest(".dataTable").attr("id", "ShopTable");
  1791. createSelector('.help-icon', 'display:inline-block;position:absolute; margin-left:10px;margin-top: 2px;cursor:pointer; height: 15px; width: 15px;')
  1792. var winHeight = $(window).height();
  1793. createSelector(".userscript-menu", "display: block;color: #555;text-decoration: none;line-height: 18px;padding: 3px 15px;margin: 0;white-space: nowrap;");
  1794. createSelector(".userscript-menu:hover", "cursor:pointer;background-color: #08C;color: #FFF;cursor: pointer;");
  1795. createSelector(".popup", "position: fixed;;left: 50%;background: #171717;top: 100px;z-index: 99; color:white;padding:60px 30px 30px 30px;border: 2px solid gray;border-radius:8px;max-height:" + (winHeight - 200) + "px;overflow-y:auto");
  1796. createSelector(".close-userscript", "margin: 40px 0;width: 100%;text-align: center;font-size: 15px;cursor: pointer;background: gray;line-height: 30px;border-radius: 8px;clear: both");
  1797. createSelector(".close-popup-img", "float:right;margin:5px;cursor:pointer;margin-right: 20px");
  1798. createSelector(".popup label", "width: 80%;display: inline-block;font-size: 15px;margin: 5px;");
  1799. createSelector(".popup .title", "color: gray;font-size: 15px;margin-top: 10px;display: inline-block;width: 95%;border-bottom: 1px gray solid;padding-bottom: 3px;");
  1800. createSelector(".popup input[type='checkbox']", "width: 20px;height: 20px;margin-left:30px;margin: 5px;-moz-appearance:none;");
  1801. createSelector(".overlay", "position: absolute;background: white;top: 0;left: 0;right: 0;bottom: 0;z-index: 98;opacity: 0.5;width: 100%;height: 100%;position: fixed;");
  1802. createSelector(".popup .head", "position: fixed;height: 40px;background: #330000;width: 660px;left: 0;right: 0;top: 100px;color: white;font-size: 15px;text-align: center;line-height: 40px;border-top-left-radius:8px;border-top-right-radius:8px;margin:auto;z-index:10000;");
  1803. createSelector(".userscript-show", "display:none");
  1804. createSelector("#MorePromotedGamesHorizontalRow", "display:none");
  1805. createSelector(".newSetting", "color: gold;font-weight: bold;");
  1806. createSelector(".userscript-menu img", "height: 18px;display: inline-block;position: relative;margin-bottom: -5px;margin-right: 7px;");
  1807. createSelector(".custom-menu", "display: none;z-index: 98;position: absolute;overflow: hidden;border: 1px solid #CCC;white-space: nowrap;font-family: sans-serif;background: #FFF;color: #333;border-radius:5px;padding: 10px;z-index:100000000; cursor:pointer");
  1808. createSelector(".custom-menu .content", "width: 300px;white-space: pre-wrap;");
  1809. createSelector('.popup input[type="text"]', 'display: inline-block;background: none;border-top: none;border-left: none;border-right: none;color: green;font-size: 15px;border-bottom: 1px white dashed;font-family: Verdana;padding: 0 5px 0 5px;text-align: center;margin-right: 5px');
  1810.  
  1811. createSelector(".popup840", "width: 840px;margin-left: -452px");
  1812. createSelector(".popup600", "width: 600px;margin-left: -332px");
  1813.  
  1814. createSelector(".popup840 .head", "width: 900px");
  1815. createSelector(".popup600 .head", "width: 660px");
  1816. createSelector(".context-menu", "display: none;z-index: 100;position: absolute;overflow: hidden;border: 1px solid #CCC;white-space: nowrap;font-family: sans-serif;background: #FFF;color: #333;border-radius: 5px;padding: 0;");
  1817. createSelector(".context-menu li", "padding: 8px 12px;cursor: pointer;list-style-type: none;");
  1818. createSelector(".context-menu li:hover", "background-color: #DEF;");
  1819. createSelector("#MyGamesTable select","margin: 0 10px 0 5px; width: 125px")
  1820. createSelector("#MyGamesFilter", "float:right")
  1821. createSelector("#MyGamesTable thead tr", "text-align: right")
  1822.  
  1823. $("body").on("click", function (e) {
  1824. if ($(".custom-menu").is(':visible')) {
  1825. $(".custom-menu").hide(100);
  1826. }
  1827. });
  1828. }
  1829.  
  1830. window.deletedRT = 0;
  1831. window.deletedMD = 0;
  1832.  
  1833. function filterGames(games, openGamesFilters) {
  1834. var filteredGames = [];
  1835. var deletedGames = [];
  1836.  
  1837. $.each(games, function (key, game) {
  1838. if (!$(game).getsFiltered(openGamesFilters)) {
  1839. filteredGames.push(game);
  1840. } else {
  1841. if (game.RealTimeGame) {
  1842. deletedRT++;
  1843. } else {
  1844. deletedMD++;
  1845. }
  1846. }
  1847. });
  1848.  
  1849. return filteredGames;
  1850. }
  1851.  
  1852.  
  1853. function storeFilterVariables() {
  1854. openGamesFilters = {};
  1855.  
  1856. $.each(filters, function (key, filter) {
  1857. if (filter.type == "checkbox") {
  1858. openGamesFilters[filter.id] = $("#" + filter.id).prop("checked");
  1859. }
  1860. });
  1861. openGamesFilters["hideKeyword"] = $("#hideKeyword").val()
  1862. openGamesFilters["hideRealTimeBootTime"] = $("#hideRealTimeBootTime").val()
  1863. openGamesFilters["hideMultiDayBootTimeDays"] = $("#hideMultiDayBootTimeDays").val()
  1864. openGamesFilters["hideMultiDayBootTimeHours"] = $("#hideMultiDayBootTimeHours").val()
  1865.  
  1866. var luck = $("#hideLuck").val();
  1867. openGamesFilters["hideLuck"] = ($.isNumeric(luck) && luck <= 100 && luck >= 0) ? luck : 100;
  1868.  
  1869. var minPlayers = $("#hideMinPlayers").val();
  1870. openGamesFilters["hideMinPlayers"] = ($.isNumeric(minPlayers) && minPlayers <= 100 && minPlayers >= 2) ? minPlayers : 2;
  1871.  
  1872. var maxPlayers = $("#hideMaxPlayers").val();
  1873. openGamesFilters["hideMaxPlayers"] = ($.isNumeric(maxPlayers) && maxPlayers <= 100 && maxPlayers >= 2) ? maxPlayers : 100;
  1874.  
  1875. if (parseFloat(openGamesFilters["hideMinPlayers"]) > parseFloat(openGamesFilters["hideMaxPlayers"])) {
  1876. openGamesFilters["hideMaxPlayers"] = openGamesFilters["hideMinPlayers"]
  1877. }
  1878.  
  1879. var rtBoot = $("#hideRealTimeBootTime").val();
  1880. openGamesFilters["hideRealTimeBootTime"] = $.isNumeric(rtBoot) ? rtBoot * 60 * 1000 : 0;
  1881.  
  1882. var mdBoot = calculateMDBoot($("#hideMultiDayBootTimeHours").val(), $("#hideMultiDayBootTimeDays").val());
  1883.  
  1884. openGamesFilters["hideMultiDayBootTimeDays"] = mdBoot.days;
  1885. openGamesFilters["hideMultiDayBootTimeHours"] = mdBoot.hours;
  1886.  
  1887. openGamesFilters["hideMultiDayBootTimeInMs"] = (parseInt(mdBoot.days) * 24 + parseInt(mdBoot.hours)) * 60 * 60 * 1000;
  1888.  
  1889. var gameFilters = {
  1890. name: "openGamesFilters",
  1891. value: openGamesFilters
  1892. }
  1893. Database.update(Database.Table.Settings, gameFilters, undefined, function() {
  1894. updateFilterSettings()
  1895. })
  1896. }
  1897.  
  1898. function calculateMDBoot(hours, days) {
  1899. hours = $.isNumeric(hours) ? hours : 0;
  1900. days = $.isNumeric(days) ? days : 0;
  1901.  
  1902. if (hours >= 24) {
  1903. days = parseFloat(days) + parseInt(hours / 24);
  1904. hours -= parseInt(hours / 24) * 24
  1905. }
  1906.  
  1907. return {
  1908. hours: hours,
  1909. days: days
  1910. }
  1911.  
  1912. }
  1913.  
  1914. function updateFilterSettings() {
  1915. Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "openGamesFilters", function(gameFilters) {
  1916. if(!gameFilters || !gameFilters.value) {
  1917. return;
  1918. }
  1919. var openGamesFilters = gameFilters.value;
  1920. $.each(filters, function (key, filter) {
  1921. if (filter.type == "checkbox") {
  1922. $("#" + filter.id).prop("checked", openGamesFilters[filter.id]);
  1923. }
  1924. });
  1925. $("#hideLuck").val(openGamesFilters["hideLuck"] || 100);
  1926. $("#hideMinPlayers").val(openGamesFilters["hideMinPlayers"] || 0);
  1927. $("#hideMaxPlayers").val(openGamesFilters["hideMaxPlayers"] || 100);
  1928. $("#hideKeyword").val(openGamesFilters["hideKeyword"] || "");
  1929. $("#hideRealTimeBootTime").val(openGamesFilters["hideRealTimeBootTime"] / 1000 / 60 || 0);
  1930. $("#hideMultiDayBootTimeDays").val(openGamesFilters["hideMultiDayBootTimeDays"] || 0);
  1931. $("#hideMultiDayBootTimeHours").val(openGamesFilters["hideMultiDayBootTimeHours"] || 0);
  1932. })
  1933. }
  1934.  
  1935. function ifSettingIsEnabled(setting, positive, negative, cb) {
  1936. Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, setting, function(setting) {
  1937. if(setting && setting.value) {
  1938. positive();
  1939. if(typeof cb == "function") {
  1940. cb();
  1941. }
  1942. } else {
  1943. if(typeof negative == 'function') {
  1944. negative();
  1945. }
  1946. if(typeof cb == 'function') {
  1947. cb();
  1948. }
  1949. }
  1950. })
  1951. }
  1952.  
  1953. function ifSettingIsNotEnabled(setting, callback) {
  1954. Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, setting, function(setting) {
  1955. if(!setting.value) {
  1956. callback();
  1957. }
  1958. })
  1959. }
  1960.  
  1961. function ifAllAreEnabled(settings, positive, negative) {
  1962. var promises = [];
  1963. var allAreEnabled = true;
  1964. $.each(settings, function (key, setting) {
  1965. promises[key] = $.Deferred();
  1966. Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, setting, function(set) {
  1967. if(!set || !set.value) {
  1968. allAreEnabled = false;
  1969. }
  1970. promises[key].resolve();
  1971. })
  1972. })
  1973. $.when.apply($, promises).done(function () {
  1974. if(allAreEnabled){
  1975. positive()
  1976. } else {
  1977. if(typeof negative == "function") {
  1978. negative();
  1979. }
  1980. }
  1981. })
  1982. }
  1983.  
  1984. function ifOneOrMoreIsEnabled(settings, positive, negative) {
  1985. var promises = [];
  1986. var isEnabled = false;
  1987. $.each(settings, function (key, setting) {
  1988. promises[key] = $.Deferred();
  1989. Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, setting, function(set) {
  1990. if(set && set.value) {
  1991. isEnabled = true;
  1992. }
  1993. promises[key].resolve();
  1994. })
  1995. })
  1996. $.when.apply($, promises).done(function () {
  1997. if(isEnabled){
  1998. positive()
  1999. } else {
  2000. if(typeof negative == "function") {
  2001. negative();
  2002. }
  2003. }
  2004. })
  2005. }
  2006.  
  2007. function pageIsMultiplayer() {
  2008. return location.href.match(/.*warlight[.]net\/MultiPlayer.*/i);
  2009. }
  2010.  
  2011. function pageIsPointsPage() {
  2012. return location.href.match(/.*warlight[.]net\/Points.*/i);
  2013. }
  2014.  
  2015. function pageIsDashboard() {
  2016. return location.href.match(/.*warlight[.]net\/MultiPlayer\/(?:#|\?|$).*$/i);
  2017. }
  2018.  
  2019. function pageIsRealTimeLadder() {
  2020. return location.href.match(/.*warlight[.]net\/LadderSeason\?ID=3.*$/i);
  2021. }
  2022.  
  2023. function pageIsProfile() {
  2024. return location.href.match(/.*warlight[.]net\/profile\?p=[0-9]+$/i);
  2025. }
  2026.  
  2027. function pageIsLevelOverview() {
  2028. return location.href.match(/.*warlight[.]net\/SinglePlayer\/Level\?ID=[0-9]+$/i);
  2029. }
  2030.  
  2031. function pageIsLevelPlayLog() {
  2032. return location.href.match(/.*warlight[.]net\/SinglePlayer\/PlayLog\?ID=[0-9]+$/i);
  2033. }
  2034.  
  2035. function pageIsMapsPage() {
  2036. return location.href.match(/.*warlight[.]net\/maps/i);
  2037. }
  2038.  
  2039. function pageIsClanThread() {
  2040. return location.href.match(/.*warlight[.]net\/Discussion/i);
  2041. }
  2042.  
  2043. function pageIsNewThread() {
  2044. return location.href.match(/.*warlight[.]net\/Forum\/NewThread.*/i);
  2045. }
  2046.  
  2047. function pageIsForumThread() {
  2048. return location.href.match(/.*warlight[.]net\/Forum\/[0-9]+.*/i);
  2049. }
  2050.  
  2051. function pageIsForumOverview() {
  2052. return location.href.match(/.*warlight[.]net\/Forum\/Forum.*/i);
  2053. }
  2054.  
  2055. function pageIsThread() {
  2056. return location.href.match(/.*warlight[.]net\/(Forum|Discussion|Clans\/CreateThread).*/i);
  2057. }
  2058.  
  2059. function pageIsSubForum() {
  2060. return location.href.match(/.*warlight[.]net\/Forum\/[A-Z]+.*/i);
  2061. }
  2062.  
  2063. function pageIsForum() {
  2064. return location.href.match(/.*warlight[.]net\/Forum\/.*/);
  2065. }
  2066.  
  2067. function pageIsLadderOverview() {
  2068. return location.href.match(/.*warlight[.]net\/Ladders/);
  2069. }
  2070.  
  2071. function pageIsLogin() {
  2072. return location.href.match(/.*warlight[.]net\/LogIn.*/);
  2073. }
  2074.  
  2075. function pageIsClanForumThread() {
  2076. return location.href.match(/.*warlight[.]net\/Discussion\/\?ID=[0-9]+.*/);
  2077. }
  2078.  
  2079. function pageIsTournament() {
  2080. return location.href.match(/.*warlight[.]net\/MultiPlayer\/Tournament\?ID=[0-9]+/i);
  2081. }
  2082.  
  2083. function pageIsTournamentOverview() {
  2084. return location.href.match(/.*warlight[.]net\/MultiPlayer\/Tournaments\/$/i);
  2085. }
  2086.  
  2087. function pageIsGame() {
  2088. return location.href.match(/.*warlight[.]net\/MultiPlayer\?GameID=[0-9]+/i);
  2089. }
  2090.  
  2091. function pageIsExamineMap() {
  2092. return location.href.match(/.*warlight[.]net\/SinglePlayer\?PreviewMap.*/i);
  2093. }
  2094.  
  2095. function pageIsDesignMap() {
  2096. return location.href.match(/.*warlight[.]net\/MultiPlayer\?DesignMaps.*/i);
  2097. }
  2098.  
  2099. function pageIsCommonGames() {
  2100. return location.href.match(/.*warlight[.]net\/CommonGames\?p=[0-9]+$/i);
  2101. }
  2102.  
  2103. function pageIsCommunityLevels() {
  2104. return location.href.match(/.*warlight[.]net\/SinglePlayer\/CommunityLevels/i);
  2105. }
  2106.  
  2107. function pageIsBlacklistPage() {
  2108. return location.href.match(/.*warlight[.]net\/ManageBlackList.*/i);
  2109. }
  2110.  
  2111. function pageIsMapPage() {
  2112. return location.href.match(/.*warlight[.]net\/Map.*/i);
  2113. }
  2114.  
  2115. function mapIsPublic() {
  2116. return $("a:contains('Start a')").length > 0;
  2117. }
  2118.  
  2119. function showOpenGamesLink() {
  2120. $("#SubTabRow td:nth-child(8)").after('<td valign="top"><img src="https://d2wcw7vp66n8b3.cloudfront.net/Images/Tabs/SubSelectedLeft.png" width="6" height="16" style="visibility: hidden"></td><td nowrap="nowrap" class="SubTabCell" id="openGamesTab"><a href="/MultiPlayer/OpenGames">Open Games</a></td><td valign="top"><img src="https://d2wcw7vp66n8b3.cloudfront.net/Images/Tabs/SubSelectedRight.png" width="6" height="16" style="visibility: hidden"></td><td width="10">&nbsp;</td>');
  2121.  
  2122. if (location.href.match(/.*warlight[.]net\/MultiPlayer\/OpenGames.*/)) {
  2123. $("#openGamesTab").addClass("SubTabCellSelected");
  2124. $("#openGamesTab").prev().children().css("visibility", "visible");
  2125. $("#openGamesTab").next().children().css("visibility", "visible");
  2126. }
  2127. }
  2128.  
  2129. function setupOpenGamesFilter() {
  2130. $("#OpenGamesTable thead tr td").prepend('<a id="editFilters" style="color:#DDDDDD;font-size: 14px;float: right;">▼</a>');
  2131.  
  2132.  
  2133. var filtersHTML = "<hr>";
  2134. $.each(filters, function (key, filter) {
  2135. if (filter.type == "checkbox") {
  2136. filtersHTML += '<div class="filterOption"><label for="' + filter.id + '">' + filter.text + '</label><input type="checkbox" id="' + filter.id + '"></div>';
  2137. } else if (filter.type == "custom") {
  2138. filtersHTML += '<div class="filterOption">' + filter.text + '</div>';
  2139. }
  2140. });
  2141.  
  2142. $("body").append("<div class='popup popup840 filters-show' style='display: none'><div class='head'>Change Filter Settings<img class='close-popup-img' src='" + IMAGES.CROSS + "' height='25' width='25'></div>" + filtersHTML + '<div class="close-userscript">Close and Apply</div></div>');
  2143.  
  2144. createSelector('hr', 'height: 1px;border: none;background-color: gray;opacity:0.5;');
  2145. createSelector('.number', 'width: 31px');
  2146. createSelector('.filterOption', 'width: 400px;float: left;margin: 5px;');
  2147. createSelector('.info', 'font-size: 12px;color: gray;border: 1px gray solid;padding: 5px;display: block;margin: 8px 0 8px 0;line-height: 20px;overflow: hidden; max-height:18px;transition:max-height 2s;-webkit-transition:max-height 2s;');
  2148. createSelector('.info:hover', 'max-height:500px');
  2149. createSelector('#hideKeyword', 'text-align: left;');
  2150. createSelector('.filter-small, .filter-small label', 'font-size: 12px!important;color: #aaa;');
  2151.  
  2152. $("#hideLuck").after("%");
  2153.  
  2154. createSelector('.ui-button-text-only .ui-button-text', 'padding: .4em 0.6em;');
  2155. createSelector('#editFilters:hover', 'cursor:pointer');
  2156.  
  2157. $(".filters-show").on("change", function () {
  2158. storeFilterVariables();
  2159. });
  2160.  
  2161. $("#editFilters").on("click", function () {
  2162. window.showFilterOptions();
  2163. });
  2164.  
  2165. $(".close-userscript").on("click", function () {
  2166. $(".filters-show").fadeOut();
  2167. $(".overlay").fadeOut();
  2168. log("Refresh by userscript settings close")
  2169. refreshAllGames(true);
  2170. });
  2171.  
  2172. $(".close-popup-img").on("click", function () {
  2173. $(".overlay").fadeOut();
  2174. $(".popup").fadeOut();
  2175. });
  2176.  
  2177. updateFilterSettings();
  2178. }
  2179.  
  2180. function setupBasicDashboardStyles() {
  2181. createSelector(".GameRow a", "font-size:16px !important;");
  2182. createSelector("a", "outline: none");
  2183. createSelector('#PromotedGamesTable td:last-of-type a img', 'display:none');
  2184. createSelector("#MyGamesTable td > a > img", 'display:none');
  2185. createSelector(".GameRow td:last-of-type span,#OpenGamesTable .GameRow td:last-of-type span:first-child, #PromotedGamesTable .GameRow td:last-of-type span:first-child", "margin:5px 0px;position:relative !important;z-index:10;");
  2186. createSelector("#MyGamesTable td span a img, #MyGamesTable td span a img", "display:inherit;");
  2187. createSelector(".GameRow:hover", "background-color:rgb(50, 50, 50);cursor:pointer;");
  2188. createSelector(".GameRow a:hover", "text-decoration:none;");
  2189. createSelector(".TournamentRow a:hover", "text-decoration:none;");
  2190. createSelector(".TournamentRow:hover", "background-color:rgb(50, 50, 50);cursor:pointer;");
  2191. createSelector(".ui-buttonset label", "font-size:11px;");
  2192. createSelector("#OpenGamesTable label:hover", " border: 1px solid #59b4d4;background: #0078a3 50% 50% repeat-x;font-weight: bold;color: #ffffff;");
  2193. createSelector("#OpenGamesTable td:last-child,#MyGamesTable td:last-child, #PromotedGamesTable td:last-child", "position: relative;");
  2194. createSelector("#OpenGamesTable td:nth-child(2) > a,#MyGamesTable td:nth-child(2) > a, #PromotedGamesTable td:nth-child(2) > a", " display: block;width: 100%;height: 100%;float: left;position: absolute;margin-top: -5px;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;");
  2195. createSelector(".loading", "position: absolute;height: 100%;width: 100%;background-color: rgba(255, 255, 255, 0.2);text-align: center;z-index: 12;margin-top: 34px;display:none;");
  2196. createSelector(".loading img", "position: absolute;top: 50%;left: 50%;margin-left: -16px;margin-top: -16px;");
  2197. createSelector("img", "position: relative;z-index:50;");
  2198. createSelector("input", "z-index: 98;position: relative;");
  2199. createSelector(".showGames thead tr", "background: rgb(51, 0, 0) none repeat scroll 0% 0%;z-index: 98;position: fixed;padding: 5px;border-bottom: 1px solid rgb(68, 68, 68);border-top-left-radius: 8px;letter-spacing: 1px;");
  2200. createSelector(".showGames table tbody", "display:table;width:100%;");
  2201. createSelector(".showGames table thead", "position:inherit;");
  2202. createSelector(".ui-tooltip", "background: #EBEBEB;padding: 4px;font-style: italic;");
  2203.  
  2204. $.each($(".TournamentRow td"), function () {
  2205. $(this).find("font:first-of-type").appendTo($(this).find("a")).css("font-size", "10px");
  2206. });
  2207. }
  2208.  
  2209. function setupFixedWindowStyles() {
  2210. createSelector('html', 'width: 100%; position:fixed')
  2211. createSelector(".followMeBar", "background: #330000;padding: 5px 0px;position: relative;z-index: 1;color: #fff;border-top-right-radius:8px;border-top-left-radius:8px;border: 1px solid gray;border-bottom:none");
  2212. var top = parseInt($(".showSide").offset().top) + parseInt(43);
  2213. createSelector(".followMeBar.fixed", "position: fixed;top: " + top + "px;z-index: 0;z-index:98;");
  2214. createSelector(".followMeBar.fixed.absolute", "position: absolute;");
  2215.  
  2216. createSelector(".showSide", "overflow-y:scroll;float: left;margin-top: 43px;padding-right: 6px;");
  2217. createSelector(".showSide thead", "display:none");
  2218. createSelector(".showSide table", "border-top-right-radius:0;border-top-left-radius:0");
  2219.  
  2220. createSelector("#switchGameRadio label", "margin-left: 6px !important");
  2221. createSelector(".showGames table", "display:block !important");
  2222. createSelector("#switchGameRadio label:hover", "border: 1px solid rgb(89, 180, 212);border-image-source: initial;border-image-slice: initial;border-image-width: initial;border-image-outset: initial;border-image-repeat: initial;background:rgb(0, 120, 163);font-weight: bold;color: rgb(255, 255, 255);");
  2223. createSelector("#MyGamesTable, #PromotedGamesTable, #OpenGamesTable", "display:none");
  2224. createSelector("#MainSiteContent > table > tbody > tr > td", "width:100%");
  2225. createSelector(".MainColumn", "width: calc(60% - 20px)!important;max-width: 800px;min-width:1px");
  2226. createSelector(".SideColumn", "float:left !important");
  2227. createSelector("h2 + span", "margin-right: 50px;");
  2228. createSelector("body", "overflow:hidden");
  2229. createSelector(".SideColumn", "width: 100% !important;");
  2230. createSelector("#MyGamesFilter", "width:200px");
  2231. createSelector(".showGames table", "display:block; overflow-y:scroll; overflow-x:hidden; border:1px gray solid; border-radius:8px");
  2232. createSelector(".adsbygoogle", "margin-top: 25px;");
  2233. createSelector(".showSide", "overflow-y:scroll;float: left;margin-top: 43px;padding-right: 6px;width:39%; min-width:1px;max-width:615px;margin-left: 20px;border-top-left-radius:8px;border-top-right-radius:8px");
  2234. createSelector("#refreshAll", "width: 140px;float: right;margin-top: 10px;");
  2235. createSelector("#fakeOpenGameMenu label", "margin-right:2px");
  2236. createSelector("#RestoreLotteryGamesBtn", "display:none");
  2237.  
  2238. createSelector('#ForumTable tbody tr td, #ClanForumTable tbody tr td', 'overflow:hidden;position:relative');
  2239. createSelector('#ForumTable tbody tr td > a, #ClanForumTable tbody tr td > a', 'width: 100%;display: block;height: 100%;float: left;position: absolute;overflow: hidden;z-index: 1;');
  2240. createSelector('#ForumTable tbody tr td span, #ClanForumTable tbody tr td span', 'display: inline-block;z-index: 1;float: left;position: relative;');
  2241. createSelector('#ForumTable tbody tr:not(:last-child):hover, #ClanForumTable tbody tr:hover', 'background-color:rgb(50, 50, 50)');
  2242.  
  2243. createSelector('#ForumTable tbody tr td a[href="/Forum/Forum"]', 'position: relative;');
  2244. createSelector('#ClanForumTable tbody tr td a[href="/Clans/Forum"]', 'position: relative;');
  2245.  
  2246. $("body").scrollTop(0)
  2247. addCSS(`
  2248. @media (max-width: 1400px) {
  2249. .showSide {
  2250. //min-width: 380px;
  2251. //width: 40%;
  2252. }
  2253. h2 + span {
  2254. margin-right: 10px!important;
  2255. }
  2256. }
  2257.  
  2258. @media (max-width: 1300px) {
  2259. #MyGamesTable > thead > tr * {
  2260. font-size: 14px;
  2261. }
  2262. #MyGamesTable > thead > tr > div:nth-of-type(1) {
  2263. margin-top: 5px!important;
  2264. display: block;
  2265. float: left;
  2266. padding-right: 5px;
  2267. }
  2268. #MyGamesTable select {
  2269. width: 110px;
  2270. }
  2271.  
  2272. }
  2273.  
  2274. @media (max-width: 1205px) {
  2275. .MainColumn {
  2276. width: 60% ;
  2277. min-width: 0;
  2278. }
  2279. #MyGamesTable select {
  2280. width: 75px;
  2281. }
  2282.  
  2283. }
  2284.  
  2285. @media (max-width: 1100px) {
  2286. #refreshAll {
  2287. width: 85px!important;
  2288. }
  2289. #MyGamesTable > thead > tr > div:nth-of-type(1) {
  2290. display: none;
  2291. }
  2292. }
  2293.  
  2294. @media (max-width: 1100px) {
  2295. .MainColumn {
  2296. float: left;
  2297. }
  2298. }
  2299. @media (max-width: 1000px) {
  2300. .showSide {
  2301. min-width:0px;
  2302. }
  2303. }
  2304. `);
  2305. }
  2306.  
  2307. function setupFixedTitlesInSideColumn() {
  2308. var blogTable = $("#BlogTable");
  2309. var realTimeLadderTable = $("#RealTimeLadderTable");
  2310. var forumTable = $("#ForumTable");
  2311. var clanForumTable = $("#ClanForumTable");
  2312. var mapOfTheWeekTable = $("#MapOfTheWeekTable");
  2313. var leaderboardTable = $("#LeaderboardTable");
  2314. var myTournamentsTable = $("#MyTournamentsTable");
  2315. var bookmarkTable = $("#BookmarkTable");
  2316.  
  2317. var shopTable = $("#ShopTable")
  2318.  
  2319. blogTable.before("<div class='followMeBar'>" + blogTable.find("thead > tr > td").html() + "</div>");
  2320. realTimeLadderTable.before("<div class='followMeBar'>" + realTimeLadderTable.find("thead > tr > td").html() + "</div>");
  2321. forumTable.before("<div class='followMeBar'>" + forumTable.find("thead > tr > td").html() + "</div>");
  2322. clanForumTable.before("<div class='followMeBar'>" + clanForumTable.find("thead > tr > td").html() + "</div>");
  2323. mapOfTheWeekTable.before("<div class='followMeBar'>" + mapOfTheWeekTable.find("thead > tr > td").html() + "</div>");
  2324. ifSettingIsEnabled("hideCoinsGlobally", function() {
  2325. }, function() {
  2326. leaderboardTable.before("<div class='followMeBar'>" + leaderboardTable.find("thead > tr > td").html() + "</div>");
  2327. }, function() {
  2328. myTournamentsTable.before("<div class='followMeBar'>" + myTournamentsTable.find("thead > tr > td").html() + "</div>");
  2329. bookmarkTable.before("<div class='followMeBar'>" + bookmarkTable.find("thead > tr > td").html() + "</div>");
  2330.  
  2331. shopTable.before("<div class='followMeBar'>" + shopTable.find("thead > tr > td").html() + "</div>");
  2332.  
  2333.  
  2334. var leagueTable = $("#LeagueTable");
  2335. leagueTable.before("<div class='followMeBar'>" + leagueTable.find("thead > tr > td").html() + "</div>");
  2336.  
  2337. new StickyTitles(jQuery(".followMeBar")).load();
  2338. })
  2339.  
  2340. }
  2341.  
  2342. function setupFixedWindowWithScrollableGames() {
  2343. var gameButtons = '<div style="margin: 10px;" id="switchGameRadio" class="ui-buttonset">';
  2344. gameButtons += '<input type="radio" id="ShowMyGames" name="switchGames" checked="checked" class="ui-helper-hidden-accessible">';
  2345. gameButtons += '<label for="ShowMyGames" class="ui-state-active ui-button ui-widget ui-state-default ui-button-text-only ui-corner-left" role="button"><span class="ui-button-text">My Games</span></label>';
  2346. ifOneOrMoreIsEnabled(["hidePromotedGames", "hideCoinsGlobally"], function() {
  2347. gameButtons += '<input type="radio" id="ShowOpenGames" name="switchGames" class="ui-helper-hidden-accessible">';
  2348. gameButtons += '<label for="ShowOpenGames" class="ui-button ui-widget ui-state-default ui-button-text-only ui-corner-right" role="button"><span class="ui-button-text">Open Games</span></label>';
  2349. gameButtons += '</div>';
  2350. setupMainColumn(gameButtons)
  2351. }, function() {
  2352. gameButtons += '<input type="radio" id="ShowOpenGames" name="switchGames" class="ui-helper-hidden-accessible">';
  2353. gameButtons += '<label for="ShowOpenGames" class="ui-button ui-widget ui-state-default ui-button-text-only" role="button"><span class="ui-button-text">Open Games</span></label>';
  2354. gameButtons += '<input type="radio" id="ShowCoinGames" name="switchGames" class="ui-helper-hidden-accessible">';
  2355. gameButtons += '<label for="ShowCoinGames" class="ui-button ui-widget ui-state-default ui-button-text-only ui-corner-right" role="button"><span class="ui-button-text">Coin Games</span></label>';
  2356. gameButtons += '</div>';
  2357. setupMainColumn(gameButtons)
  2358. })
  2359.  
  2360. }
  2361.  
  2362. function setupMainColumn(gameButtons) {
  2363. var mainColumn = $(".MainColumn ");
  2364. mainColumn.prepend('<div class="showGamesContainer">' + gameButtons + '<div class="showGames"></div></div>');
  2365. mainColumn.prepend($('#refreshAll').detach())
  2366. myGamesTable.appendTo(".showGames");
  2367.  
  2368. mainColumn.after('<div class="showSide"></div>');
  2369. $(".SideColumn").appendTo(".showSide");
  2370.  
  2371. setupFixedWindowStyles();
  2372.  
  2373. refreshSingleColumnSize();
  2374.  
  2375. $("#switchGameRadio").find("label").on("click", function () {
  2376. var newShowGames = $(this).attr("for");
  2377. if (newShowGames != showGamesActive) {
  2378. $.each($("#switchGameRadio").find("label"), function () {
  2379. $(this).removeClass("ui-state-active");
  2380. });
  2381. $(this).addClass("ui-state-active");
  2382.  
  2383. if (newShowGames == "ShowMyGames") {
  2384. showGamesActive = newShowGames;
  2385. promotedGamesTable.appendTo("body");
  2386. openGamesTable.appendTo("body");
  2387. myGamesTable.appendTo(".showGames");
  2388. } else if (newShowGames == "ShowCoinGames") {
  2389. showGamesActive = newShowGames;
  2390. myGamesTable.appendTo("body");
  2391. openGamesTable.appendTo("body");
  2392. promotedGamesTable.appendTo(".showGames");
  2393. } else if (newShowGames == "ShowOpenGames") {
  2394. showGamesActive = newShowGames;
  2395. myGamesTable.appendTo("body");
  2396. promotedGamesTable.appendTo("body");
  2397. openGamesTable.appendTo(".showGames");
  2398. }
  2399.  
  2400. refreshSingleColumnSize()
  2401. }
  2402. });
  2403. }
  2404.  
  2405. function hideRightColumn() {
  2406. ifSettingIsEnabled('scrollGames', function() {
  2407. $(".showSide").css("display", "none");
  2408. createSelector(".MainColumn", "margin: auto;max-width: 800px;width: 60%!important;float: none !important;min-width: 600px !important;");
  2409. }, function() {
  2410. $(".SideColumn").css("display", "none");
  2411. $(".MainColumn").css("width", "100%");
  2412. $(".MainColumn").css("max-width", "800px");
  2413. })
  2414. }
  2415.  
  2416. function registerGameTabClick() {
  2417. if (lastClick - new Date() > 2000) {
  2418. openGamesTable.scrollTop(0);
  2419. lastClick = new Date();
  2420. }
  2421. window.setTimeout(function () {
  2422. domRefresh();
  2423. addOpenGamesSuffix();
  2424. }, 1);
  2425. }
  2426.  
  2427. function updateOpenGamesCounter() {
  2428. var numMD = countGames(wljs_AllOpenGames, 1);
  2429. var numRT = countGames(wljs_AllOpenGames, 2);
  2430. var numBoth = parseInt(numMD) + parseInt(numRT)
  2431. //Both
  2432. $("#OpenGamesTable [for='BothRadio'] span").text('Both (' + numBoth + ')')
  2433. //Real
  2434. $("#OpenGamesTable [for='RealTimeRadio'] span").text('Real-Time (' + numRT + ')')
  2435. //Multi-Day
  2436. $("#OpenGamesTable [for='MultiDayRadio'] span").text('Multi-Day (' + numMD + ')')
  2437. }
  2438.  
  2439. // Type 1 : Multiday
  2440. // Type 2 : Realtime
  2441. function countGames(games, type) {
  2442. games = system_linq_Enumerable.Where(games, function (a) {
  2443. if (type == 1) return !a.RealTimeGame;
  2444. if (type == 2) return a.RealTimeGame;
  2445. });
  2446. return system_linq_Enumerable.ToArray(games).length
  2447. }
  2448.  
  2449. function addOpenGamesSuffix() {
  2450. var deletedBoth = parseInt(deletedMD) + parseInt(deletedRT);
  2451. $("#OpenGamesTable tbody tr:not(.GameRow)").remove();
  2452. var active = $("#OpenGamesTable .ui-buttonset .ui-state-active").text();
  2453.  
  2454. if (active.indexOf('Both') > -1 && deletedBoth > 0) {
  2455. //Both
  2456. $("#OpenGamesTable tbody").append("<tr id='gamesAreHidden' style='color: gray;font-style: italic;'><td colspan='2'>" + getNumHiddenLabelText(deletedBoth) + " <span style='float: right;cursor: pointer;font-size: 11px;margin-left: 10px;display: inline-block;margin-top: 2px;margin-right: 20px;' onclick='showFilterOptions()'>Change Filter Options</span</td></tr>");
  2457. } else if (active.indexOf('Real') > -1 && deletedRT > 0) {
  2458. //Real
  2459. $("#OpenGamesTable tbody").append("<tr id='gamesAreHidden' style='color: gray;font-style: italic;'><td colspan='2'>" + getNumHiddenLabelText(deletedRT) + " <span style='float: right;cursor: pointer;font-size: 11px;margin-left: 10px;display: inline-block;margin-top: 2px;margin-right: 20px;' onclick='showFilterOptions()'>Change Filter Options</span</td></tr>");
  2460. } else if (active.indexOf('Multi') > -1 && deletedMD > 0) {
  2461. //Multi-Day
  2462. $("#OpenGamesTable tbody").append("<tr id='gamesAreHidden' style='color: gray;font-style: italic;'><td colspan='2'>" + getNumHiddenLabelText(deletedMD) + " <span style='float: right;cursor: pointer;font-size: 11px;margin-left: 10px;display: inline-block;margin-top: 2px;margin-right: 20px;' onclick='showFilterOptions()'>Change Filter Options</span</td></tr>");
  2463. }
  2464.  
  2465. }
  2466.  
  2467. function getNumHiddenLabelText(num) {
  2468. return num == 1 ? "1 Game is hidden" : (num + " Games are hidden");
  2469. }
  2470.  
  2471.  
  2472. function loadPrivateNotes() {
  2473. log("Loading private notes")
  2474. $("#FeedbackMsg").after('<div class="profileBox" id="privateNotes"><h3>Private Notes</h3><p style="width: 285px;overflow:hidden" class="content">Loading Privates Notes..</p></div>');
  2475. var url = $("img[alt='Private Notes']").parent()[0].href;
  2476. var page = $('<div />').load(url, function () {
  2477. var notes = page.find('#PostForDisplay_0').html().trim();
  2478. if (notes) {
  2479. $('#privateNotes .content').html(notes);
  2480. } else {
  2481. $('#privateNotes .content').html('You don\'t have any Private Notes.');
  2482. }
  2483.  
  2484. });
  2485. }
  2486.  
  2487. window.showFilterOptions = function () {
  2488. showPopup(".filters-show")
  2489. }
  2490.  
  2491. function domRefresh() {
  2492. $("body").hide(0).show(0);
  2493. $(window).trigger('resize')
  2494. }
  2495.  
  2496. window.showFilterHelp = function (text, obj) {
  2497. window.setTimeout(function () {
  2498. if (!$(".custom-menu").is(':visible')) {
  2499. $(".custom-menu .content").html(text);
  2500. $(".custom-menu").finish().toggle(100).
  2501.  
  2502. // In the right position (the mouse)
  2503. css({
  2504. top: $(obj).offset().top + "px",
  2505. left: $(obj).offset().left + "px"
  2506. });
  2507. }
  2508.  
  2509. }, 10);
  2510. }
  2511.  
  2512. function setupBookmarkMenu() {
  2513. bookmarkBody = "<label for='bookmarkName'>Name</label><input style='width:100%;color: lightgray;text-align: left;' type='text' id='bookmarkName'><br><br><label for='bookmarkURL'>Url</label><input style='width:100%; text-align: left; color: lightgray' id='bookmarkURL' type='text'><br><br><label for='bookmarkNewWindow'>Open in new Window</label><input style='float:left;' id='bookmarkNewWindow' type='checkbox'>";
  2514.  
  2515. $("body").append("<div class='popup popup600' id='bookmarkMenu' style='display: none; margin-top: 150px;width:500px; margin-left:-282px'><div class='head' style=' margin-top: 152px;width:560px;'>Add Bookmark<img class='close-popup-img' src='" + IMAGES.CROSS + "' height='25' width='25'></div>" + bookmarkBody + "<div class='close-userscript' onclick='saveBookmark()'>Add Bookmark</div></div>");
  2516.  
  2517. $("bookmarkMenu").append('<div id="bookmarkMenu"></div>');
  2518.  
  2519. $(".close-popup-img").on("click", function () {
  2520. $(".popup").fadeOut();
  2521. $(".overlay").fadeOut();
  2522. });
  2523. createSelector(".highlightedBookmark", "background-color:rgb(50, 50, 50);cursor:pointer;");
  2524. $("body").append("<ul class='context-menu bookmark-context'><li onclick='editBookmark()'>Edit</li><li onclick='moveBookmarkUp()'>Move up</li><li onclick='moveBookmarkDown()'>Move Down</li></ul>")
  2525. $("body").append("<ul class='context-menu thread-context'><li onclick='hideThread()'>Hide</li></ul>")
  2526. $("body").append("<ul class='context-menu playersearch-context'><li onclick='findMostCommonGames()'>Most Common Games (Friends)</li></ul>")
  2527. bindCustomContextMenu()
  2528.  
  2529. }
  2530.  
  2531. function setupBookmarkTable() {
  2532. $(".SideColumn").prepend('<table class="dataTable" cellspacing="0" width="100%" id="BookmarkTable" style="text-align: left;"><thead><tr><td style="text-align: center">Bookmarks<img src="' + IMAGES.PLUS + '" width="15" height="15" onclick="showAddBookmark()"style="display:inline-block;float:right; opacity: 0.6; margin-right:15px; cursor: pointer"></td></tr></thead></table><br>');
  2533.  
  2534. refreshBookmarks();
  2535. bindBookmarkTable();
  2536. }
  2537.  
  2538. function refreshBookmarks() {
  2539. Database.readAll(Database.Table.Bookmarks, function(bookmarks) {
  2540. $("#BookmarkTable tbody tr").remove();
  2541. bookmarks.sort(function(a, b) {return a.order - b.order})
  2542. var data = "<tbody>";
  2543. $.each(bookmarks, function (key, bookmark) {
  2544. data += '<tr data-bookmarkId="' + bookmark.id + '" data-order="' + bookmark.order + '"><td><a ' + (bookmark.newWindow ? 'target="_blank"' : "") + ' href="' + bookmark.url + '">' + bookmark.name + '</a>';
  2545. data += '<a onclick="deleteBookmark(' + bookmark.id + ')" style="display:inline-block;float:right; opacity: 0.6;cursor: pointer;margin-right:5px">';
  2546. data += '<span class="ui-icon ui-icon-trash"></span></a></td></tr>';
  2547. })
  2548.  
  2549. $("#BookmarkTable").prepend(data + '</tbody>');
  2550. warlight_shared_viewmodels_WaitDialogVM.Stop()
  2551. $(".loader").fadeOut("fast", function() {
  2552. if($(".loader")) {
  2553. $(".loader").remove();
  2554. window.timeUserscriptReady = new Date().getTime();
  2555. log("Time userscript ready " + (timeUserscriptReady - timeUserscriptStart) / 1000)
  2556. }
  2557. })
  2558. })
  2559.  
  2560. }
  2561.  
  2562. window.bookmarkOrder;
  2563. window.bookmarkId;
  2564. window.showAddBookmark = function () {
  2565. showPopup("#bookmarkMenu")
  2566. bookmarkId = undefined
  2567. bookmarkOrder = undefined
  2568. }
  2569.  
  2570. window.editBookmark = function () {
  2571. Database.read(Database.Table.Bookmarks, bookmarkId, function(bookmark) {
  2572. $("#bookmarkURL").val(bookmark.url);
  2573. $("#bookmarkName").val(bookmark.name);
  2574. $("#bookmarkNewWindow").prop("checked", bookmark.newWindow);
  2575. showPopup("#bookmarkMenu");
  2576. })
  2577. }
  2578.  
  2579. window.moveBookmarkUp = function() {
  2580. Database.readAll(Database.Table.Bookmarks, function(bookmarks) {
  2581. var bookmark;
  2582. var newIdx = -1
  2583. $.each(bookmarks, function (key, bm) {
  2584. if (bookmarkId == bm.id) {
  2585. bookmark = bm
  2586. }
  2587. })
  2588. bookmarks.sort(function(a,b){return a.order - b.order});
  2589. var previousBookmark1 = bookmarks[bookmarks.indexOf(bookmark) - 1]
  2590. var previousBookmark2 = bookmarks[bookmarks.indexOf(bookmark) - 2] || {order: 0}
  2591. if(previousBookmark1) {
  2592. bookmark.order = (previousBookmark1.order + previousBookmark2.order) / 2
  2593.  
  2594. Database.update(Database.Table.Bookmarks, bookmark, bookmark.id, function() {
  2595. $("#bookmarkURL").val('');
  2596. $("#bookmarkName").val('');
  2597. $("#bookmarkNewWindow").prop('checked', false);
  2598. $(".overlay").fadeOut();
  2599. refreshBookmarks();
  2600. })
  2601. }
  2602. })
  2603. }
  2604.  
  2605. window.moveBookmarkDown = function() {
  2606. Database.readAll(Database.Table.Bookmarks, function(bookmarks) {
  2607. var bookmark;
  2608. var newIdx = -1
  2609. $.each(bookmarks, function (key, bm) {
  2610. if (bookmarkId == bm.id) {
  2611. bookmark = bm
  2612. }
  2613. })
  2614. bookmarks.sort(function(a,b){return a.order - b.order});
  2615. var nextBookmark1 = bookmarks[bookmarks.indexOf(bookmark) + 1]
  2616. var nextBookmark2 = bookmarks[bookmarks.indexOf(bookmark) + 2] || {order: 100000}
  2617. if(nextBookmark1) {
  2618. bookmark.order = (nextBookmark1.order + nextBookmark2.order) / 2
  2619. Database.update(Database.Table.Bookmarks, bookmark, bookmark.id, function() {
  2620. $("#bookmarkURL").val('');
  2621. $("#bookmarkName").val('');
  2622. $("#bookmarkNewWindow").prop('checked', false);
  2623. $(".overlay").fadeOut();
  2624. refreshBookmarks();
  2625. })
  2626. }
  2627. })
  2628. }
  2629.  
  2630.  
  2631. window.deleteBookmark = function (id) {
  2632. Database.delete(Database.Table.Bookmarks, id, function() {
  2633. refreshBookmarks();
  2634. })
  2635. }
  2636.  
  2637. window.saveBookmark = function () {
  2638. $("#bookmarkMenu").hide();
  2639. var url = $("#bookmarkURL").val().trim();
  2640. url = (url.lastIndexOf('http', 0) != 0) && (url.lastIndexOf('javascript', 0) != 0) ? "http://" + url : url;
  2641. var name = $("#bookmarkName").val().trim();
  2642. var newWindow = $("#bookmarkNewWindow").prop("checked");
  2643. if(bookmarkId == undefined) {
  2644. Database.readAll(Database.Table.Bookmarks, function(bookmarks) {
  2645. bookmarks.sort(function(a, b) {return a.order - b.order})
  2646. var bookmark = {
  2647. name: name,
  2648. url: url,
  2649. newWindow: newWindow,
  2650. order: (bookmarks.length > 0) ? bookmarks[bookmarks.length - 1].order + 1 : 1
  2651. }
  2652. Database.add(Database.Table.Bookmarks, bookmark, function() {
  2653. showBookmarkTable();
  2654. refreshBookmarks();
  2655. })
  2656. })
  2657. } else {
  2658. var bookmark = {
  2659. name: name,
  2660. url: url,
  2661. newWindow: newWindow,
  2662. order: bookmarkOrder
  2663. }
  2664. Database.update(Database.Table.Bookmarks, bookmark, bookmarkId, function() {
  2665. showBookmarkTable();
  2666. refreshBookmarks();
  2667. })
  2668. }
  2669. $("#bookmarkURL").val('');
  2670. $("#bookmarkName").val('');
  2671. $("#bookmarkNewWindow").prop('checked', false);
  2672. $(".overlay").fadeOut();
  2673. }
  2674.  
  2675. function hideBookmarkTable() {
  2676. $("#BookmarkTable").hide();
  2677. if ($("#BookmarkTable").prev().hasClass("followWrap")) {
  2678. $("#BookmarkTable").prev().hide();
  2679. }
  2680. if ($("#BookmarkTable").next().is('br')) {
  2681. $("#BookmarkTable").next().hide();
  2682. }
  2683. }
  2684.  
  2685. function showBookmarkTable() {
  2686. $("#BookmarkTable").show();
  2687. if ($("#BookmarkTable").prev().hasClass("followWrap")) {
  2688. $("#BookmarkTable").prev().show();
  2689. }
  2690. if ($("#BookmarkTable").next().is('br')) {
  2691. $("#BookmarkTable").next().show();
  2692. }
  2693. }
  2694.  
  2695. window.bookmarkForumThread = function () {
  2696. var title = $("title").text().replace(' - Play Risk Online Free - WarLight', '');
  2697. var url = window.location.href;
  2698.  
  2699. $("#bookmarkURL").val(url);
  2700. $("#bookmarkName").val(title);
  2701. showAddBookmark();
  2702.  
  2703. }
  2704. window.bookmarkTournament = function () {
  2705. var title = $("#TournamentName").text().replace("Tournament: ", "").trim();
  2706. var url = window.location.href;
  2707.  
  2708. $("#bookmarkURL").val(url);
  2709. $("#bookmarkName").val(title);
  2710. showAddBookmark();
  2711.  
  2712. }
  2713.  
  2714. window.bookmarkLevel = function () {
  2715. var title = $("h1").text()
  2716. var url = window.location.href;
  2717.  
  2718. $("#bookmarkURL").val(url);
  2719. $("#bookmarkName").val(title);
  2720. showAddBookmark();
  2721.  
  2722. }
  2723.  
  2724. function addDefaultBookmark() {
  2725. var bookmark = {
  2726. name: "Muli's userscript (Tidy up Your Dashboard)",
  2727. url: "https://www.warlight.net/Forum/106092-tidy-up-dashboard-2",
  2728. newWindow: false,
  2729. order: 0
  2730. }
  2731. Database.add(Database.Table.Bookmarks, bookmark, function() {
  2732. showBookmarkTable();
  2733. refreshBookmarks();
  2734. })
  2735. }
  2736.  
  2737. function setupTournamentDecline() {
  2738. $.each($(".TournamentRow"), function(key, val) {
  2739. //Waiting for accept / decline
  2740. if($(val).find("[style='color: red']:not(.BootTimeLabel)").length > 0) {
  2741. $(val).find("td:last-of-type").append('<button style="width: 100px; height: 25px;float: right" class="DeclineBtn ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button"><span class="ui-button-text">Decline</span></button>')
  2742. }
  2743. })
  2744. $(".DeclineBtn").on("click", function(e) {
  2745. var id = $(e.target).closest(".TournamentRow").attr("data-tournamentid")
  2746. warlight_shared_messages_Message.DeclineTournamentAsync(null,
  2747. warlight_shared_viewmodels_SignIn.Auth, id, null, function (b, c) {
  2748. warlight_shared_viewmodels_WaitDialogVM.Stop();
  2749. if (null != c && 129 != c.ErrorType) {
  2750. if (135 == c.ErrorType) {
  2751. warlight_shared_viewmodels_AlertVM.DoPopup("The tournament has been deleted");
  2752. } else {
  2753. throw c;
  2754. }
  2755. }
  2756. var btn = $(e.target).closest(".DeclineBtn")
  2757. $(e.target).text("Declined")
  2758. btn.attr("disabled", true).addClass("ui-state-disabled");
  2759. btn.closest(".TournamentRow").find("[style='color:red']:not(.BootTimeLabel)").remove()
  2760. Database.update(Database.Table.TournamentData, {tournamentId: Number(id), value: false, name: false}, undefined, function() {
  2761. })
  2762. }
  2763. )
  2764. })
  2765. }
  2766.  
  2767. function setupTournamentTableStyles() {
  2768. createSelector("body", "overflow: hidden")
  2769. $("#MyTournamentsTable").parent().css({
  2770. "display" : "block",
  2771. "overflow-y" : "scroll",
  2772. "border-bottom" : "1px solid #444444",
  2773. "border-top" : "1px solid #444444"
  2774. })
  2775. setTournamentTableHeight();
  2776. }
  2777.  
  2778. function updateTournamentData() {
  2779. var tournament = WL_Tournament.Tourn
  2780. var players = WL_Tournament.Players._players
  2781. var name = WL_Tournament.Tourn.Settings.Name
  2782. var id = tournament.ID
  2783. try {
  2784. Database.readIndex(Database.Table.TournamentData, Database.Row.TournamentData.Id, id, function(tourn) {
  2785. if(tourn && tourn.value) {
  2786. var details = getTournamentPlayerInfo(tournament, players, warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID)
  2787. Database.update(Database.Table.TournamentData, {tournamentId: Number(id), value: details, name: name}, undefined, function() {
  2788. })
  2789. }
  2790. })
  2791. } catch(e) {
  2792. log("Bad tournament")
  2793. log(e)
  2794. }
  2795. }
  2796.  
  2797. function setDefaultElimnatedTournamentStatus() {
  2798. ifSettingIsEnabled('hideEliminatedTournaments', function () {
  2799. $('#hideElimnatedTournaments').prop('checked', true);
  2800. hideElimatedTournaments();
  2801. })
  2802. }
  2803.  
  2804. function setupTournamentDataCheck() {
  2805. $("#MyTournamentsTable h2").after('<label id="showHideTournaments"><input id="hideElimnatedTournaments" type="checkbox" >Hide tournaments where I am eliminated</input></label>');
  2806. $("#MyTournamentsTable h2").after('<button id="dataTournamanetButton" onclick="updateAllTournamentData()">Update data</button>');
  2807. $("body").append("<div style='display:none'><div id='ShowAllBtn'></div><div id='PlayersContainer'></div></div>")
  2808. $("#MyTournamentsTable thead td").attr("colspan", 3)
  2809. $("#MyTournamentsTable tr:last td").attr("colspan", 3)
  2810. addCSS(`
  2811. #showHideTournaments, #dataTournamanetButton {
  2812. float: right;
  2813. margin: 0 10px;
  2814. }
  2815. `)
  2816. $('#hideElimnatedTournaments').change(function(){
  2817. var hideEliminatedTournaments = {
  2818. name : "hideEliminatedTournaments",
  2819. value : this.checked
  2820. }
  2821. Database.update(Database.Table.Settings, hideEliminatedTournaments, undefined, function () {})
  2822. if(this.checked) {
  2823. hideElimatedTournaments();
  2824. } else {
  2825. showElimnatedTournaments();
  2826. }
  2827. });
  2828. }
  2829.  
  2830. function loadTournamentData() {
  2831. $.each($("#MyTournamentsTable [data-tournamentid]"), function(key, row) {
  2832. if(!$(row).find("[style='color: red']:not(.BootTimeLabel)").length > 0) {
  2833. var id = $(row).attr("data-tournamentid")
  2834. Database.readIndex(Database.Table.TournamentData, Database.Row.TournamentData.Id, Number(id), function(tourn) {
  2835. if(!tourn) {
  2836. Database.update(Database.Table.TournamentData, {tournamentId: Number(id), value: "-", name: "-"}, undefined, function() {})
  2837. }
  2838. })
  2839. }
  2840. })
  2841. Database.readAll(Database.Table.TournamentData, function(tournamentDatas) {
  2842. $.each(tournamentDatas, function(key, tournamentData) {
  2843. if($(`[data-tournamentid='${tournamentData.tournamentId}']`).length) {
  2844. $(`[data-tournamentid='${tournamentData.tournamentId}']`).append(`<td class="tournamentData">${tournamentData.value ? tournamentData.value : "-"}</td>`)
  2845. } else if(tournamentData.value && tournamentData.name) {
  2846. $("#MyTournamentsTable").prepend(`<tr class="TournamentRow" data-tournament="${tournamentData.tournamentId}"><td></td><td><a style="font-size: 17px; color: white" href="https://www.warlight.net/MultiPlayer/Tournament?ID=${tournamentData.tournamentId}"> ${tournamentData.name} (finished)</a></td><td><a><button style="width: 100px; height: 25px;" class="removeTournament ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button"><span class="ui-button-text">Remove</span></button></a></td></tr>`);
  2847. }
  2848. })
  2849. $(".removeTournament").on("click", function() {
  2850. var row = $(this).closest("tr");
  2851. var id = row.attr("data-tournament")
  2852. Database.update(Database.Table.TournamentData, {tournamentId: Number(id), value: false, name: false}, undefined, function() {
  2853. row.remove();
  2854. })
  2855. })
  2856. setDefaultElimnatedTournamentStatus();
  2857. })
  2858. }
  2859.  
  2860. function showElimnatedTournaments() {
  2861. $(".TournamentRow").show();
  2862. }
  2863.  
  2864. function hideElimatedTournaments () {
  2865. $.each($("#MyTournamentsTable [data-tournamentid]"), function(key, row) {
  2866. if($(row).find(".tournamentData").text().indexOf("None") != -1) {
  2867. $(row).hide();
  2868. }
  2869. });
  2870. }
  2871.  
  2872. window.updateAllTournamentData = function() {
  2873. addCSS(`
  2874. .ui-progressbar {
  2875. position: relative;
  2876. width: 139px;
  2877. height: 20px;
  2878. float: right;
  2879. margin-right: 15px;
  2880. }
  2881. .progress-label {
  2882. position: absolute;
  2883. top: 2px;
  2884. width: 139px;
  2885. text-align: center;
  2886. }
  2887. `)
  2888. $("#dataTournamanetButton").replaceWith('<div id="progressbar"><div class="progress-label"></div></div>')
  2889. var progressbar = $( "#progressbar" );
  2890. var progressLabel = $( ".progress-label" );
  2891. var numOfMyTournaments = $("#MyTournamentsTable [data-tournamentid]").length;
  2892. progressbar.progressbar({
  2893. value: false,
  2894. change: function() {
  2895. progressLabel.text( `${Math.round(progressbar.progressbar("value") * numOfMyTournaments / 100, 0)} / ${$("#MyTournamentsTable [data-tournamentid]").length}` );
  2896. },
  2897. complete: function() {
  2898. progressLabel.text( "Done!" );
  2899. }
  2900. });
  2901. $.each($("#MyTournamentsTable [data-tournamentid]"), function(key, row){
  2902. var id = $(row).attr("data-tournamentid")
  2903. loadTournamentDetails(id, function() {
  2904. progressTournamentData(progressbar, numOfMyTournaments)
  2905. })
  2906. })
  2907. }
  2908.  
  2909. function progressTournamentData(progressbar, max) {
  2910. var val = progressbar.progressbar("value") || 0;
  2911. progressbar.progressbar("value", val + 100 / max +0.001);
  2912.  
  2913. }
  2914.  
  2915. function loadTournamentDetails(id, cb) {
  2916. $(".tournamentData").remove();
  2917. warlight_shared_messages_Message.GetTournamentDetailsAsync(null, warlight_shared_viewmodels_SignIn.Auth, id, new system_Nullable_$Float(999999999), null, function(a,b,c){
  2918. var tournament = c["Tournament"]
  2919. var name = tournament.Settings.Name
  2920. var players = new wljs_multiplayer_tournaments_display_Players(tournament)["_players"];
  2921. var details = getTournamentPlayerInfo(tournament, players, warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID)
  2922. $(`[data-tournamentid='${id}']`).append(`<td class="tournamentData">${details}</td>`)
  2923. Database.update(Database.Table.TournamentData, {tournamentId: Number(id), value: details, name: name}, undefined, function() {
  2924. })
  2925. if(cb) {
  2926. cb();
  2927. }
  2928.  
  2929. })
  2930. }
  2931.  
  2932. window.getTournamentPlayerInfo = function(tournament, players, id) {
  2933. var playerInfo = players["store"]["h"][id]
  2934. var playing = playerInfo.NumInProgress
  2935. var won = playerInfo.NumWins
  2936. var lost = playerInfo.NumLosses
  2937. var myGames = playing + won + lost
  2938. var allowVacations = tournament.Settings.AllowVacations
  2939. // 0 -> Single Elimination, 1 -> Double Elimination, 2 -> Robin Round
  2940. var tournamentType = tournament.Type
  2941. var myMaxGames;
  2942. var tournamentTotalGames;
  2943. var tournamentGamesStarted = tournament.Games.length
  2944. var teamsPerGame = tournament.TeamsPerGame.val;
  2945. var joker = 0;
  2946. if(tournamentType == 0) {
  2947. tournamentTotalGames = (Math.pow(teamsPerGame,tournament.NumberOfRoundsOrNumberOfTeams)-1)/(teamsPerGame-1);
  2948. if(lost == 1) {
  2949. myMaxGames = undefined;
  2950. } else {
  2951. myMaxGames = [0, tournament.NumberOfRoundsOrNumberOfTeams]
  2952. }
  2953. } else if(tournamentType == 1) {
  2954. tournamentTotalGames = 2*Math.pow(2, tournament.NumberOfRoundsOrNumberOfTeams)-1 ;
  2955. if(lost == 0) {
  2956. joker = 1;
  2957. }
  2958. if(lost == 2) {
  2959. myMaxGames = undefined;
  2960. } else {
  2961. myMaxGames = [0, tournament.NumberOfRoundsOrNumberOfTeams * 2]
  2962. }
  2963. } else if(tournamentType == 2) {
  2964. joker = 0;
  2965. var count = 0;
  2966. $.each(players.store.h, function(index, player) {
  2967. if(player.TP.State == 1) {
  2968. count++
  2969. }
  2970. });
  2971. myMaxGames = count / tournament.TeamSize - 1
  2972. tournamentTotalGames = (myMaxGames * myMaxGames +myMaxGames ) / 2
  2973. } else {
  2974. myMaxGames = undefined;
  2975. tournamentTotalGames = undefined;
  2976. }
  2977. var details;
  2978. if(myMaxGames == undefined) {
  2979. details = `
  2980. <font color="#858585">Won:</font> ${won} <br>
  2981. <font color="#858585">Lost:</font> ${lost} <br>
  2982. <font color="#858585">Games left:</font> None <br>
  2983. <font color="#858585">Progress: </font>${getTournamentProgress(tournamentGamesStarted, tournamentTotalGames)} <br>`
  2984. } else if(tournamentGamesStarted == 0) {
  2985. details = `
  2986. <font color="#858585">Games left:</font> ${getGamesLeftString(myGames, myMaxGames, playing, joker)} <br>
  2987. <font color="#858585">Progress: </font>Not started`
  2988. } else {
  2989. details = `
  2990. <font color="#858585">Playing:</font> ${playing} <br>
  2991. <font color="#858585">Won:</font> ${won} <br>
  2992. <font color="#858585">Lost:</font> ${lost} <br>
  2993. <font color="#858585">Games left:</font> ${getGamesLeftString(myGames, myMaxGames, playing, joker)} <br>
  2994. <font color="#858585">Progress: </font>${getTournamentProgress(tournamentGamesStarted, tournamentTotalGames)} <br>`
  2995. }
  2996. log(details)
  2997. return details;
  2998. }
  2999.  
  3000. function getTournamentProgress(tournamentGamesStarted, tournamentTotalGames) {
  3001. var progress = Math.round(tournamentGamesStarted / tournamentTotalGames * 100,0)
  3002. if(progress == 100) {
  3003. return "Almost done"
  3004. } else {
  3005. return progress + "%"
  3006. }
  3007. }
  3008.  
  3009. function getGamesLeftString(myGames, myMaxGames, playing, joker) {
  3010. if (typeof myMaxGames == "number") {
  3011. return (myMaxGames - myGames == 0 ? "None" : (myMaxGames - myGames))
  3012. } else if(typeof myMaxGames == "object") {
  3013. if(playing == 1) {
  3014. if(myMaxGames[1]-myGames == 0) {
  3015. return "None"
  3016. } else {
  3017. return (Math.max(joker, myMaxGames[0]-myGames)) + " - " + (myMaxGames[1]-myGames)
  3018. }
  3019. } else {
  3020. return (Math.max(joker + 1, myMaxGames[0]-myGames)) + " - " + (myMaxGames[1]-myGames)
  3021. }
  3022. } else {
  3023. return "undefined"
  3024. }
  3025. }
  3026.  
  3027. function setTournamentTableHeight() {
  3028. $("#MyTournamentsTable").parent().height(window.innerHeight - 100);
  3029. }
  3030.  
  3031. window.findMeIndex = -1;
  3032. window.findNextInTournament = function() {
  3033. var boxes = getPlayerBoxes();
  3034. var max = boxes.length - 1;
  3035. findMeIndex = findMeIndex == max ? 0 : findMeIndex + 1;
  3036. panzoomMatrix = undefined;
  3037. findInTournament();
  3038. }
  3039.  
  3040. function setupPlayerDataTable() {
  3041. var dataTable = $$$("#PlayersContainer > table").DataTable({
  3042. "order": [],
  3043. paging: false,
  3044. sDom: 't',
  3045. columnDefs: [ {
  3046. targets: [ 0 ],
  3047. orderData: [ 0, 3 ]
  3048. },{
  3049. targets: [ 1 ],
  3050. orderData: [ 1, 0 ]
  3051. },{
  3052. targets: [ 2 ],
  3053. orderData: [ 2, 1, 0 ],
  3054. type: "rank"
  3055. },{
  3056. targets: [ 3 ],
  3057. orderData: [ 3, 1, 0 ]
  3058. },{
  3059. targets: [ 4 ],
  3060. orderData: [ 4, 1, 0 ]
  3061. },{
  3062. targets: [ 5 ],
  3063. orderData: [ 5, 1, 0 ]
  3064. } ],
  3065. "aoColumns": [
  3066. { "orderSequence": [ "asc", "desc" ] },
  3067. { "orderSequence": [ "asc", "desc" ] },
  3068. { "orderSequence": [ "asc", "desc" ] },
  3069. { "orderSequence": [ "desc", "asc" ] },
  3070. { "orderSequence": [ "desc", "asc" ] },
  3071. { "orderSequence": [ "desc", "asc" ] },
  3072. ]
  3073. });
  3074. loadDataTableCSS();
  3075. }
  3076.  
  3077. function setupCommonGamesDataTable() {
  3078. var $$$$$ = jQuery.noConflict(true);
  3079. var dataTable = $$$("#MainSiteContent > table").DataTable({
  3080. "order": [],
  3081. paging: false,
  3082. sDom: 't',
  3083. columnDefs: [ {
  3084. targets: [ 0 ],
  3085. orderData: [ 0, 3 ]
  3086. },{
  3087. targets: [ 1 ],
  3088. orderData: [ 1, 2, 3, 0 ]
  3089. },{
  3090. targets: [ 2 ],
  3091. orderData: [ 2, 3, 0 ]
  3092. },{
  3093. targets: [ 3 ],
  3094. orderData: [ 3, 2, 0 ]
  3095. } ],
  3096. "aoColumns": [
  3097. { "orderSequence": [ "asc", "desc" ] },
  3098. { "orderSequence": [ "asc", "desc" ] },
  3099. { "orderSequence": [ "asc", "desc" ] },
  3100. { "orderSequence": [ "asc", "desc" ] },
  3101. ]
  3102. });
  3103. loadDataTableCSS();
  3104. }
  3105.  
  3106. window.setCurrentplayer = function (player, noSearch) {
  3107. window.currentPlayer = {
  3108. id: player.id,
  3109. name: player.name,
  3110. fullID: player.fullID,
  3111. team: player.team
  3112. };
  3113. $("#selectContainer").toggle(100);
  3114. $("#activePlayer").html(htmlEscape(player.name == self.name ? "Me" : player.name));
  3115. $("#playerSelectInput").val("");
  3116. panzoomMatrix = undefined;
  3117. findMeIndex = 0;
  3118. $(".gold").removeClass("gold")
  3119. $("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").addClass("gold")
  3120. $("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "'] a").addClass("gold")
  3121. if(window.WL_Tournament.Tourn.Type == 2 ) { //Robin Round
  3122. $(".TeamTip_" + (window.currentPlayer.team == "" ? window.currentPlayer.id : window.currentPlayer.team.replace("Team ", "").charCodeAt(0)-65)).addClass("gold")
  3123. } else { //Elimination Tournament
  3124. getPlayerBoxes().find("a").addClass("gold")
  3125. }
  3126. if(noSearch != true) {
  3127. window.findInTournament();
  3128. }
  3129.  
  3130. }
  3131.  
  3132. function setupTournamentFindMe() {
  3133. $("body").keyup(function (event) {
  3134. // "Left" is pressed
  3135. var boxes = getPlayerBoxes();
  3136. var max = boxes.length - 1;
  3137. if(event.which == 37) {
  3138. findMeIndex = findMeIndex == 0 ? max : findMeIndex - 1;
  3139. panzoomMatrix = undefined;
  3140. findInTournament();
  3141. }
  3142. // "Right" is pressed
  3143. else if(event.which == 39) {
  3144. findMeIndex = findMeIndex == max ? 0 : findMeIndex + 1;
  3145. panzoomMatrix = undefined;
  3146. findInTournament();
  3147. }
  3148. // "Home" is pressed
  3149. else if(event.which == 36) {
  3150. findMeIndex = 0;
  3151. panzoomMatrix = undefined;
  3152. findInTournament();
  3153. }
  3154. // "End" is pressed
  3155. else if(event.which == 35) {
  3156. findMeIndex = boxes.length - 1;
  3157. panzoomMatrix = undefined;
  3158. findInTournament();
  3159. }
  3160. });
  3161. window.players = []
  3162. $("[href='#SettingsTab']").parent().after('<li id="findMe" class="ui-state-default ui-corner-top"><div style="cursor: pointer" class="ui-tabs-anchor" onclick="window.findNextInTournament()">Find <label id="activePlayer"></labal></div><a id="showPlayerSelect">▼</a></li>');
  3163. createSelector('#findMe:hover', 'border: 1px solid #59b4d4;background: #0078a3 url("https://d2wcw7vp66n8b3.cloudfront.net/jui4/images/ui-bg_glass_40_0078a3_1x400.png") 50% 50% repeat-x;font-weight: bold;color: #ffffff;border-bottom-width: 0')
  3164. createSelector('#findMe', 'border: 1px solid #666666;border-bottom-width: 0')
  3165.  
  3166. var css = '-webkit-keyframes pulsate{ 0% { background-color: rgba(0,0,0,0); } 50% { background-color: olive; } 100% { background-color: rgba(0,0,0,0); }}@keyframes pulsate { 0% { background-color: rgba(0,0,0,0); } 50% { background-color: olive; } 100% { background-color: rgba(0,0,0,0); }}.pulsate { -webkit-animation: pulsate 1s ease-in 1; -moz-animation: pulsate 1s ease-in 1; -ms-animation: pulsate 1s ease-in 1; -o-animation: pulsate 1s ease-in 1; animation: pulsate 1s ease-in 1;}-webkit-keyframes pulsate-border{ 0% { border: 3px solid #c4c2c4; } 25% { border: 3px solid red; } 50% { border: 3px solid red; } 100% { border: 3px solid #c4c2c4; }}@keyframes pulsate-border { 0% { border: 3px solid #c4c2c4; } 25% { border: 3px solid red; }50% { border: 3px solid red; } 100% { border: 3px solid #c4c2c4; }}.pulsate-border { -webkit-animation: pulsate-border 2s ease-in 1; -moz-animation: pulsate-border 2s ease-in 1; -ms-animation: pulsate-border 2s ease-in 1; -o-animation: pulsate-border 2s ease-in 1; animation: pulsate-border 2s ease-in 1;}'
  3167. addCSS(css)
  3168.  
  3169.  
  3170. $("#findMe").append('<div id="selectContainer"><div id="playerSelectInputContainer"><input placeholder="Search a Player" type="text" id="playerSelectInput"></input></div><div id="playerContainer"></div></div>');
  3171. self = {
  3172. id: warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID,
  3173. name: warlight_shared_viewmodels_SignIn.get_CurrentPlayer().Name,
  3174. fullID: String(warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ProfileToken).substring(0, 2) + warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID + String(warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ProfileToken).substring(2, 4),
  3175. team: $("[data-playerid='" + warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID + "'] td:nth-of-type(2)").text()
  3176. };
  3177. window.setCurrentplayer(self, true);
  3178. $.each($("#PlayingPlayers tr"), function (key, playerRow) {
  3179. var id = $(playerRow).attr("data-playerid");
  3180. var fullID = $(playerRow).find("a").get($(playerRow).find("a").length - 1).href.replace(/.*warlight.net\/Profile\?p=/, "");
  3181. var name = $(playerRow).find("td a").text();
  3182. var img = $(playerRow).find("td img").attr("src");
  3183. var team = $("[data-playerid='" + id + "'] td:nth-of-type(2)").text();
  3184. if (img && img.indexOf("MemberIcon") > -1) {
  3185. img = "";
  3186. }
  3187. window.players.push({
  3188. id: id,
  3189. fullID: fullID,
  3190. name: name,
  3191. img: img,
  3192. team: team
  3193. });
  3194. });
  3195.  
  3196. $("#playerSelectInput").on('input', function (data) {
  3197. $(".playerElement").remove();
  3198. var search = $(this).val().toLowerCase();
  3199. $("#playerContainer").append("<div class='playerElement' onclick='setCurrentplayer(self)'>" + self.name + " (Me)</div>")
  3200. $.each(window.players, function (key, player) {
  3201. if (player.name.toLowerCase().indexOf(search) > -1 && self.name != player.name) {
  3202. var img = player.img ? "<img src='" + player.img + "'>" : "";
  3203. $("#playerContainer").append("<div onclick='setCurrentplayer(players[" + key + "])' class='playerElement'>" + img + "<span>" + htmlEscape(player.name) + "</span>" + "</div>")
  3204. }
  3205. });
  3206.  
  3207. $("#activePlayer").html(window.currentPlayer.name == self.name ? "Me" : window.currentPlayer.name);
  3208. $("#playerContainer").scrollTop(0)
  3209.  
  3210. });
  3211. $("#playerSelectInput").trigger("input");
  3212.  
  3213. $("#showPlayerSelect").on("click", function () {
  3214. $("#selectContainer").toggle(100);
  3215. $("#playerContainer").scrollTop(0);
  3216. $("#playerSelectInput").trigger("input");
  3217. $("#playerSelectInput").focus();
  3218. });
  3219. createSelector("#playerSelectInputContainer", "height: 28px; ");
  3220. createSelector(".border-red", "border: 3px red solid !important; ");
  3221. createSelector(".playerElement span, .playerElement img", "display:inline-block; margin-right: 10px");
  3222. createSelector("#showPlayerSelect", "color: #DDDDDD;font-size: 14px;margin: 5px 5px 0 -3px;cursor: pointer; display: inline-block;margin-right: 10px;");
  3223. createSelector("#playerSelectInput", "display: block;margin: 5px 3%;width: 93%;");
  3224. createSelector("#activePlayer", "cursor:pointer");
  3225. createSelector(".playerElement", "border-bottom: 1px gray solid;padding: 7px;color: white; clear:both; height: 14px; font-weight: normal;");
  3226. createSelector(".playerElement:hover", "background: rgb(102, 102, 102);");
  3227. createSelector("#playerContainer", "border: 2px gray solid; overflow-y: auto; overflow-x: hidden;max-height: 275px; min-width: 175px; ");
  3228. createSelector(".gold", "color: gold")
  3229. createSelector("#selectContainer", "cursor: pointer; background:rgb(23, 23, 23);position: fixed; z-index: 10;border: 2px gray solid;border-radius: 5px;box-shadow: 0 20px 50px 3px black;margin-top: 16px;display: none");
  3230. }
  3231.  
  3232.  
  3233. window.panzoomMatrix;
  3234. window.findInTournament = function () {
  3235. var id;
  3236. $("#selectContainer").hide(100);
  3237. if ($("[href='#PlayersTab']").parent().hasClass("ui-state-active")) {
  3238. id = window.currentPlayer.id;
  3239. if ($("#PlayingPlayers [data-playerid='" + id + "']").length > 0) {
  3240. var player = $("#PlayingPlayers [data-playerid='" + id + "']");
  3241. var box = $("#CenterTabs").parent()
  3242. var offset = player.offset().top - box.offset().top - box.height() / 2
  3243.  
  3244. box.stop().animate({
  3245. scrollTop: offset
  3246. }, '500', 'swing');
  3247.  
  3248. window.setTimeout(function () {
  3249. $("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").addClass("pulsate");
  3250. window.setTimeout(function () {
  3251. $(".pulsate").removeClass("pulsate");
  3252. }, 1000);
  3253. }, 250);
  3254. } else {
  3255. showInfo("You didn't join this tournament.", $("#findMe").offset().top + 25, $("#findMe").offset().left + 25);
  3256. }
  3257.  
  3258. // Elimination Tournament
  3259. } else if ($("[href='#BracketTab']").parent().hasClass("ui-state-active") && window.WL_Tournament.Tourn.Type != 2) {
  3260. id = window.currentPlayer.fullID;
  3261. //Started
  3262. if (window.WL_Tournament.Tourn.State >= 1 && $("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").length > 0) {
  3263.  
  3264. if (!panzoomMatrix) {
  3265. var currentMatrix = $("#Visualize").panzoom("getMatrix");
  3266. $("#Visualize").panzoom("reset", {
  3267. animate: false
  3268. });
  3269.  
  3270. VisualizePanzoom.panzoom("zoom", {
  3271. increment: 0.75,
  3272. animate: false
  3273. })
  3274. var boxes = getPlayerBoxes();
  3275. $(".TeamBoxHighlighted").removeClass("TeamBoxHighlighted");
  3276. boxes.addClass("TeamBoxHighlighted");
  3277. var offsetTop = $(boxes.get(findMeIndex)).offset().top - $("#VisualizeContainer").offset().top - $("#VisualizeContainer").height() / 4;
  3278. var offsetLeft = $(boxes.get(findMeIndex)).offset().left - $("#VisualizeContainer").offset().left - $("#VisualizeContainer").width() / 2;
  3279.  
  3280. $(".border-red").removeClass("border-red");
  3281. $(boxes.get(findMeIndex)).addClass("border-red");
  3282. $("#Visualize").panzoom("pan", 0 - offsetLeft, 100 - offsetTop, {
  3283. relative: true,
  3284. animate: false
  3285. });
  3286.  
  3287. panzoomMatrix = $("#Visualize").panzoom("getMatrix");
  3288. $("#Visualize").panzoom("setMatrix", currentMatrix, {
  3289. animate: false
  3290. });
  3291. }
  3292.  
  3293. window.setTimeout(function () {
  3294. $("#Visualize").panzoom("setMatrix", panzoomMatrix, {
  3295. animate: true
  3296. })
  3297. window.setTimeout(function () {
  3298. //getPlayerBoxes().addClass("pulsate-border");
  3299. window.setTimeout(function() {
  3300. $(".pulsate-border").removeClass("pulsate-border");
  3301. }, 2000)
  3302. }, 400);
  3303. }, 10)
  3304.  
  3305. } else {
  3306. showFindMeError();
  3307. }
  3308. // Robin Round Tournament
  3309. } else if ($("[href='#BracketTab']").parent().hasClass("ui-state-active") && window.WL_Tournament.Tourn.Type == 2) {
  3310. //Started
  3311. if ($("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").length > 0) {
  3312. $(".TeamTip_" + (window.WL_Tournament.Tourn.TeamSize == 1 ? window.currentPlayer.id : window.currentPlayer.team.replace("Team ", "").charCodeAt(0)-65)).addClass("pulsate")
  3313. window.setTimeout(function() {
  3314. $(".pulsate").removeClass("pulsate")
  3315. }, 2000)
  3316. } else {
  3317. showFindMeError()
  3318. }
  3319. }
  3320. }
  3321.  
  3322. function showFindMeError() {
  3323. if ($("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").length == 0) {
  3324. showInfo("You didn't join this tournament.", $("#findMe").offset().top + 25, $("#findMe").offset().left + 25);
  3325.  
  3326. } else {
  3327. showInfo("This tournament didn't start yet.", $("#findMe").offset().top + 25, $("#findMe").offset().left + 25);
  3328.  
  3329. }
  3330. }
  3331.  
  3332. function getPlayerBoxes() {
  3333. var boxes = $(".GameBox [href='/Profile?p=" + window.currentPlayer.fullID + "']").closest(".TeamBox");
  3334. if(boxes.length == 0) {
  3335. boxes = $("[title='" + window.currentPlayer.team + "']").closest(".TeamBox");
  3336. }
  3337. return boxes;
  3338. }
  3339.  
  3340. function htmlEscape(str) {
  3341. return String(str)
  3342. .replace(/&/g, '&amp;')
  3343. .replace(/"/g, '&quot;')
  3344. .replace(/'/g, '&#39;')
  3345. .replace(/</g, '&lt;')
  3346. .replace(/>/g, '&gt;');
  3347. }
  3348.  
  3349. function bindBookmarkTable() {
  3350. $("#BookmarkTable").bind("contextmenu", function (event) {
  3351. $(".highlightedBookmark").removeClass("highlightedBookmark")
  3352. var row = $(event.target).closest("tr");
  3353. bookmarkId = row.attr("data-bookmarkid")
  3354. bookmarkOrder = row.attr("data-order")
  3355. if(bookmarkId && bookmarkOrder) {
  3356. event.preventDefault();
  3357. row.addClass("highlightedBookmark")
  3358. // Show contextmenu
  3359. $(".bookmark-context").finish().toggle(100).
  3360. css({
  3361. top: event.pageY + "px",
  3362. left: event.pageX + "px"
  3363. });
  3364. }
  3365. });
  3366. }
  3367.  
  3368.  
  3369.  
  3370. function bindCustomContextMenu() {
  3371. // If the document is clicked somewhere
  3372. $(document).bind("mousedown", function (e) {
  3373.  
  3374. // If the clicked element is not the menu
  3375. if (!$(e.target).parents(".context-menu").length > 0) {
  3376.  
  3377. // Hide it
  3378. $(".context-menu").hide(100);
  3379. $(".highlightedBookmark").removeClass("highlightedBookmark")
  3380. }
  3381. });
  3382.  
  3383.  
  3384. // If the menu element is clicked
  3385. $(".context-menu li").click(function(){
  3386.  
  3387. // This is the triggered action name
  3388. switch($(this).attr("data-action")) {
  3389.  
  3390. // A case for each action. Your actions here
  3391. case "first": alert("first"); break;
  3392. case "second": alert("second"); break;
  3393. case "third": alert("third"); break;
  3394. }
  3395.  
  3396. // Hide it AFTER the action was triggered
  3397. $(".context-menu").hide(100);
  3398. });
  3399.  
  3400. }
  3401.  
  3402.  
  3403.  
  3404. function setupRealTimeLadderTable() {
  3405. if($("#RealTimeLadderTable").length == 0) {
  3406. return;
  3407. }
  3408. if( $(".extendedRTLadderRow").length == 0) {
  3409. createSelector(".extendedRTLadderRow .rtBox", "width: calc(100%/2);");
  3410. createSelector(".extendedRTLadderRow span", "");
  3411. createSelector(".rtLeft", "float:left");
  3412. createSelector(".rtRight", "float:Right");
  3413. createSelector(".rtRight a", " padding: 10px 30px;position: absolute;margin-left: -75px;");
  3414. createSelector(".newGamesRT", "display:block");
  3415. createSelector(".rtLabelBig", "font-size: 18px; margin: 5px");
  3416. }
  3417. var joinLeaveText = $(".rtRight a").text()
  3418. var joinLeaveLink = $(".rtRight a").attr("href")
  3419. $(".extendedRTLadderRow").remove();
  3420. $("#RealTimeLadderTable").append('<tr class="extendedRTLadderRow"><td colspan="2"><div class="rtLeft rtBox"><span class="newGamesRT">New Games in<br></span><div class="rtLabelBig">' + getRealTimeLadderTimerHTML() + '<a href="' + joinLeaveLink + '" class="rtLabelBig">' + joinLeaveText + '</a></div></td></tr>')
  3421. $("[href='/LadderSeason?ID=3']").text("Ladder Page")
  3422. WLPost("/LadderSeason?ID=3", "WaiterData=1", function(data) {
  3423. if(JSON.parse(data).length > 0) {
  3424. $(".rtRight a").attr("href", "https://www.warlight.net/LadderLeave?Ladder=RealTime")
  3425. $(".rtRight a").text("Leave!")
  3426. } else {
  3427. $(".rtRight a").attr("href", "https://www.warlight.net/LadderJoin?Ladder=RealTime")
  3428. $(".rtRight a").text("Join!")
  3429. }
  3430. });
  3431. setRTLadderTime()
  3432. }
  3433.  
  3434. function setupRealTimeLadderPageTimer() {
  3435. $("#LadderJoinBtn").after("<div>New Games in " + getRealTimeLadderTimerHTML() +"</div>")
  3436. $("#LeaveLadderBtn").after("<div>New Games in " + getRealTimeLadderTimerHTML() +"</div>")
  3437. setRTLadderTime()
  3438. }
  3439.  
  3440. function getRealTimeLadderTimerHTML() {
  3441. return '<span class="rtMin">00</span>:<span class="rtSec">00</span></div></div><div class="rtRight rtBox">'
  3442. }
  3443.  
  3444.  
  3445. function setRTLadderTime() {
  3446. var date = new Date()
  3447. date.setMinutes(Math.ceil((new Date().getMinutes() + date.getSeconds() / 60) / 5) * 5)
  3448. date.setSeconds(0)
  3449. var diff = (date - new Date()) / 1000
  3450. var min = Math.floor(diff / 60) % 60
  3451. diff -= min * 60
  3452. var sec = diff % 60
  3453. $(".rtMin").text(padLeft(min))
  3454. $(".rtSec").text(padLeft(sec))
  3455. }
  3456.  
  3457. function padLeft(str) {
  3458. str = Math.round(str)
  3459. len = 2
  3460. symbol = '0'
  3461. while(String(str).length < len) {
  3462. str = symbol + str;
  3463. }
  3464. return str
  3465. }
  3466.  
  3467. function setupLeagueTable() {
  3468. if($("#LeagueTable").length == 0) {
  3469. $(".SideColumn").append('<table class="dataTable" cellspacing="0" width="100%" id="LeagueTable" style="text-align: left"><thead><tr><td style="text-align: center">Community Events</td></tr></thead><tbody></tbody></table>')
  3470. }
  3471. parseLeagueTable()
  3472. loadClots()
  3473. createSelector(".clotLabel", "display: inline-block; width: 70px")
  3474. createSelector(".clotPlayers", "display: inline-block; margin-left: 5px; color:gray; ")
  3475. }
  3476.  
  3477. function setupLadderClotOverview() {
  3478. $("h1").text($("h1").text() + " & Community Events")
  3479. var clotInfo = getClots()
  3480. if(!clotInfo) {
  3481. return
  3482. }
  3483. var clots = clotInfo
  3484. var ladders = clots['leagues']
  3485. var md = ""
  3486. var rt = ""
  3487. var leagues = ""
  3488. var counter = 0
  3489. $.each(ladders, function (key, val) {
  3490. if (val.type == "realtime") {
  3491. rt += "<li><big><a target='_blank' href=" + val.url + ">" + val.name + "</a> using Real-Time boot times</big></li><br><br>"
  3492. counter++
  3493. } else if (val.type == "multiday") {
  3494. md += "<li><big><a target='_blank' href = " + val.url + ">" + val.name + "</a> using Multi-Day boot times</big></li><br><br>"
  3495. counter++
  3496. } else {
  3497. leagues += `<li><big><a target='_blank' href="${val.url}">${val.name}</a> ${getPlayerString(val.players)}</big></li><br><br>`
  3498. counter++
  3499. }
  3500. })
  3501. $("#MainSiteContent > div").append("Warlight currently has " + toWords(counter) + " Community Events:<br><br>")
  3502. $("#MainSiteContent > div").append("<ul id='clotInfo'></ul>")
  3503. $("#clotInfo").append(rt)
  3504. $("#clotInfo").append(md)
  3505. $("#clotInfo").append(leagues)
  3506. }
  3507.  
  3508. function parseLeagueTable() {
  3509. try {
  3510. var clotInfo = getClots()
  3511. if(!clotInfo) {
  3512. return
  3513. }
  3514. var ladders = clots['leagues']
  3515. var md = ""
  3516. var rt = ""
  3517. var leagues = ""
  3518. $.each(ladders, function (key, val) {
  3519. if (val.type == "realtime") {
  3520. rt += `<tr><td><a target='_blank' href="${val.url}">${val.name} (RT)</a> ${getPlayerString(val.players)}</td></tr>`
  3521. } else if (val.type == "multiday") {
  3522. md += `<tr><td><a target='_blank' href="${val.url}">${val.name} (MD)</a>${getPlayerString(val.players)}</td></tr>`
  3523. } else {
  3524. leagues += `<tr><td><a target='_blank' href="${val.url}">${val.name}</a>${getPlayerString(val.players)}</td></tr>`
  3525. }
  3526. })
  3527. $("#LeagueTable tbody tr").remove()
  3528. $("#LeagueTable tbody").append(leagues)
  3529. $("#LeagueTable tbody").append(md)
  3530. $("#LeagueTable tbody").append(rt)
  3531. $(window).trigger('resize');
  3532. } catch (e) {
  3533. log("Error reading CLOTs")
  3534. log(e.message)
  3535. hideTable("#LeagueTable")
  3536. }
  3537. }
  3538.  
  3539. function getPlayerString(players) {
  3540. if(players) {
  3541. return `<span class='clotPlayers'>${players} players participating</span>`
  3542. }
  3543. return ""
  3544. }
  3545.  
  3546. function getClots() {
  3547. try {
  3548. return clots = $.parseJSON(sessionStorage.getItem('clots'))
  3549. } catch (e) {
  3550. log("Error reading CLOTs")
  3551. log(e.message)
  3552. hideTable("#LeagueTable")
  3553. }
  3554. return undefined
  3555. }
  3556.  
  3557. function loadClots() {
  3558. $.ajax({
  3559. type: 'GET',
  3560. //url: 'https://php-psenough.rhcloud.com/hub/list.php',
  3561. //url: 'https://w115l144.hoststar.ch/test.php',
  3562. url: 'https://php-psenough.rhcloud.com/hub/list_jsonp.php',
  3563. dataType: 'jsonp',
  3564. crossDomain: true,
  3565. }).done(function(response){
  3566. try {
  3567. var json = response.data
  3568. sessionStorage.setItem('clots', JSON.stringify(json));
  3569. parseLeagueTable()
  3570. var datetime = json.datetime
  3571. log("clot update " + datetime)
  3572. } catch (e) {
  3573. log("Error parsing CLOTs")
  3574. log(e)
  3575. }
  3576. }).fail(function(e){
  3577. log("Error loading CLOTs")
  3578. log(e);
  3579. });
  3580. }
  3581.  
  3582.  
  3583. function isJson(str) {
  3584. try {
  3585. JSON.parse(str);
  3586. } catch (e) {
  3587. log(e)
  3588. return false;
  3589. }
  3590. return true;
  3591. }
  3592.  
  3593.  
  3594. function setupRightColumn(isInit) {
  3595. if(isInit) {
  3596. createSelector(".SideColumn > table", "margin-bottom: 17px;")
  3597. }
  3598. //Bookmarks
  3599. if(isInit) {
  3600. setupBookmarkTable()
  3601. } else {
  3602. refreshBookmarks()
  3603. }
  3604. //Tournament
  3605. // #MyTournamentsTable
  3606. //Clots
  3607. setupLeagueTable()
  3608. //RT Ladder
  3609. setupRealTimeLadderTable()
  3610. //Map of the Week
  3611. //Forum Posts
  3612. // hideBlacklistedThreads()
  3613. //Blog Posts
  3614. //Coin Leaderboard
  3615. sortRightColumnTables(function() {
  3616. if(isInit) {
  3617. ifSettingIsEnabled('scrollGames', function() {
  3618. setupFixedTitlesInSideColumn();
  3619. })
  3620. }
  3621. })
  3622. }
  3623.  
  3624. function sortRightColumnTables(callback) {
  3625. var sideColumn = $(".SideColumn")
  3626. getSortTables(function(tables) {
  3627. $.each(tables, function(key, table) {
  3628. if(table.hidden == true) {
  3629. hideTable(table.id)
  3630. } else {
  3631. var table = $(table.id)
  3632. if(table.prev().hasClass("followWrap")) {
  3633. var wrap = table.prev().remove()
  3634. sideColumn.append(wrap)
  3635. }
  3636. table = table.detach()
  3637. sideColumn.append(table)
  3638. }
  3639. })
  3640.  
  3641. $(".SideColumn > br").remove()
  3642. callback();
  3643. })
  3644. }
  3645.  
  3646. function toWords(number) {
  3647. var NS = [
  3648. {value: 1000000000000000000000, str: "sextillion"},
  3649. {value: 1000000000000000000, str: "quintillion"},
  3650. {value: 1000000000000000, str: "quadrillion"},
  3651. {value: 1000000000000, str: "trillion"},
  3652. {value: 1000000000, str: "billion"},
  3653. {value: 1000000, str: "million"},
  3654. {value: 1000, str: "thousand"},
  3655. {value: 100, str: "hundred"},
  3656. {value: 90, str: "ninety"},
  3657. {value: 80, str: "eighty"},
  3658. {value: 70, str: "seventy"},
  3659. {value: 60, str: "sixty"},
  3660. {value: 50, str: "fifty"},
  3661. {value: 40, str: "forty"},
  3662. {value: 30, str: "thirty"},
  3663. {value: 20, str: "twenty"},
  3664. {value: 19, str: "nineteen"},
  3665. {value: 18, str: "eighteen"},
  3666. {value: 17, str: "seventeen"},
  3667. {value: 16, str: "sixteen"},
  3668. {value: 15, str: "fifteen"},
  3669. {value: 14, str: "fourteen"},
  3670. {value: 13, str: "thirteen"},
  3671. {value: 12, str: "twelve"},
  3672. {value: 11, str: "eleven"},
  3673. {value: 10, str: "ten"},
  3674. {value: 9, str: "nine"},
  3675. {value: 8, str: "eight"},
  3676. {value: 7, str: "seven"},
  3677. {value: 6, str: "six"},
  3678. {value: 5, str: "five"},
  3679. {value: 4, str: "four"},
  3680. {value: 3, str: "three"},
  3681. {value: 2, str: "two"},
  3682. {value: 1, str: "one"}
  3683. ];
  3684.  
  3685. var result = '';
  3686. for (var n of NS) {
  3687. if(number>=n.value){
  3688. if(number<=20){
  3689. result += n.str;
  3690. number -= n.value;
  3691. if(number>0) result += ' ';
  3692. }else{
  3693. var t = Math.floor(number / n.value);
  3694. var d = number % n.value;
  3695. if(d>0){
  3696. return intToEnglish(t) + ' ' + n.str +' ' + intToEnglish(d);
  3697. }else{
  3698. return intToEnglish(t) + ' ' + n.str;
  3699. }
  3700.  
  3701. }
  3702. }
  3703. }
  3704. return result;
  3705. }
  3706.  
  3707. function hideTable(seletor) {
  3708. if( $(seletor).prev().hasClass("followWrap")) {
  3709. $(seletor).prev().remove()
  3710. }
  3711. $(seletor).remove()
  3712. }
  3713.  
  3714. window.findMostCommonGames = function() {
  3715. $("#foundPlayers").empty()
  3716. warlight_shared_viewmodels_WaitDialogVM.Start("Searching Players...")
  3717. warlight_shared_messages_Message.GetFriendsAsync(null, warlight_shared_viewmodels_SignIn.Auth, null, function (b, c, players) {
  3718. if (null != c) throw c;
  3719. var myId = warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID;
  3720. warlight_shared_SharedUtility.RemoveWhere(players, function (p) {
  3721. return p.PlayerID == myId
  3722. });
  3723. var topPlayers = [];
  3724. var limit = -1;
  3725. for (var i = 0; i < players.length; i++) {
  3726. var player = players[i];
  3727. if(player.TimesPlayedWithYou > limit || topPlayers.length < 10) {
  3728. topPlayers.push(player)
  3729. topPlayers.sort(function (p1, p2) {
  3730. return p2.TimesPlayedWithYou - p1.TimesPlayedWithYou
  3731. });
  3732. topPlayers = topPlayers.slice(0, 10);
  3733. limit = topPlayers.slice(-1)[0].TimesPlayedWithYou
  3734. }
  3735. }
  3736. warlight_shared_viewmodels_WaitDialogVM.Stop()
  3737. parseFoundFriendPlayers(topPlayers)
  3738. })
  3739. }
  3740.  
  3741. function setupDashboardSearch() {
  3742. loadDataTableCSS();
  3743. $("body").append(`<div class='popup popup840 playersearch-show' style='display: none'>
  3744. <div class='head'>Search<img class='close-popup-img' src='${IMAGES.CROSS}' height='25' width='25'></div>
  3745. <div id="searchTabs">
  3746. <ul>
  3747. <li><a href="#tabs-playerSearch">Player</a></li>
  3748. <li><a href="#tabs-clanSearch">Clan</a></li>
  3749. </ul>
  3750. <div id="tabs-playerSearch">
  3751.  
  3752. <input placeholder='Player Name' id='playerSearchQuery'>
  3753. <button id='searchPlayerBtn'>Search</button>
  3754. <div class='playerSearchTypeSelect'>
  3755. <label for='playerSearchFriend'>Friends</label>
  3756. <input type='radio' id='playerSearchFriend' name='playerSearchType' value='playerSearchFriend' >
  3757. <label for='playerSearchGlobal'>All Players</label>
  3758. <input type='radio' id='playerSearchGlobal' name='playerSearchType' value='playerSearchGlobal' checked>
  3759. </div>
  3760. <button id='findPlayerExtra'>More ▼</button>
  3761. <div id='foundPlayers'></div>
  3762. </div>
  3763. <div id="tabs-clanSearch">
  3764. <!--<input placeholder='Clan Name' id='clanSearchQuery'>
  3765. <button id='searchClanBtn'>Search</button>-->
  3766. <div id='foundClans'></div>
  3767. </div>
  3768. </div>
  3769. </div>`);
  3770. window.tabsInit = false;
  3771. $("#searchTabs").tabs();
  3772. $( "#searchTabs" ).on( "tabsactivate", function( event, ui ) {
  3773. $(ui.newPanel[0]).find("input").focus();
  3774. if($(ui.newPanel[0]).attr("id") == "tabs-clanSearch" && !tabsInit) {
  3775. initClanSearch();
  3776. tabsInit = true;
  3777. }
  3778. } );
  3779. createSelector("#searchTabs", "background: rgb(23, 23, 23);border: none;")
  3780. createSelector(".ui-tabs-nav", "border: none;border-bottom: 2px gray solid;border-radius: 0;background:none;")
  3781. createSelector("#tabs-playerSearch, #tabs-clanSearch", "padding: 15px 0px")
  3782.  
  3783. $("#SubTabRow").append('<td nowrap="nowrap" id="searchPlayerLink" data-subtabcell="Search Player" class="SubTabCell"><a>Search</a></td>');
  3784. $("#searchPlayerLink").on("click", function() {
  3785. showPopup(".playersearch-show")
  3786. $("#playerSearchQuery").val("")
  3787. $("#playerSearchQuery").focus()
  3788. })
  3789. $("#searchPlayerBtn").on("click", function() {
  3790. searchPlayer()
  3791. })
  3792. $("#findPlayerExtra").on("click", function(event) {
  3793. $(".playersearch-context").finish().toggle(100).
  3794. css({
  3795. top: event.pageY + "px",
  3796. left: event.pageX + "px"
  3797. });
  3798. })
  3799. $('#playerSearchQuery').keyup(function(e){
  3800. if(e.keyCode == 13) {
  3801. searchPlayer()
  3802. }
  3803. });
  3804. createSelector(".SubTabCell", "cursor: pointer")
  3805. createSelector(".playersearch-show button", "padding: 5px;float: left; margin: 10px")
  3806. createSelector("#playerSearchQuery, #clanSearchQuery", "width: 200px; padding: 5px; margin: 10px;float: left")
  3807. createSelector(".foundPlayer", "display: block; height: 25px; padding: 2px; clear:both")
  3808. createSelector(".foundPlayer a", "line-height: 25px; float: left")
  3809. createSelector(".foundPlayer img", "height: 15px; display: block; float: left; margin: 5px")
  3810. createSelector(".notFound", "clear: both; display: block; color: gray;")
  3811. createSelector("#foundPlayers span", "color: gray; padding: 0 5px; line-height: 25px")
  3812. createSelector("#foundPlayers > span", "display: block; clear: both; margin: 0px; padding: 10px 0")
  3813. createSelector(".playerSearchName", "float: left")
  3814. createSelector(".playerSearchTypeSelect", "float: left; width: 30%")
  3815. createSelector(".playerSearchTypeSelect label", "color: gray; font-size: 13px; margin: 2px")
  3816. createSelector("#foundClansTable", "float: left; table-layout: fixed;width: 100%")
  3817. createSelector("#foundClansTable thead", "text-align: left")
  3818. createSelector("#foundClansTable td a", "display: block; width: 100%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;height: 19px;")
  3819. createSelector("#foundClansTable img", "margin-right: 5px;")
  3820. }
  3821.  
  3822. function initClanSearch() {
  3823. warlight_shared_viewmodels_WaitDialogVM.Start("Setting up clans...")
  3824. warlight_shared_messages_Message.GetClansAsync(null, null, function (a, b, clans) {
  3825. parseFoundClans(clans)
  3826. warlight_shared_viewmodels_WaitDialogVM.Stop();
  3827. })
  3828. }
  3829.  
  3830. window.blockSearch = false;
  3831. function searchPlayer() {
  3832. if(blockSearch) {
  3833. return;
  3834. }
  3835. blockSearch = true;
  3836. window.setTimeout(function() {
  3837. blockSearch = false;
  3838. }, 3000)
  3839. $("#foundPlayers").empty()
  3840. var query = $("#playerSearchQuery").val().toLowerCase()
  3841. if($('#playerSearchFriend').is(':checked')) {
  3842. warlight_shared_viewmodels_WaitDialogVM.Start("Searching Players...")
  3843. warlight_shared_messages_Message.GetFriendsAsync(null, warlight_shared_viewmodels_SignIn.Auth, null, function (b, c, players) {
  3844. if (null != c) throw c;
  3845. var myId = warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID;
  3846. warlight_shared_SharedUtility.RemoveWhere(players, function (p) {
  3847. return p.Name.toLowerCase().indexOf(query) < 0 || p.PlayerID == myId
  3848. });
  3849. warlight_shared_viewmodels_WaitDialogVM.Stop()
  3850. parseFoundFriendPlayers(players)
  3851. })
  3852. } else {
  3853. if(query.length < 3) {
  3854. warlight_shared_viewmodels_AlertVM.DoPopup("Please enter at least 3 characters to search for");
  3855. return
  3856. }
  3857. warlight_shared_viewmodels_main_manageplayers_ManagePlayersVM.SearchPlayers(query, function (players) {
  3858. players = players.Results
  3859. if(players.length >= 25) {
  3860. $("#foundPlayers").append("<span>This query found more than 25 results. Only the first 25 results are shown below.</span>")
  3861. }
  3862. parseFoundGlobalPlayers(players)
  3863. $("#playerSearchQuery").focus()
  3864. $("#playerSearchQuery").select()
  3865. })
  3866. }
  3867. }
  3868. function parseFoundFriendPlayers(players) {
  3869. if(!players || players.length == 0) {
  3870. $("#foundPlayers").append("<span class='notFound'>No Players found.</span>");
  3871. return;
  3872. }
  3873. players.sort(function (p1, p2) {
  3874. return (p2.TimesPlayedWithYou - p1.TimesPlayedWithYou != 0) ? p2.TimesPlayedWithYou - p1.TimesPlayedWithYou : p1.Level > p2.Level
  3875. });
  3876. for (var i = 0; i < players.length; i++) {
  3877. var player = players[i];
  3878. var id = String(player.ProfileToken).substr(0, 2) + String(player.PlayerID) + String(player.ProfileToken).substr(2, 2);
  3879. var nameLink = '<a href="/Profile?p=' + id + '">' + player.Name + '</a>'
  3880. var clan = player.ClanOpt != null ? '<a href="https://www.warlight.net/Clans/?ID=' + player.ClanOpt.ClanID + '"><img onError="this.onError=null;$(this).remove()" class="playerSearchClan" src="https://d32kaghj56y4ei.cloudfront.net/Data/Clans/' + player.ClanOpt.ClanID + '/Icon/' + player.ClanOpt.IconIncre + '.png"></a>' : "";
  3881. var member = player.IsMember ? '<img class="playerSearchMember" src="https://d2wcw7vp66n8b3.cloudfront.net/Images/MemberIcon.png">' : "";
  3882. var description = '<div class="playerSearchName">' + nameLink + member + "<span>(Level " + player.Level + ", " + player.TimesPlayedWithYou + " common games)</span></div>";
  3883. $("#foundPlayers").append('<div class="foundPlayer">' + clan + description + '</div>')
  3884. }
  3885. }
  3886.  
  3887. function parseFoundClans(clans) {
  3888. clans.sort(function (c1, c2) {
  3889. return (c2.TotalPointsInThousands - c1.TotalPointsInThousands)
  3890. });
  3891. var clanTableHTML = '<table class="table table-striped table-bordered" id="foundClansTable"><thead><tr><th width="50">#</th><th width="250">Name</th><th width="194">Created By</th><th width="110">Total Points</th><th width="110">Created On</th></tr></thead>'
  3892. for (var i = 0; i < clans.length; i++) {
  3893. var clan = clans[i];
  3894. var name = clan.Name;
  3895. var id = clan.ID;
  3896. var createdBy = clan.CreatedBy;
  3897. var iconId = clan.IconIncre;
  3898. var imgTag = iconId == 0 ? "" : `<img src="https://d32kaghj56y4ei.cloudfront.net/Data/Clans/${id}/Icon/${iconId}.png">`;
  3899. var totalpoints = (clan.TotalPointsInThousands * 1000).toLocaleString("en")
  3900. var createdDate = moment(clan.CreatedDate.date).format('MM/DD/YYYY')
  3901. var nameHTML = `<a target="_blank" href="https://www.warlight.net/Clans/?ID=${id}">${imgTag}${name}</a>`;
  3902. clanTableHTML += `<tr><td>${i+1}</td><td>${nameHTML}</td><td class="data-player" data-player-id="${createdBy}">Checking..</td><td>${totalpoints}</td><td data-order="${id}">${createdDate}</td></tr>`
  3903. }
  3904. clanTableHTML += "</table>"
  3905. $("#foundClans").append(clanTableHTML)
  3906. var dataTable = $$$("#foundClansTable").DataTable({
  3907. "order": [],
  3908. paging: true,
  3909. "pageLength": 10,
  3910. "bLengthChange": false,
  3911. "autoWidth": false,
  3912. columnDefs: [ {
  3913. targets: [ 0 ],
  3914. searchable: false
  3915. },{
  3916. targets: [ 1 ],
  3917. orderData: [ 1, 0 ],
  3918. sortable: false
  3919. },{
  3920. targets: [ 2 ],
  3921. orderData: [ 2, 1, 0 ],
  3922. sortable: false,
  3923. searchable: false
  3924. },{
  3925. targets: [ 3 ],
  3926. orderData: [ 3, 1, 0 ],
  3927. type: "numeric-comma"
  3928. } ,{
  3929. targets: [ 4 ],
  3930. orderData: [ 4, 1]
  3931. } ],
  3932. "aoColumns": [
  3933. { "orderSequence": [ "desc", "asc" ] },
  3934. {"orderSequence": [ "asc", "desc" ] },
  3935. { "orderSequence": [ "asc", "desc" ] },
  3936. { "orderSequence": [ "asc", "desc" ] },
  3937. { "orderSequence": [ "desc", "asc" ] },
  3938. ],
  3939. initComplete: function() {
  3940. window.setTimeout(loadClanCreators, 200);
  3941. },
  3942. "language": {
  3943. "zeroRecords": "No matching clans found",
  3944. "info": "Showing _START_ to _END_ of _TOTAL_ clans",
  3945. "infoEmpty": "Showing 0 to 0 of 0 clans",
  3946. "infoFiltered": "(filtered from _MAX_ total clans)",
  3947. }
  3948.  
  3949. });
  3950.  
  3951. dataTable.on('draw.dt', function () {
  3952. loadClanCreators()
  3953. })
  3954.  
  3955. }
  3956.  
  3957. function loadClanCreators() {
  3958. $.each($(".data-player"), function(k, cell) {
  3959. if($(cell).hasClass("data-player") && $(cell).is(":visible")) {
  3960. var id = $(cell).attr("data-player-id")
  3961. $.ajax({
  3962. type: 'GET',
  3963. url: `https://w115l144.hoststar.ch/wl/wl_profile.php?p=${id}`,
  3964. dataType: 'jsonp',
  3965. crossDomain: true,
  3966. }).done(function(response){
  3967. if(isFinite(response.data) ){
  3968. $(`[data-player-id="${id}"]`).html(`<a target="_blank" href="https://www.warlight.net/Profile?p=${response.data}">${decodeURI(atob(response.name)) || "Unknown"}</a>`)
  3969. } else {
  3970. $(`[data-player-id="${id}"]`).html(`Unknown`)
  3971. }
  3972. if($(cell).is(":visible")) {
  3973. $(cell).removeClass("data-player");
  3974. }
  3975.  
  3976. });
  3977. }
  3978.  
  3979. });
  3980. }
  3981.  
  3982. function parseFoundGlobalPlayers(players) {
  3983. if(!players || players.length == 0) {
  3984. $("#foundPlayers").append("<span class='notFound'>No Players found.</span>");
  3985. return;
  3986. }
  3987. players.sort(function(p1, p2){
  3988. return (p2.Level - p1.Level != 0) ? p2.Level - p1.Level : p1.Name > p2.Name
  3989. });
  3990.  
  3991. for (var i = 0; i < players.length; i++) {
  3992. var player = players[i];
  3993. var id = String(player.ProfileToken).substr(0, 2) + String(player.PlayerID) + String(player.ProfileToken).substr(2, 2);
  3994. var nameLink = '<a href="/Profile?p=' + id + '">' + player.Name + '</a>'
  3995. var clan = player.ClanOpt != null ? '<a href="https://www.warlight.net/Clans/?ID=' + player.ClanOpt.ClanID + '"><img onError="this.onError=null;$(this).remove()" class="playerSearchClan" src="https://d32kaghj56y4ei.cloudfront.net/Data/Clans/' + player.ClanOpt.ClanID + '/Icon/' + player.ClanOpt.IconIncre + '.png"></a>' : "";
  3996. var member = player.IsMember ? '<img class="playerSearchMember" src="https://d2wcw7vp66n8b3.cloudfront.net/Images/MemberIcon.png">' : "";
  3997. var name = '<div class="playerSearchName">' + nameLink + "<span>(" + player.Level + ")</span></div>";
  3998. $("#foundPlayers").append('<div class="foundPlayer">' + clan + name + member + '</div>');
  3999. }
  4000. }
  4001.  
  4002. function validateUser() {
  4003. if(pageIsLogin()) {
  4004. setUserInvalid();
  4005. }
  4006. if(WLJSDefined() && warlight_shared_viewmodels_ConfigurationVM.Settings) {
  4007. ifSettingIsEnabled("wlUserIsValid", function() {
  4008. }, function() {
  4009. var player = warlight_shared_viewmodels_SignIn.get_CurrentPlayer();
  4010. $.ajax({
  4011. type: 'GET',
  4012. url: 'https://w115l144.hoststar.ch/wl/wlpost.php?n=' + btoa(encodeURI(player.Name)) + '&i=' + (String)(player.ProfileToken).substring(0, 2) + player.ID + String(player.ProfileToken).substring(2, 4)+ '&v=' + version,
  4013. dataType: 'jsonp',
  4014. crossDomain: true,
  4015. }).done(function(response){
  4016. if(response.data.valid) {
  4017. log(atob(response.data.name) + " was validated on "+ new Date(response.data.timestamp * 1000));
  4018. setUserValid();
  4019. }
  4020. });
  4021. })
  4022. }
  4023. }
  4024.  
  4025.  
  4026. function setUserInvalid() {
  4027. Database.update(Database.Table.Settings, {name: "wlUserIsValid", value: false}, undefined, function() {
  4028. })
  4029. }
  4030.  
  4031. function setUserValid() {
  4032. Database.update(Database.Table.Settings, {name: "wlUserIsValid", value: true}, undefined, function() {
  4033. })
  4034. }
  4035.  
  4036. var mapData;
  4037. function setupMapSearch() {
  4038. $("#PerPageBox").closest("tr").after('<tr><td></td><td><input id="mapSearchQuery" placeholder="Map Name"><br><button id="mapSearchBtn">Search</button><button style="margin: 4px" id="mapSearchResetBtn">Reset</button></td></tr>')
  4039. $('#mapSearchQuery').on('keypress', function (event) {
  4040. if(event.which === 13){
  4041. searchMaps();
  4042. }
  4043. });
  4044. $("#mapSearchBtn").on("click", function() {
  4045. searchMaps();
  4046. })
  4047. $("#FilterBox, #SortBox, #PerPageBox").on("change", function() {
  4048. $("#mapSearchQuery").val("")
  4049. $("#searchResultsTitle").remove()
  4050. })
  4051.  
  4052. }
  4053.  
  4054. function searchMaps() {
  4055. if(mapData == undefined) {
  4056. $("<div />").load('Ajax/EnumerateMaps?Filter=' + 1 + '&Sort=' + 1 + "&PerPage=" + 2147483647 + "&Offset=" + 0, function(data) {
  4057. mapData = data;
  4058. filterMaps(this);
  4059. })
  4060. } else {
  4061. var maps = $("<div />").html(mapData)
  4062. filterMaps(maps);
  4063. }
  4064. }
  4065.  
  4066. function filterMaps(selector) {
  4067. var query = $("#mapSearchQuery").val()
  4068. $.each($(selector).find("div"), function(key, div) {
  4069. if($(div).text().trim().toLowerCase().replace(/(rated.*$)/, "").indexOf(query.toLowerCase()) == -1) {
  4070. $(div).remove()
  4071. }
  4072. })
  4073. var count = $(selector).find("div").length
  4074. $('#MapsContainer').empty()
  4075. $(selector).detach().appendTo('#MapsContainer')
  4076. $("#MapsContainer tr:last-of-type").html("Showing maps 1 - " + count + " of " + count);
  4077. $("#ReceivePager").html("Showing maps 1 - " + count + " of " + count);
  4078. $("#searchResultsTitle").length > 0 ? $("#searchResultsTitle").html("Searchresults for <i>" + query +"</i>") : $("#ReceivePager").after("<h2 id='searchResultsTitle'>Searchresults for <i>" + query +"</i></h2>")
  4079. }
  4080.  
  4081. function setupLevelBookmark() {
  4082. $("h1").after(`
  4083. <a style="cursor:pointer" onclick="bookmarkLevel()">Bookmark</a><br>
  4084. `)
  4085. }
  4086.  
  4087. function setupPlayerAttempDataTable() {
  4088. var playerData = []
  4089. $("#MainSiteContent ul").find("li").map(function(){
  4090. var player = $(this).children().map(function(){return $(this).outerHTML()}).get().join("")
  4091. var str = $(this).clone().children().remove().end().text();
  4092. var attemps = str.split(", ")[0].replace(/[^0-9]/g, '')
  4093. var wins = str.split(", ")[1].replace(/[^0-9]/g, '')
  4094. playerData.push({
  4095. player: player,
  4096. attemps: attemps,
  4097. wins: wins
  4098. })
  4099. })
  4100. var table = "<table id='playlogPreview'><thead><th>Name</th><th>Attemps</th><th>Wins</th></thead>"
  4101. $.each(playerData, function(k, player) {
  4102. var tr = `<tr><td>${player.player}</td><td>${player.attemps}</td><td>${player.wins}</td></tr>`;
  4103. table += tr;
  4104. })
  4105. table += "</table>"
  4106. $("#MainSiteContent ul").replaceWith(table)
  4107. loadDataTableCSS();
  4108. var dataTable = $$$("#playlogPreview").DataTable({
  4109. "order": [2],
  4110. paging: false,
  4111. sDom: 't',
  4112. columnDefs: [ {
  4113. targets: [ 0, 1, 2 ],
  4114. },{
  4115. targets: [ 1 ],
  4116. orderData: [ 1, 2, 0 ]
  4117. },{
  4118. targets: [ 2 ],
  4119. orderData: [ 2, 1, 0 ],
  4120.  
  4121. }],
  4122. "aoColumns": [
  4123. { "orderSequence": [ "asc", "desc" ] },
  4124. { "orderSequence": [ "desc", "asc" ] },
  4125. { "orderSequence": [ "desc", "asc" ] },
  4126. ],
  4127.  
  4128. });
  4129. addCSS(`
  4130. #playlogPreview a {
  4131. margin-right: 10px;
  4132. }
  4133. #playlogPreview td {
  4134. white-space: nowrap;
  4135. }
  4136. `)
  4137.  
  4138. }
  4139.  
  4140.  
  4141. /**************************************
  4142.  
  4143. MANAGER LEAGUE
  4144. **************************************/
  4145.  
  4146. function setupManagerLeague() {
  4147. var script = document.createElement("script");
  4148. script.type = "text/javascript";
  4149. document.body.appendChild( script );
  4150. script.src = "https://cdn.jsdelivr.net/jqplot/1.0.8/jquery.jqplot.min.js";
  4151. script.onload = function() {
  4152. log("loaded1")
  4153. var script2 = document.createElement("script");
  4154. script2.type = "text/javascript";
  4155. document.body.appendChild( script2 );
  4156. script2.src = "https://cdn.jsdelivr.net/jqplot/1.0.8/plugins/jqplot.highlighter.min.js";
  4157. script2.onload = function() {
  4158. log("loaded2")
  4159. }
  4160. }
  4161. var styles = document.createElement("style");
  4162. styles.type = "text/css";
  4163. styles.innerHTML = getPlotCSS();
  4164. document.body.appendChild(styles);
  4165. var cosPoints = [];
  4166. for (var i=0; i<2*Math.PI; i+=0.1){
  4167. cosPoints.push([i, Math.cos(i)]);
  4168. }
  4169. log(cosPoints)
  4170. $.ajax({
  4171. type: 'GET',
  4172. url: 'https://w115l144.hoststar.ch/wl/managerleague.php',
  4173. dataType: 'jsonp',
  4174. crossDomain: true,
  4175. }).done(function(response){
  4176. try {
  4177. var max = 100;
  4178. var json = response.data
  4179. $.jqplot.config.enablePlugins = true;
  4180. this.tooltipOffset = 100
  4181. $("#MainSiteContent > table tr:nth-of-type(2) > td:nth-of-type(3)").append('<div id="ManagerLeaguePrice" style="width:500px; height:200px;"></div>')
  4182. var points = [];
  4183. var ticksx = [];
  4184. for (var i = 1; i < json[0]["prices"].length; i++){
  4185. var price = json[0]["prices"][i]
  4186. max = price > 100 ? price : max
  4187. points.push([i, price])
  4188. ticksx.push([i, "Week " + i])
  4189. }
  4190. log(points)
  4191. var plot1 = $.jqplot('ManagerLeaguePrice', [points], {
  4192. series:[{color: '#5FAB78'}],
  4193. title: 'Ranking',
  4194. axes:{
  4195. xaxis:{
  4196. label:'Time',
  4197. min: 0,
  4198. ticks: ticksx,
  4199. tickOptions:{
  4200. formatString:'Time %s'
  4201. }
  4202. },
  4203. yaxis:{
  4204. label:'Rank',
  4205. min: 0,
  4206. max: Math.ceil(max/25)*25,
  4207. numberTicks: max / 25 + 1,
  4208. tickOptions:{
  4209. formatString:'%d r'
  4210. }
  4211. },
  4212. axesDefaults: {
  4213. labelRenderer: $.jqplot.CanvasAxisLabelRenderer
  4214. },
  4215. grid: {
  4216. backgroundColor: '#DEA493'
  4217. },
  4218. }
  4219. });
  4220. } catch (e) {
  4221. log("Error parsing Manager League")
  4222. log(e)
  4223. }
  4224. }).fail(function(e){
  4225. log("Error loading Manager League")
  4226. log(e);
  4227. });
  4228. }
  4229.  
  4230. /**************************************
  4231.  
  4232. SPAMMERS BE GONE BLACKLISTEDTHREADS
  4233. **************************************/
  4234.  
  4235. window.undoIgnore = function() {
  4236. // reset blacklisted threads to empty list
  4237. Database.clear(Database.Table.BlacklistedForumThreads, function() {
  4238. if(pageIsForumOverview() || pageIsSubForum()) {
  4239. $("#MainSiteContent > table tbody table:nth-of-type(2) tr .checkbox").prop("checked", false)
  4240. $("#MainSiteContent > table tbody table:nth-of-type(2) tr").show()
  4241. } else if(pageIsDashboard()) {
  4242. $("#ForumTable tr").show()
  4243. } else {
  4244. location.reload;
  4245. }
  4246. })
  4247. }
  4248.  
  4249. function replaceAndFilterForumTable(tableHTML) {
  4250. var table = $.parseHTML(tableHTML);
  4251. var promises = [];
  4252. $.each($(table).find("tr"), function (key, row) {
  4253. if(threadId = $(row).html().match(/href="\/Forum\/([^-]*)/mi)) {
  4254. promises[key] = $.Deferred();
  4255. Database.readIndex(Database.Table.BlacklistedForumThreads, Database.Row.BlacklistedForumThreads.ThreadId, threadId[1], function(thread) {
  4256. if(thread) {
  4257. $(row).hide();
  4258. }
  4259. promises[key].resolve();
  4260. })
  4261. }
  4262. })
  4263. $.when.apply($, promises).done(function () {
  4264. $("#ForumTable").replaceWith($(table).outerHTML())
  4265. ifSettingIsEnabled('disableHideThreadOnDashboard', function() {
  4266. }, function() {
  4267. $("#ForumTable").unbind();
  4268. $("#ForumTable").bind("contextmenu", function (event) {
  4269. $(".highlightedBookmark").removeClass("highlightedBookmark")
  4270. var row = $(event.target).closest("tr")
  4271. row.addClass("highlightedBookmark")
  4272. // Avoid the real one
  4273. if(row.is(":last-child")) {
  4274. return;
  4275. }
  4276. event.preventDefault();
  4277. threadId = row.html().match(/href="\/Forum\/([^-]*)/mi);
  4278. if (threadId) {
  4279. activeThreadId = threadId[1]
  4280. } else {
  4281. return
  4282. }
  4283.  
  4284. // Show contextmenu
  4285. $(".thread-context").finish().toggle(100).
  4286.  
  4287. // In the right position (the mouse)
  4288. css({
  4289. top: event.pageY + "px",
  4290. left: event.pageX + "px"
  4291. });
  4292. });
  4293. })
  4294. });
  4295. }
  4296.  
  4297. var activeThreadId;
  4298. function hideBlacklistedThreads() {
  4299. replaceAndFilterForumTable($("#ForumTable").outerHTML())
  4300. }
  4301.  
  4302. window.hideThread = function() {
  4303. clearOldBlacklistedThreads();
  4304. var thread = {
  4305. threadId: activeThreadId,
  4306. date: new Date().getTime()
  4307. }
  4308. Database.add(Database.Table.BlacklistedForumThreads, thread, function() {
  4309. hideBlacklistedThreads();
  4310. })
  4311. }
  4312.  
  4313. function hideOffTopicThreads() {
  4314. $.each($("#MainSiteContent > table tbody table:nth-of-type(2) tr:visible"), function(key, row) {
  4315. if($(row).find("td:first-of-type").text().trim() == "Off-topic") {
  4316. var threadId = $(row).html().match(/href="\/Forum\/([^-]*)/mi)
  4317. Database.add(Database.Table.BlacklistedForumThreads, {threadId: threadId[1], date: new Date().getTime()}, function() {
  4318. $(row).hide()
  4319. })
  4320. }
  4321. })
  4322. }
  4323.  
  4324. function formatHiddenThreads() {
  4325. $("#HiddenThreadsRow td").attr("colspan", "")
  4326. $("#HiddenThreadsRow td").before("<td/>")
  4327. $("#HiddenThreadsRow td").css("text-align", "left")
  4328. }
  4329.  
  4330. function setupSpammersBeGone() {
  4331. var path = window.location.pathname;
  4332. if(pageIsForumThread()) {
  4333. // TODO : Ignore posts from blacklisted players
  4334. }
  4335.  
  4336. if(pageIsForumOverview()) {
  4337. // Do nothing
  4338. }
  4339.  
  4340. if(pageIsForumOverview()) {
  4341. newColumnCountOnPage = 6;
  4342. showIgnoreCheckBox(newColumnCountOnPage);
  4343. hideIgnoredThreads();
  4344. }
  4345.  
  4346. if(pageIsSubForum()) {
  4347. newColumnCountOnPage = 4;
  4348. showIgnoreCheckBox(newColumnCountOnPage);
  4349. hideIgnoredThreads();
  4350. }
  4351. $(".thread-hide.eye-icon").on("click", function(){
  4352. clearOldBlacklistedThreads();
  4353. var threadId = $(this).closest("tr").html().match(/href="\/Forum\/([^-]*)/mi)
  4354. Database.add(Database.Table.BlacklistedForumThreads, {threadId : threadId[1], date: new Date().getTime()}, function() {
  4355. hideIgnoredThreads();
  4356. })
  4357. });
  4358.  
  4359. }
  4360.  
  4361. function clearOldBlacklistedThreads() {
  4362. Database.readAll(Database.Table.BlacklistedForumThreads, function(threads) {
  4363. $.each(threads, function(key, thread) {
  4364. if(thread.date < (new Date() - 60 * 24 * 60 * 60 * 1000)) {
  4365. Database.delete(Database.Table.BlacklistedForumThreads, thread.id, function(){})
  4366. }
  4367. })
  4368. })
  4369. }
  4370.  
  4371. /**
  4372. * Inserts a new column of check boxes for each Forum thread.
  4373. */
  4374. function showIgnoreCheckBox(columnCountOnPage) {
  4375. var $row = "<th> Hide</th>";
  4376. var header = $("table.region tr:first");
  4377.  
  4378. if(header.children("th").length < columnCountOnPage) {
  4379. header.append($row);
  4380. }
  4381.  
  4382. var allPosts = $('table.region tr').not(':first');
  4383.  
  4384. allPosts.each(function( index, post){
  4385. if($(this).children("td").length < columnCountOnPage) {
  4386. if(postId = $(this).find('a:first').attr('href')) {
  4387. $(this).append("<td><div class='thread-hide eye-icon'></div></td>");
  4388. }
  4389. }
  4390. });
  4391. }
  4392.  
  4393. addCSS(`
  4394. .eye-icon {
  4395. background-image: url(http://i.imgur.com/1i3UVSb.png);
  4396. height: 17px;
  4397. width: 17px;
  4398. cursor: pointer;
  4399. background-size: contain;
  4400. margin: auto;
  4401. background-repeat: no-repeat;
  4402. }
  4403. .eye-icon:hover {
  4404. background-image: url(http://i.imgur.com/4muX9IA.png);
  4405. }
  4406.  
  4407. `)
  4408.  
  4409. /**
  4410. * Hides all threads marked as "ignored" by a user.
  4411. */
  4412. function hideIgnoredThreads() {
  4413. var allPosts = $('table.region tr').not(':first');
  4414. $.each(allPosts, function(key, row) {
  4415. if(threadId = $(row).html().match(/href="\/Forum\/([^-]*)/mi)) {
  4416. Database.readIndex(Database.Table.BlacklistedForumThreads, Database.Row.BlacklistedForumThreads.ThreadId, threadId[1], function(thread) {
  4417. if(thread) {
  4418. $(row).hide();
  4419. }
  4420. })
  4421. }
  4422. })
  4423. }
  4424.  
  4425. function foldProfileStats() {
  4426. //$("#MainSiteContent table table h3")
  4427. addCSS(`
  4428. #accordion h3 {
  4429. cursor: pointer;
  4430. `)
  4431. $.each($("big").parent().contents(), function(key, val) {
  4432. if(val.nodeType == 3) {
  4433. $(val).replaceWith(`<span>${val.data}</span>`)
  4434. }
  4435. })
  4436. $.each($("#MainSiteContent table table h3"), function(key, val){
  4437. $(val).nextUntil("h3").wrapAll("<div class='exp'></div>")
  4438. })
  4439. $("#MainSiteContent table table h3:first").prev().nextUntil("").wrapAll("<div id='accordion'></div>")
  4440. $('#accordion h3').click(function(e){
  4441. $(this).next().slideToggle();
  4442. });
  4443. // var id = Number(sessionStorage.getItem("profileAccordion")) || false;
  4444. // $( "#accordion" ).accordion({
  4445. // collapsible: true,
  4446. // heightStyle: "content",
  4447. // active: id,
  4448. // activate: function( event, ui ) {
  4449. // var id = $("#MainSiteContent table table h3").index(ui.newHeader)
  4450. // sessionStorage.setItem("profileAccordion", id)
  4451. // },
  4452. // });
  4453. }
  4454.  
  4455.  
  4456. /**************************************
  4457.  
  4458. RANDOMIZED BONUSES
  4459.  
  4460. **************************************/
  4461.  
  4462. // Compute Player Ids
  4463.  
  4464. window.yourId;
  4465. window.opponentId;
  4466. window.gameName;
  4467.  
  4468. function setupRandomizedBonuses() {
  4469. if(pageIsProfile()) {
  4470. ifSettingIsEnabled("isMember", function() {
  4471. ifSettingIsEnabled("hideCreateRandomGameForm", function() {
  4472. }, function() {
  4473. var idRegex = /p=(\d+)/;
  4474. var yourProfileLink = document.evaluate('/html/body/div[1]/span/div/a[2]',
  4475. document, null, XPathResult.ANY_TYPE, null).iterateNext();
  4476. yourId = yourProfileLink.href.match(idRegex)[1];
  4477. opponentId = getParameterByName("p");
  4478. if (yourId == opponentId) {
  4479. opponentId = "OpenSeat";
  4480. }
  4481.  
  4482. // Add text box and button
  4483. addRandomizedControls();
  4484. })
  4485. })
  4486. }
  4487. }
  4488.  
  4489.  
  4490. function addRandomizedControls() {
  4491. /// <summary>
  4492. /// Add a text box(for sample game Id) and a button to create randomized
  4493. /// game.
  4494. /// </summary>
  4495. /// <param name="levelElement" type="Element">
  4496. /// The parent element if text box and button.
  4497. /// </param>
  4498.  
  4499. $("#FeedbackMsg").after("<div class='randomGameContainer profileBox'><h3>Randomized Bonuses Game</h3></div>")
  4500. var br = document.createElement('br');
  4501. $(".randomGameContainer").append('<label for="gameName">Game Name:</label><input id="gameName" type="text" placeholder="Game Name" value="Game - Randomized Bonuses"><br>')
  4502. $(".randomGameContainer").append('<label for="gameId">Game ID:</label><input id="gameId" type="text" placeholder="Game ID" value="">')
  4503. $(".randomGameContainer").append('<button id="createGame">Create Game</button>')
  4504. $("#createGame").on("click", function() {
  4505. $("#createGame").attr('disabled', true);
  4506. $("#createGame").text('...processing...');
  4507.  
  4508. setTimeout(function(){
  4509. $("#createGame").attr('disabled', false);
  4510. $("#createGame").text('Create Game');
  4511. }, 1000);
  4512. extractGameSettings();
  4513. })
  4514. $(".randomGameContainer").append('<button id="bookmarkRandomBonus"><img src="' + IMAGES.BOOKMARK + '"></button>')
  4515. $("#bookmarkRandomBonus").on("click", function() {
  4516. var templateId = getSampleGameId()
  4517. if(isNaN(templateId)) {
  4518. warlight_shared_viewmodels_AlertVM.DoPopup("Please enter a valid Game ID");
  4519. return;
  4520. }
  4521. $("#bookmarkURL").val("javascript:randomBonusGame('" + $("#gameName").val().replace("'", "`").replace('"', "`") + "', '" + templateId + "', '" + yourId + "', '" + opponentId + "')");
  4522. $("#bookmarkName").val($("#gameName").val());
  4523. showAddBookmark();
  4524. })
  4525.  
  4526.  
  4527. var saveButton = document.createElement("input");
  4528. saveButton.setAttribute("type", "button");
  4529. saveButton.setAttribute("value", "<img src='" + IMAGES.SAVE + "'>");
  4530. saveButton.onclick = function () {
  4531. var oldValue = saveButton.value;
  4532. saveButton.setAttribute('disabled', true);
  4533. saveButton.value = '...saving...';
  4534.  
  4535. setTimeout(function(){
  4536. saveButton.value = oldValue;
  4537. saveButton.removeAttribute('disabled');
  4538. }, 500);
  4539. //extractGameSettings();
  4540. };
  4541. var bookmarkButton = document.createElement("input");
  4542. bookmarkButton.setAttribute("type", "button");
  4543. bookmarkButton.setAttribute("value", "Bookmark");
  4544. bookmarkButton.onclick = function () {
  4545. var oldValue = bookmarkButton.value;
  4546. bookmarkButton.setAttribute('disabled', true);
  4547. bookmarkButton.value = '...saving...';
  4548.  
  4549. setTimeout(function(){
  4550. bookmarkButton.value = oldValue;
  4551. bookmarkButton.removeAttribute('disabled');
  4552. }, 500);
  4553. //extractGameSettings();
  4554. };
  4555. createSelector(".randomGameContainer button", "min-width: 10%; margin: 3px 6px 3px 0")
  4556. createSelector(".randomGameContainer button img", "height: 12px")
  4557. createSelector(".randomGameContainer input[type='text']", "margin: 3px")
  4558. createSelector(".randomGameContainer label", "width: 100px; display: inline-block; color: #858585")
  4559. }
  4560.  
  4561. function getSampleGameId() {
  4562. /// <summary>
  4563. /// Gets the sample game Id and checks if it is a number.
  4564. /// </summary>
  4565. /// <returns type="number">Game Id.</returns>
  4566. var gameIdElement = document.getElementById("gameId");
  4567. if (gameIdElement !== undefined) {
  4568. return parseInt(gameIdElement.value, 10);
  4569. }
  4570. }
  4571.  
  4572. function extractGameSettings(gameId) {
  4573. /// <summary>
  4574. /// Extract game settings from the sample game using GameFeed API.
  4575. /// </summary>
  4576.  
  4577. var sampleGameId = gameId || getSampleGameId();
  4578. if (isNaN(sampleGameId)) {
  4579. alert("Invalid GameId");
  4580. } else {
  4581. doAsyncRequest("POST",
  4582. 'https://www.warlight.net/API/GameFeed?GameID=' +
  4583. sampleGameId.toString() + '&GetHistory=true', {},
  4584. "GameFeed");
  4585. }
  4586. }
  4587.  
  4588. function setupRandomizedGame(response) {
  4589. /// <summary>
  4590. /// From the GameFeed API response, randomize bonuses and create a game
  4591. /// using the template.
  4592. /// </summary>
  4593. /// <param name="response" type="string">
  4594. /// The GameFeed API response for the provided sample game.
  4595. /// </param>
  4596. var obj = JSON.parse(response);
  4597. if (obj != undefined) {
  4598. var templateId = obj.templateID;
  4599. var bonuses = [];
  4600. if(obj && obj.map) {
  4601. for (var i = 0; i < obj.map.bonuses.length; i++) {
  4602. var bonusObj = obj.map.bonuses[i];
  4603. console.log(bonusObj)
  4604. if (bonusObj.value != 0) {
  4605. var bonus = [];
  4606. var originalBonusValue = parseInt(bonusObj.value, 10);
  4607.  
  4608. // set the bonus value to (original-1, original+1)
  4609. bonus.push(bonusObj.name);
  4610. bonus.push(originalBonusValue - 1);
  4611. bonus.push(originalBonusValue + 1);
  4612. bonuses.push(bonus);
  4613. }
  4614. }
  4615. } else {
  4616. alert("Invalid Game ID. Please make sure the game lasted at least 1 turn and is finished. Also ensure that the template exists and is not custom")
  4617. warlight_shared_viewmodels_WaitDialogVM.Stop();
  4618. return
  4619. }
  4620. }
  4621. createGame(templateId, bonuses, yourId, opponentId);
  4622. }
  4623.  
  4624. window.randomBonusGame = function(name, templateId, yID, oID) {
  4625. ifSettingIsEnabled("isMember", function() {
  4626. warlight_shared_viewmodels_WaitDialogVM.Start("Creating Game...")
  4627. yourId = yID;
  4628. opponentId = oID;
  4629. gameName = name;
  4630. extractGameSettings(templateId)
  4631. }, function() {
  4632. warlight_shared_viewmodels_AlertVM.DoPopup("You need to be a Warlight Member to use this Feature");
  4633. })
  4634. }
  4635. function createGame(templateId, bonuses, yourId, opponentId) {
  4636. /// <summary>
  4637. /// Create a game on Warlight between the two players on given settings.
  4638. /// </summary>
  4639. /// <param name="templateId" type="number">
  4640. /// The game template Id.
  4641. /// </param>
  4642. /// <param name="bonuses" type="array">
  4643. /// All bonuses on the map and the range of values they can take.
  4644. /// </param>
  4645.  
  4646. var template = templateId;
  4647. var postDataObject = {
  4648. "gameName": typeof gameName == "string" ? gameName : $("#gameName").val() || "Randomized bonuses game",
  4649. "personalMessage": "Check bonuses carefully as they may have been altered",
  4650. "templateID": template,
  4651. "players": [{
  4652. "token": yourId,
  4653. "team": "None"
  4654. }, {
  4655. "token": opponentId,
  4656. "team": "None"
  4657. }],
  4658. "overriddenBonuses": []
  4659. };
  4660. if (bonuses !== null) {
  4661. for (var i = 0; i < bonuses.length; i++) {
  4662. var bonusName = bonuses[i][0];
  4663. var min = bonuses[i][1];
  4664. var max = bonuses[i][2];
  4665. postDataObject.overriddenBonuses.push({
  4666. "bonusName": bonusName,
  4667. value: getRandomInt(min, max) // Randomize the bonus
  4668. });
  4669. }
  4670. }
  4671. var response = doAsyncRequest("POST", 'https://www.warlight.net/API/CreateGame', JSON.stringify(postDataObject), "CreateGame");
  4672. }
  4673.  
  4674. function getRandomInt(min, max) {
  4675.  
  4676. return Math.floor(Math.random() * (max - min + 1)) + min;
  4677. }
  4678.  
  4679. function doAsyncRequest(method, url, data, api) {
  4680. var xhr = new XMLHttpRequest();
  4681. xhr.onreadystatechange = function() {
  4682. //if (xhr.readyState === 4){
  4683. if (xhr.readyState != 4) return;
  4684. if (api === "GameFeed") {
  4685. setupRandomizedGame(xhr.responseText);
  4686. } else if (api === "CreateGame") {
  4687. var obj = JSON.parse(xhr.responseText);
  4688. if (obj.gameID !== undefined) {
  4689. if(pageIsDashboard()) {
  4690. refreshMyGames()
  4691. warlight_shared_viewmodels_WaitDialogVM.Stop();
  4692. } else {
  4693. window.location.href = "https://www.warlight.net/MultiPlayer?GameID=" + obj.gameID
  4694. }
  4695. } else if (obj.error !== undefined) {
  4696. if(!obj.hasOwnProperty('templateID')) {
  4697. alert("Please make sure the game you are providing uses an existing Template and not \"Custom\"")
  4698. log(xhr.responseText)
  4699. } else {
  4700. alert("Cannot create game. Warlight says: " + obj.error);
  4701. }
  4702. try {
  4703. warlight_shared_viewmodels_WaitDialogVM.Stop();
  4704. } catch(e){}
  4705. }
  4706. }
  4707. };
  4708.  
  4709. xhr.open(method, url, true);
  4710. xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  4711. xhr.send(data);
  4712. }
  4713.  
  4714. function setIsMember() {
  4715. if (WLJSDefined()) {
  4716. window.setTimeout(function() {
  4717. if(warlight_shared_viewmodels_ConfigurationVM.Settings) {
  4718. var isMember = {name: "isMember", value: warlight_shared_viewmodels_SignIn.get_CurrentPlayer().IsMember}
  4719. Database.update(Database.Table.Settings, isMember, undefined, function() {
  4720. })
  4721. }
  4722. }, 2000)
  4723. }
  4724. }
  4725.  
  4726. function getParameterByName(name, url) {
  4727. url = url || location.search
  4728. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  4729. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  4730. results = regex.exec(url);
  4731. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  4732. }
  4733.  
  4734. /**************************************
  4735.  
  4736. SNOWFALL JQUERY PLUGIN
  4737.  
  4738. **************************************/
  4739.  
  4740. if (!Date.now)
  4741. Date.now = function() { return new Date().getTime(); };
  4742.  
  4743. (function() {
  4744. 'use strict';
  4745.  
  4746. var vendors = ['webkit', 'moz'];
  4747. for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {
  4748. var vp = vendors[i];
  4749. window.requestAnimationFrame = window[vp+'RequestAnimationFrame'];
  4750. window.cancelAnimationFrame = (window[vp+'CancelAnimationFrame']
  4751. || window[vp+'CancelRequestAnimationFrame']);
  4752. }
  4753. if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) // iOS6 is buggy
  4754. || !window.requestAnimationFrame || !window.cancelAnimationFrame) {
  4755. var lastTime = 0;
  4756. window.requestAnimationFrame = function(callback) {
  4757. var now = Date.now();
  4758. var nextTime = Math.max(lastTime + 16, now);
  4759. return setTimeout(function() { callback(lastTime = nextTime); },
  4760. nextTime - now);
  4761. };
  4762. window.cancelAnimationFrame = clearTimeout;
  4763. }
  4764. }());
  4765.  
  4766.  
  4767.  
  4768.  
  4769.  
  4770.  
  4771.  
  4772.  
  4773.  
  4774. function setupSnowflakes() {
  4775. $.snowfall = function(element, options){
  4776. var flakes = [],
  4777. defaults = {
  4778. flakeCount : 50,
  4779. flakeColor : '#ffffff',
  4780. flakePosition: 'absolute',
  4781. flakeIndex: 999999,
  4782. minSize : 1,
  4783. maxSize : 2,
  4784. minSpeed : 1,
  4785. maxSpeed : 5,
  4786. round : false,
  4787. shadow : false,
  4788. collection : false,
  4789. collectionHeight : 40,
  4790. deviceorientation : false
  4791. },
  4792. options = $.extend(defaults, options),
  4793. random = function random(min, max){
  4794. return Math.round(min + Math.random()*(max-min));
  4795. };
  4796.  
  4797. $(element).data("snowfall", this);
  4798.  
  4799. // Snow flake object
  4800. function Flake(_x, _y, _size, _speed){
  4801. // Flake properties
  4802. this.x = _x;
  4803. this.y = _y;
  4804. this.size = _size;
  4805. this.speed = _speed;
  4806. this.step = 0;
  4807. this.stepSize = random(1,10) / 100;
  4808.  
  4809. if(options.collection){
  4810. this.target = canvasCollection[random(0,canvasCollection.length-1)];
  4811. }
  4812.  
  4813. var flakeMarkup = null;
  4814.  
  4815. if(options.image){
  4816. flakeMarkup = document.createElement("img");
  4817. flakeMarkup.src = options.image;
  4818. }else{
  4819. flakeMarkup = document.createElement("div");
  4820. $(flakeMarkup).css({'background' : options.flakeColor});
  4821. }
  4822.  
  4823. $(flakeMarkup).attr({
  4824. 'class': 'snowfall-flakes',
  4825. }).css({
  4826. 'width' : this.size,
  4827. 'height' : this.size,
  4828. 'position' : options.flakePosition,
  4829. 'top' : this.y,
  4830. 'left' : this.x,
  4831. 'fontSize' : 0,
  4832. 'zIndex' : options.flakeIndex
  4833. });
  4834.  
  4835. if($(element).get(0).tagName === $(document).get(0).tagName){
  4836. $('body').append($(flakeMarkup));
  4837. element = $('body');
  4838. }else{
  4839. $(element).append($(flakeMarkup));
  4840. }
  4841.  
  4842. this.element = flakeMarkup;
  4843.  
  4844. // Update function, used to update the snow flakes, and checks current snowflake against bounds
  4845. this.update = function(){
  4846. this.y += this.speed;
  4847.  
  4848. if(this.y > (elHeight) - (this.size + 6)){
  4849. this.reset();
  4850. }
  4851.  
  4852. this.element.style.top = this.y + 'px';
  4853. this.element.style.left = this.x + 'px';
  4854.  
  4855. this.step += this.stepSize;
  4856.  
  4857. if (doRatio === false) {
  4858. this.x += Math.cos(this.step);
  4859. } else {
  4860. this.x += (doRatio + Math.cos(this.step));
  4861. }
  4862.  
  4863. // Pileup check
  4864. if(options.collection){
  4865. if(this.x > this.target.x && this.x < this.target.width + this.target.x && this.y > this.target.y && this.y < this.target.height + this.target.y){
  4866. var ctx = this.target.element.getContext("2d"),
  4867. curX = this.x - this.target.x,
  4868. curY = this.y - this.target.y,
  4869. colData = this.target.colData;
  4870.  
  4871. if(colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] !== undefined || curY+this.speed+this.size > this.target.height){
  4872. if(curY+this.speed+this.size > this.target.height){
  4873. while(curY+this.speed+this.size > this.target.height && this.speed > 0){
  4874. this.speed *= .5;
  4875. }
  4876.  
  4877. ctx.fillStyle = "#fff";
  4878.  
  4879. if(colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] == undefined){
  4880. colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] = 1;
  4881. ctx.fillRect(curX, (curY)+this.speed+this.size, this.size, this.size);
  4882. }else{
  4883. colData[parseInt(curX)][parseInt(curY+this.speed)] = 1;
  4884. ctx.fillRect(curX, curY+this.speed, this.size, this.size);
  4885. }
  4886. this.reset();
  4887. }else{
  4888. // flow to the sides
  4889. this.speed = 1;
  4890. this.stepSize = 0;
  4891.  
  4892. if(parseInt(curX)+1 < this.target.width && colData[parseInt(curX)+1][parseInt(curY)+1] == undefined ){
  4893. // go left
  4894. this.x++;
  4895. }else if(parseInt(curX)-1 > 0 && colData[parseInt(curX)-1][parseInt(curY)+1] == undefined ){
  4896. // go right
  4897. this.x--;
  4898. }else{
  4899. //stop
  4900. ctx.fillStyle = "#fff";
  4901. ctx.fillRect(curX, curY, this.size, this.size);
  4902. colData[parseInt(curX)][parseInt(curY)] = 1;
  4903. this.reset();
  4904. }
  4905. }
  4906. }
  4907. }
  4908. }
  4909.  
  4910. if(this.x + this.size > (elWidth) - widthOffset || this.x < widthOffset){
  4911. this.reset();
  4912. }
  4913. }
  4914.  
  4915. // Resets the snowflake once it reaches one of the bounds set
  4916. this.reset = function(){
  4917. this.y = 0;
  4918. this.x = random(widthOffset, elWidth - widthOffset);
  4919. this.stepSize = random(1,10) / 100;
  4920. this.size = random((options.minSize * 100), (options.maxSize * 100)) / 100;
  4921. this.element.style.width = this.size + 'px';
  4922. this.element.style.height = this.size + 'px';
  4923. this.speed = random(options.minSpeed, options.maxSpeed);
  4924. }
  4925. }
  4926.  
  4927. // local vars
  4928. var i = 0,
  4929. elHeight = $(element).height(),
  4930. elWidth = $(element).width(),
  4931. widthOffset = 0,
  4932. snowTimeout = 0;
  4933.  
  4934. // Collection Piece ******************************
  4935. if(options.collection !== false){
  4936. var testElem = document.createElement('canvas');
  4937. if(!!(testElem.getContext && testElem.getContext('2d'))){
  4938. var canvasCollection = [],
  4939. elements = $(options.collection),
  4940. collectionHeight = options.collectionHeight;
  4941.  
  4942. for(var i =0; i < elements.length; i++){
  4943. var bounds = elements[i].getBoundingClientRect(),
  4944. $canvas = $('<canvas/>',
  4945. {
  4946. 'class' : 'snowfall-canvas'
  4947. }),
  4948. collisionData = [];
  4949.  
  4950. if(bounds.top-collectionHeight > 0){
  4951. $('body').append($canvas);
  4952.  
  4953. $canvas.css({
  4954. 'position' : options.flakePosition,
  4955. 'left' : bounds.left + 'px',
  4956. 'top' : bounds.top-collectionHeight + 'px'
  4957. })
  4958. .prop({
  4959. width: bounds.width,
  4960. height: collectionHeight
  4961. });
  4962.  
  4963. for(var w = 0; w < bounds.width; w++){
  4964. collisionData[w] = [];
  4965. }
  4966.  
  4967. canvasCollection.push({
  4968. element : $canvas.get(0),
  4969. x : bounds.left,
  4970. y : bounds.top-collectionHeight,
  4971. width : bounds.width,
  4972. height: collectionHeight,
  4973. colData : collisionData
  4974. });
  4975. }
  4976. }
  4977. }else{
  4978. // Canvas element isnt supported
  4979. options.collection = false;
  4980. }
  4981. }
  4982. // ************************************************
  4983.  
  4984. // This will reduce the horizontal scroll bar from displaying, when the effect is applied to the whole page
  4985. if($(element).get(0).tagName === $(document).get(0).tagName){
  4986. widthOffset = 25;
  4987. }
  4988.  
  4989. // Bind the Window resize event so we can get the innerHeight again
  4990. $(window).bind("resize", function(){
  4991. elHeight = $(element)[0].clientHeight;
  4992. elWidth = $(element)[0].offsetWidth;
  4993. });
  4994.  
  4995.  
  4996. // initialize the flakes
  4997. for(i = 0; i < options.flakeCount; i+=1){
  4998. flakes.push(new Flake(random(widthOffset,elWidth - widthOffset), random(0, elHeight), random((options.minSize * 100), (options.maxSize * 100)) / 100, random(options.minSpeed, options.maxSpeed)));
  4999. }
  5000.  
  5001. // This adds the style to make the snowflakes round via border radius property
  5002. if(options.round){
  5003. $('.snowfall-flakes').css({'-moz-border-radius' : options.maxSize, '-webkit-border-radius' : options.maxSize, 'border-radius' : options.maxSize});
  5004. }
  5005.  
  5006. // This adds shadows just below the snowflake so they pop a bit on lighter colored web pages
  5007. if(options.shadow){
  5008. $('.snowfall-flakes').css({'-moz-box-shadow' : '1px 1px 1px #555', '-webkit-box-shadow' : '1px 1px 1px #555', 'box-shadow' : '1px 1px 1px #555'});
  5009. }
  5010.  
  5011. // On newer Macbooks Snowflakes will fall based on deviceorientation
  5012. var doRatio = false;
  5013. if (options.deviceorientation) {
  5014. $(window).bind('deviceorientation', function(event) {
  5015. doRatio = event.originalEvent.gamma * 0.1;
  5016. });
  5017. }
  5018.  
  5019. // this controls flow of the updating snow
  5020. function snow(){
  5021. for( i = 0; i < flakes.length; i += 1){
  5022. flakes[i].update();
  5023. }
  5024.  
  5025. snowTimeout = requestAnimationFrame(function(){snow()});
  5026. }
  5027.  
  5028. snow();
  5029.  
  5030. // clears the snowflakes
  5031. this.clear = function(){
  5032. $('.snowfall-canvas').remove();
  5033. $(element).children('.snowfall-flakes').remove();
  5034. cancelAnimationFrame(snowTimeout);
  5035. }
  5036. };
  5037.  
  5038. // Initialize the options and the plugin
  5039. $.fn.snowfall = function(options){
  5040. if(typeof(options) == "object" || options == undefined){
  5041. return this.each(function(i){
  5042. (new $.snowfall(this, options));
  5043. });
  5044. }else if (typeof(options) == "string") {
  5045. return this.each(function(i){
  5046. var snow = $(this).data('snowfall');
  5047. if(snow){
  5048. snow.clear();
  5049. }
  5050. });
  5051. }
  5052. };
  5053.  
  5054. ifSettingIsEnabled('showSnow', function() {
  5055. var flakes;
  5056. ifSettingIsEnabled('snowLight', function() {
  5057. flakes = pageIsGame() ? 40 : 125
  5058. $(document).snowfall({flakeCount : flakes});
  5059. }, function() {
  5060. flakes = pageIsGame() ? 75 : 225
  5061. $(document).snowfall({flakeCount : flakes});
  5062. })
  5063. }, function() {
  5064.  
  5065. })
  5066. }
  5067.  
  5068.  
  5069.  
  5070. /**************************************
  5071.  
  5072. Burn
  5073.  
  5074. **************************************/
  5075.  
  5076. function setupBurn() {
  5077. (function(e){function f(a){this.burning=null;this.settings=a;return this}var d={a:0.3,k:0.05,w:10,wind:1,strength:1,diffusion:1,flames:[{x:0,hsla:[58,96,89,1],y:0,blur:0.1},{x:0,hsla:[51,98,76,1],y:0.02,blur:0.15},{x:0,hsla:[36,100,60,1],y:0.04,blur:0.2},{x:0,hsla:[28,91,49,1],y:0.08,blur:0.25},{x:0,hsla:[19,94,41,1],y:0.15,blur:0.3},{x:0,hsla:[15,75,34,1],y:0.2,blur:0.4},{x:0,hsla:[14,66,16,1],y:0.5,blur:0.5}]};e.fn.burn=function(a,c){var b;if(!1===a)return(b=this.data("_burn"))&&b.off(),this;if("object"===typeof a)c=a;else if("string"==typeof a)return(b=this.data("_burn"))&&void 0!==d[a]?void 0!==c?("title"==a&&b.content.html(c),b.settings[a]=c,!0):b.settings[a]:!1;c=e.extend({},d,c||{});return this.each(function(){var a=e.extend(!0,{},c),a=new f(a);a.elem=e(this);a.ignite();a.elem.data("_burn",a)})};f.prototype={ignite:function(){var a=this;if(a.burning)return a.burning;a.oldShadow=a.elem.css("text-shadow");(function b(){a.timer=window.requestAnimationFrame(b);a.burn()})()},wave:function(a,c,b){var g=this.settings;return b*g.a*Math.sin(g.k*a-g.w*c)},burn:function(){var a=this,c=this.settings,b;b=e.map(c.flames,function(b){var e=-b.y,d=Math.sqrt(Math.random());b.x=a.wave(b.y,Date.now()/1E3,d);return(b.x+c.wind)*b.y*c.strength*c.diffusion+"em "+e*c.strength*c.diffusion+"em "+b.blur*c.strength*c.diffusion+"em hsla("+b.hsla[0]+", "+b.hsla[1]+"%, "+b.hsla[2]+"%, "+b.hsla[3]+")"});a.elem.css("text-shadow",b.join(", "))},off:function(){window.cancelAnimationFrame(this.timer);this.timer=null;this.elem.css("text-shadow",this.oldShadow)}}})(jQuery);(function(){for(var e=0,f=["ms","moz","webkit","o"],d=0;d<f.length&&!window.requestAnimationFrame;++d)window.requestAnimationFrame=window[f[d]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[f[d]+"CancelAnimationFrame"]||window[f[d]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(a){var c=(new Date).getTime(),b=Math.max(0,16-(c-e)),d=window.setTimeout(function(){a(c+b)},b);e=c+b;return d});window.cancelAnimationFrame||(window.cancelAnimationFrame=function(a){clearTimeout(a)})})();
  5078. ifSettingIsEnabled("burningHot", function(){}, function() {
  5079. if(window.location.href.match(/Forum/i)) {
  5080. $(".region:not(:last) td:nth-of-type(2) div *:not(img)").each(function() {
  5081. $(this).html($(this).html().replace(/(flame[a-z]*)/gi, "<span class='burning'>$1</span>"));
  5082. $(this).html($(this).html().replace(/hot/g, "<span class='burning'>hot</span>"));
  5083. $(this).html($(this).html().replace(/(3[0-9] degrees)/g, "<span class='burning'>$1</span>"));
  5084. $(this).html($(this).html().replace(/31°/g, "<span class='burning'>31°</span>"));
  5085. });
  5086. $(".burning").burn({w: 15})
  5087. }
  5088. })
  5089. }
  5090.  
  5091. /**************************************
  5092.  
  5093. Textarea HTML Box
  5094.  
  5095. **************************************/
  5096.  
  5097.  
  5098. function setupTextarea() {
  5099. var controls_default = [
  5100. {title: "<b>B</b>", class: ["tag"], openClose: true, tag: "b"},
  5101. {title: "<i>I</i>", class: ["tag"], openClose: true, tag: "i"},
  5102. {title: "code", class: ["tag"], openClose: true, tag: "code"},
  5103. {title: "img", class: ["tag"], openClose: true, tag: "img"},
  5104. {title: "hr", class: ["tag"], openClose: false, tag: "hr"},
  5105. {title: "quote", class: ["tag"], openClose: true, tag: "quote"},
  5106. {title: "list", class: ["tag"], openClose: true, tag: "list"},
  5107. {title: "*", class: ["tag"], openClose: false, tag: "*"},
  5108. ]
  5109. var controls = "";
  5110. $.each(controls_default, function(key, control) {
  5111. controls += `<span class="button ${control.class.join(" ")}" ${(control.openClose ? `open-close` : ``)} data-tag="${control.tag}">${control.title}</span>`
  5112. })
  5113. $(".region textarea").before(`<div class="editor">${controls}</div>`)
  5114. $("textarea").attr("style", "")
  5115. addCSS(`
  5116. .editor {
  5117. padding: 5px;
  5118. background: brown;
  5119. margin: 5px 5px 0 0;
  5120. }
  5121. .editor .button {
  5122. margin-right: 10px;
  5123. background: rgb(185,122,122);
  5124. padding: 3px 5px;
  5125. border-radius: 5px;
  5126. cursor: pointer;
  5127. }
  5128. textarea {
  5129. padding: 5px 0 0 5px;
  5130. box-sizing: border-box;
  5131. width: calc(100% - 5px);
  5132. max-width: 774px;
  5133. height: 300px
  5134. }
  5135. `)
  5136. createSelector("pre, textarea", "-moz-tab-size: 8;-o-tab-size: 8;tab-size: 8;")
  5137.  
  5138. $(document).on("click", ".editor .tag", function(e) {
  5139. var areaId = $(this).closest(".editor").next().attr("id")
  5140. var area = document.getElementById(areaId)
  5141. var tag = $(e.target).closest(".tag").attr("data-tag")
  5142. if(area) {
  5143. var startPos = area.selectionStart || 0;
  5144. var endPos = area.selectionEnd || 0;
  5145. if($(this).is("[open-close]")) {
  5146. addTagInEditor(area, startPos, endPos, tag)
  5147. } else {
  5148. addCodeInEditor(area, startPos, tag)
  5149. }
  5150. }
  5151. })
  5152. $("textarea").on('keydown', function(e) {
  5153. var keyCode = e.keyCode || e.which;
  5154. if (keyCode == 9) {
  5155. e.preventDefault();
  5156. var areaId = $(this).attr("id")
  5157. var area = document.getElementById(areaId)
  5158. if(area) {
  5159. var oldVal = $(area).val();
  5160. var start = area.selectionStart || 0;
  5161. var end = area.selectionEnd || 0;
  5162. var newVal = oldVal.substring(0, start) + "\t" + oldVal.substring(end)
  5163. if(browserIsFirefox()) {
  5164. $(area).val(newVal)
  5165. area.setSelectionRange(start + 1, start + 1)
  5166. } else {
  5167. document.execCommand("insertText", false, "\t")
  5168. }
  5169. }
  5170. }
  5171. });
  5172.  
  5173. }
  5174.  
  5175. function addCodeInEditor(area, place, tag) {
  5176. var oldVal = $(area).val()
  5177. var newVal = oldVal.substring(0, place) + "[" + tag + "]" + oldVal.substring(place)
  5178. $(area).focus();
  5179. if(browserIsFirefox()) {
  5180. $(area).val(newVal)
  5181. } else {
  5182. document.execCommand("insertText", false, "[" + tag + "]")
  5183. }
  5184. area.setSelectionRange(place + tag.length + 2, place + tag.length + 2)
  5185. $(area).focus();
  5186. }
  5187.  
  5188. function addTagInEditor(area, start, end, tag) {
  5189. var oldVal = $(area).val()
  5190. var selection = oldVal.substring(start, end)
  5191. var newContent = "[" + tag + "]" + selection + "[/" + tag + "]"
  5192. var newVal = oldVal.substring(0, start) + newContent + oldVal.substring(end)
  5193. $(area).focus();
  5194. if(browserIsFirefox()) {
  5195. $(area).val(newVal)
  5196. } else {
  5197. document.execCommand("insertText", false, newContent)
  5198. }
  5199. if(start == end) {
  5200. area.setSelectionRange(start + tag.length + 2, start + tag.length + 2)
  5201. } else {
  5202. area.setSelectionRange(end + 5 + (2 * tag.length), end + 5 + (2 * tag.length))
  5203. }
  5204. $(area).focus();
  5205. }
  5206.  
  5207. function browserIsFirefox() {
  5208. return navigator.userAgent.toLowerCase().indexOf('firefox') > -1
  5209. }
  5210.  
  5211.  
  5212. /**************************************
  5213.  
  5214. INDEXED DB
  5215.  
  5216. **************************************/
  5217.  
  5218.  
  5219. function setupDatabase() {
  5220. log("indexedDB start setup")
  5221. window.Database = {
  5222. db: null,
  5223. Table: {
  5224. Bookmarks: "Bookmarks",
  5225. Settings: "Settings",
  5226. BlacklistedForumThreads: "BlacklistedForumThreads",
  5227. TournamentData: "TournamentData"
  5228. },
  5229. Exports: {
  5230. Bookmarks: "Bookmarks",
  5231. Settings: "Settings",
  5232. BlacklistedForumThreads: "BlacklistedForumThreads"
  5233. },
  5234. Row: {
  5235. BlacklistedForumThreads: {
  5236. ThreadId: "threadId",
  5237. Date: "date"
  5238. },
  5239. Bookmarks: {
  5240. Order: "order"
  5241. },
  5242. Settings: {
  5243. Name: "name"
  5244. },
  5245. TournamentData: {
  5246. Id: "tournamentId",
  5247. }
  5248. },
  5249. init: function(callback) {
  5250. log("indexedDB start init")
  5251. if(!"indexedDB" in window) {
  5252. log("IndexedDB not supported")
  5253. return;
  5254. }
  5255. var openRequest = indexedDB.open("TidyUpYourDashboard_v3", 3);
  5256. openRequest.onupgradeneeded = function(e) {
  5257. var thisDB = e.target.result;
  5258. if(!thisDB.objectStoreNames.contains("Bookmarks")) {
  5259. var objectStore = thisDB.createObjectStore("Bookmarks", {autoIncrement:true});
  5260. objectStore.createIndex("order", "order", {unique:true});
  5261. }
  5262. if(!thisDB.objectStoreNames.contains("Settings")) {
  5263. var objectStore = thisDB.createObjectStore("Settings", { keyPath: "name" });
  5264. objectStore.createIndex("name", "name", {unique: true});
  5265. objectStore.createIndex("value", "value", {unique: false});
  5266. }
  5267. if(!thisDB.objectStoreNames.contains("BlacklistedForumThreads")) {
  5268. var objectStore = thisDB.createObjectStore("BlacklistedForumThreads", {autoIncrement:true});
  5269. objectStore.createIndex("threadId", "threadId", {unique:true});
  5270. objectStore.createIndex("date", "date", {unique:false});
  5271. }
  5272. if(!thisDB.objectStoreNames.contains("TournamentData")) {
  5273. var objectStore = thisDB.createObjectStore("TournamentData",{ keyPath: "tournamentId" });
  5274. objectStore.createIndex("tournamentId", "tournamentId", {unique:true});
  5275. objectStore.createIndex("value", "value", {unique: false});
  5276. }
  5277. }
  5278.  
  5279. openRequest.onsuccess = function(e) {
  5280. log("indexedDB init sucessful");
  5281. db = e.target.result;
  5282. callback()
  5283. }
  5284.  
  5285. openRequest.onerror = function(e) {
  5286. log("Error Init IndexedDB")
  5287. log(e.target.error)
  5288. // alert("Sorry, Tidy Up Your Dashboard is not supported")
  5289. $("<div>Sorry,<br> Tidy Up Your Dashboard is not supported.</div>").dialog();
  5290. }
  5291. },
  5292. update: function(table, value, key, callback) {
  5293. var transaction = db.transaction([table],"readwrite");
  5294. var store = transaction.objectStore(table);
  5295.  
  5296.  
  5297. //Perform the add
  5298. try {
  5299. var request = store.put(value, key != undefined ? Number(key) : undefined);
  5300. request.onerror = function(e) {
  5301. log(`Error saving ${JSON.stringify(value)} in ${table}`)
  5302. log(JSON.stringify(e));
  5303. }
  5304.  
  5305. request.onsuccess = function(e) {
  5306. log(`Saved ${JSON.stringify(value)} in ${table}`)
  5307. callback()
  5308. }
  5309. } catch(e) {
  5310. log(`Error saving ${JSON.stringify(value)} in ${table}`)
  5311. log(JSON.stringify(e));
  5312. }
  5313.  
  5314. },
  5315. read: function(table, key, callback) {
  5316. var transaction = db.transaction([table], "readonly");
  5317. var objectStore = transaction.objectStore(table);
  5318.  
  5319. var ob = objectStore.get(Number(key));
  5320.  
  5321. ob.onsuccess = function(e) {
  5322. var result = e.target.result;
  5323. callback(result)
  5324. }
  5325. },
  5326. readIndex: function(table, row, value, callback) {
  5327. var transaction = db.transaction([table], "readonly");
  5328. var objectStore = transaction.objectStore(table);
  5329.  
  5330. var index = objectStore.index(row);
  5331. //name is some value
  5332. var ob = index.get(value);
  5333.  
  5334. ob.onsuccess = function(e) {
  5335. var result = e.target.result;
  5336. callback(result)
  5337. }
  5338. },
  5339. readAll: function(table, callback) {
  5340. var transaction = db.transaction([table], "readonly");
  5341. var objectStore = transaction.objectStore(table);
  5342. var items = []
  5343.  
  5344. var ob = objectStore.openCursor()
  5345.  
  5346. ob.onsuccess = function(e) {
  5347. var cursor = e.target.result;
  5348. if (cursor) {
  5349. var item = cursor.value;
  5350. item.id = cursor.primaryKey;
  5351. items.push(item);
  5352. cursor.continue();
  5353. } else {
  5354. callback(items)
  5355. }
  5356. }
  5357. },
  5358. add: function(table, value, callback) {
  5359. var transaction = db.transaction([table],"readwrite");
  5360. var store = transaction.objectStore(table);
  5361.  
  5362. try {
  5363. var request = store.add(value);
  5364. request.onerror = function(e) {
  5365. log(`Error saving ${JSON.stringify(value)} in ${table}`)
  5366. log(JSON.stringify(e));
  5367. }
  5368.  
  5369. request.onsuccess = function(e) {
  5370. log(`Saved ${JSON.stringify(value)} in ${table}`)
  5371. callback()
  5372. }
  5373. } catch(e) {
  5374. log(`Error saving ${JSON.stringify(value)} in ${table}`)
  5375. log(JSON.stringify(e));
  5376. }
  5377.  
  5378. request.onerror = function(e) {
  5379. log(`Error saving ${JSON.stringify(value)} in ${table}`)
  5380. log(JSON.stringify(e));
  5381. }
  5382.  
  5383. request.onsuccess = function(e) {
  5384. log(`Saved ${JSON.stringify(value)} in ${table}`)
  5385. callback()
  5386. }
  5387. },
  5388. delete: function(table, key, callback) {
  5389. var transaction = db.transaction([table],"readwrite");
  5390. var store = transaction.objectStore(table);
  5391.  
  5392.  
  5393. //Perform the add
  5394. var request = store.delete(key)
  5395.  
  5396. request.onerror = function(e) {
  5397. log("Error deleting in " + table)
  5398. log(e.target.error);
  5399. //some type of error handler
  5400. }
  5401.  
  5402. request.onsuccess = function(e) {
  5403. log("Deleted in " + table)
  5404. callback()
  5405. }
  5406. },
  5407. clear: function(table, callback) {
  5408. var transaction = db.transaction([table],"readwrite");
  5409. var store = transaction.objectStore(table);
  5410.  
  5411.  
  5412. //Perform the add
  5413. var request = store.clear();
  5414.  
  5415. request.onerror = function(e) {
  5416. log("Error clearing " + table)
  5417. log(e.target.error);
  5418. //some type of error handler
  5419. }
  5420.  
  5421. request.onsuccess = function(e) {
  5422. log("Cleared " + table)
  5423. callback()
  5424. }
  5425. },
  5426.  
  5427. }
  5428.  
  5429. }
  5430.  
  5431. /**************************************
  5432.  
  5433. Other
  5434.  
  5435. **************************************/
  5436.  
  5437. function addCSS(css) {
  5438. head = document.head || document.getElementsByTagName('head')[0],
  5439. style = document.createElement('style');
  5440.  
  5441. style.type = 'text/css';
  5442. if (style.styleSheet) {
  5443. style.styleSheet.cssText = css;
  5444. } else {
  5445. style.appendChild(document.createTextNode(css));
  5446. }
  5447. head.appendChild(style);
  5448. }
  5449.  
  5450. function addVersionLabel() {
  5451. if(!pageIsGame() && !pageIsExamineMap() && !pageIsDesignMap()) {
  5452. $("body").append('<div class="versionLabel">' + GM_info.script.version +'</div>')
  5453. createSelector(".versionLabel", "position:fixed; right:0; bottom: 0; padding: 5px; color: #555; font-size: 10px; cursor:pointer")
  5454. $(".versionLabel").on("click", showUserscriptMenu)
  5455. }
  5456. }
  5457.  
  5458. function WLJSDefined() {
  5459. return (typeof WLJSLoaded) != "undefined" && WLJSLoaded();
  5460. }
  5461.  
  5462. function loadDataTableCSS() {
  5463. var styles = document.createElement("style");
  5464. styles.type = "text/css";
  5465. styles.innerHTML = getDataTableCSS();
  5466. document.body.appendChild(styles);
  5467. }
  5468. function getDataTableCSS() {
  5469. return `table.dataTable thead td,table.dataTable thead th{padding:6px 18px 6px 6px}table.dataTable tfoot td,table.dataTable tfoot th{padding:10px 18px 6px;border-top:1px solid #111}table.dataTable thead .sorting,table.dataTable thead .sorting_asc,table.dataTable thead .sorting_desc{cursor:pointer}table.dataTable thead .sorting,table.dataTable thead .sorting_asc,table.dataTable thead .sorting_asc_disabled,table.dataTable thead .sorting_desc,table.dataTable thead .sorting_desc_disabled{background-repeat:no-repeat;background-position:center right}table.dataTable thead .sorting{background-image:url(https://cdn.datatables.net/1.10.10/images/sort_both.png)}table.dataTable thead .sorting_asc{background-image:url(https://cdn.datatables.net/1.10.10/images/sort_asc.png)}table.dataTable thead .sorting_desc{background-image:url(https://cdn.datatables.net/1.10.10/images/sort_desc.png)}table.dataTable thead .sorting_asc_disabled{background-image:url(https://cdn.datatables.net/1.10.10/images/sort_asc_disabled.png)}table.dataTable thead .sorting_desc_disabled{background-image:url(https://cdn.datatables.net/1.10.10/images/sort_desc_disabled.png)}.dataTables_wrapper{position:relative;clear:both;zoom:1}#PlayersContainer tbody td{border-left:#222 1px solid}#PlayersContainer td{white-space:nowrap}
  5470.  
  5471. .dataTables_filter {
  5472. float: left;
  5473. margin-right: -7px;
  5474. }
  5475.  
  5476. .dataTables_filter label {
  5477. display: inline!important;
  5478. }
  5479.  
  5480. .dataTables_filter input {
  5481. padding: 3px;
  5482. border-radius: 5px;
  5483. margin: 5px;
  5484. }
  5485.  
  5486. .dataTables_info {
  5487. clear: both;
  5488. padding-top: 10px;
  5489. }
  5490.  
  5491. .pagination {
  5492. display: inline-block;
  5493. float: right;
  5494. margin-top: -16px;
  5495.  
  5496. }
  5497. .paginate_button {
  5498. display: inline;
  5499. padding: 5px;
  5500. }.paginate_button.active {
  5501. text-decoration: underline;
  5502. }`
  5503. }
  5504.  
  5505. function getPlotCSS() {
  5506. return `.jqplot-target{position:relative;color:#666;font-family:"Trebuchet MS",Arial,Helvetica,sans-serif;font-size:1em;}.jqplot-axis{font-size:.75em;}.jqplot-xaxis{margin-top:10px;}.jqplot-x2axis{margin-bottom:10px;}.jqplot-yaxis{margin-right:10px;}.jqplot-y2axis,.jqplot-y3axis,.jqplot-y4axis,.jqplot-y5axis,.jqplot-y6axis,.jqplot-y7axis,.jqplot-y8axis,.jqplot-y9axis{margin-left:10px;margin-right:10px;}.jqplot-axis-tick,.jqplot-xaxis-tick,.jqplot-yaxis-tick,.jqplot-x2axis-tick,.jqplot-y2axis-tick,.jqplot-y3axis-tick,.jqplot-y4axis-tick,.jqplot-y5axis-tick,.jqplot-y6axis-tick,.jqplot-y7axis-tick,.jqplot-y8axis-tick,.jqplot-y9axis-tick{position:absolute;}.jqplot-xaxis-tick{top:0;left:15px;vertical-align:top;}.jqplot-x2axis-tick{bottom:0;left:15px;vertical-align:bottom;}.jqplot-yaxis-tick{right:0;top:15px;text-align:right;}.jqplot-yaxis-tick.jqplot-breakTick{right:-20px;margin-right:0;padding:1px 5px 1px 5px;z-index:2;font-size:1.5em;}.jqplot-y2axis-tick,.jqplot-y3axis-tick,.jqplot-y4axis-tick,.jqplot-y5axis-tick,.jqplot-y6axis-tick,.jqplot-y7axis-tick,.jqplot-y8axis-tick,.jqplot-y9axis-tick{left:0;top:15px;text-align:left;}.jqplot-meterGauge-tick{font-size:.75em;color:#999;}.jqplot-meterGauge-label{font-size:1em;color:#999;}.jqplot-xaxis-label{margin-top:10px;font-size:11pt;position:absolute;}.jqplot-x2axis-label{margin-bottom:10px;font-size:11pt;position:absolute;}.jqplot-yaxis-label{margin-right:10px;font-size:11pt;position:absolute;}.jqplot-y2axis-label,.jqplot-y3axis-label,.jqplot-y4axis-label,.jqplot-y5axis-label,.jqplot-y6axis-label,.jqplot-y7axis-label,.jqplot-y8axis-label,.jqplot-y9axis-label{font-size:11pt;position:absolute;}table.jqplot-table-legend{margin-top:12px;margin-bottom:12px;margin-left:12px;margin-right:12px;}table.jqplot-table-legend,table.jqplot-cursor-legend{background-color:rgba(255,255,255,0.6);border:1px solid #ccc;position:absolute;font-size:.75em;}td.jqplot-table-legend{vertical-align:middle;}td.jqplot-seriesToggle:hover,td.jqplot-seriesToggle:active{cursor:pointer;}td.jqplot-table-legend>div{border:1px solid #ccc;padding:1px;}div.jqplot-table-legend-swatch{width:0;height:0;border-top-width:5px;border-bottom-width:5px;border-left-width:6px;border-right-width:6px;border-top-style:solid;border-bottom-style:solid;border-left-style:solid;border-right-style:solid;}.jqplot-title{top:0;left:0;padding-bottom:.5em;font-size:1.2em;}table.jqplot-cursor-tooltip{border:1px solid #ccc;font-size:.75em;}.jqplot-cursor-tooltip{border:1px solid #ccc;font-size:.75em;white-space:nowrap;background:rgba(208,208,208,0.5);padding:1px;}.jqplot-highlighter-tooltip{border:1px solid #ccc;font-size:.75em;white-space:nowrap;background:rgba(208,208,208,0.5);padding:1px;}.jqplot-point-label{font-size:.75em;z-index:2;}td.jqplot-cursor-legend-swatch{vertical-align:middle;text-align:center;}div.jqplot-cursor-legend-swatch{width:1.2em;height:.7em;}.jqplot-error{text-align:center;}.jqplot-error-message{position:relative;top:46%;display:inline-block;}div.jqplot-bubble-label{font-size:.8em;padding-left:2px;padding-right:2px;color:rgb(20%,20%,20%);}div.jqplot-bubble-label.jqplot-bubble-label-highlight{background:rgba(90%,90%,90%,0.7);}div.jqplot-noData-container{text-align:center;background-color:rgba(96%,96%,96%,0.3);}`
  5507. }
  5508.  
  5509. function setupImages() {
  5510. window.IMAGES = {
  5511. EYE: 'https://i.imgur.com/kekYrsO.png',
  5512. CROSS: 'https://i.imgur.com/RItbpDS.png',
  5513. QUESTION: 'https://i.imgur.com/TUyoZOP.png',
  5514. PLUS: 'https://i.imgur.com/lT6SvSY.png',
  5515. SAVE: 'https://i.imgur.com/Ze4h3NQ.png',
  5516. BOOKMARK: 'https://i.imgur.com/c6IxAql.png'
  5517.  
  5518. }
  5519. }
  5520.  
  5521. function setupAWPWorldTour() {
  5522. if($("title").text().toLowerCase().indexOf("awp world tour") != -1) {
  5523. setupAWPRanking();
  5524. setupAWPEvents();
  5525. $("#MainSiteContent div:first").after("<div class='awp'></div>")
  5526. $("#MainSiteContent div:first").css("float", "left")
  5527. $("#MainSiteContent div:first").css("width", "60%")
  5528. $("#MainSiteContent > table").css("width", "100%")
  5529. addCSS(`
  5530. .awp {
  5531. float: left;
  5532. margin: 60px 0 20px 20px;
  5533. width: 30%;
  5534. max-width: 400px;
  5535. }
  5536. .AWPRanking {
  5537. margin-bottom: 20px;
  5538. width: 100%;
  5539. }
  5540. .awpUpdated {
  5541. color: gray;
  5542. float: right;
  5543. font-size: 11px;
  5544. `)
  5545. }
  5546. }
  5547.  
  5548. function setupAWPRanking() {
  5549. var minRow = 12;
  5550. var maxRow = 30;
  5551. var minCol = 1;
  5552. var maxCol = 25;
  5553. var url = `https://spreadsheets.google.com/feeds/cells/1YuV5WqthgmYsZqv4rFVSE1xhM0BKVrcbkivRZ8ht6-E/1/public/values?min-row=${minRow}&max-row=${maxRow}&min-col=${minCol}&max-col=${maxCol}&alt=json-in-script&callback=parseAWPRankingData`
  5554. $.ajax({
  5555. url: url,
  5556. dataType: "script",
  5557. });
  5558. }
  5559.  
  5560. function setupAWPEvents() {
  5561. var minRow = 10;
  5562. var minCol = 1;
  5563. var maxCol = 6;
  5564. var url = `https://spreadsheets.google.com/feeds/cells/1YuV5WqthgmYsZqv4rFVSE1xhM0BKVrcbkivRZ8ht6-E/2/public/values?min-row=${minRow}&min-col=${minCol}&max-col=${maxCol}&alt=json-in-script&callback=parseAWPEventData`
  5565. $.ajax({
  5566. url: url,
  5567. dataType: "script",
  5568. });
  5569. }
  5570.  
  5571. window.parseAWPEventData = function(data) {
  5572. var entries = data.feed.entry
  5573. var lastUpdated = moment(data.feed.updated.$t)
  5574. var table = $('<table class="AWPRanking dataTable"><thead><tr><td colspan="3" class="dataTableTitleRow"><h3 style="margin: 0px"><a href="https://www.warlight.net/Forum/156042-awp-world-tour">AWP World Tour</a>: Events</h3></td></tr><tr><td>Week</td><td>Name</td><td>Champion</td></tr></thead><tbody></tbody></table>')
  5575. var tbody = $("<tbody></tbody>")
  5576. var tr = $("<tr></tr>");
  5577. var events = [];
  5578. var event = {finished: true};
  5579. var currentRow = entries[0].gs$cell.row
  5580. try {
  5581. $.each(entries, function(key, entry){
  5582. var col = entry.gs$cell.col
  5583. var row = entry.gs$cell.row
  5584.  
  5585. if((row - currentRow) >= 3) {
  5586. currentRow = row;
  5587. events.push(event)
  5588. if(event.url.match(/forum/i)) {
  5589. return;
  5590. }
  5591. event = {finished: true}
  5592. }
  5593.  
  5594. if(col == 1 && entry.content.$t) {
  5595. event.url = entry.content.$t.match(/docs.google.com/i) ? undefined : entry.content.$t
  5596. } else if(col == 3) {
  5597. event.date = entry.content.$t
  5598. } else if(col == 4) {
  5599. if(event.name == undefined) {
  5600. event.name = entry.content.$t
  5601. } else if(event.series == undefined) {
  5602. event.series = entry.content.$t
  5603. }
  5604. } else if(col == 5) {
  5605. event.champion = entry.content.$t
  5606. } else if(col == 6) {
  5607. event.finished = false
  5608. }
  5609. })
  5610. } catch(e) {
  5611. log("error parsing awp event data")
  5612. log(e)
  5613. }
  5614. var eventRows = events.filter(function(e){
  5615. return e.url && Math.abs(moment().diff(moment(e.date), 'days')) < 150
  5616. }).map(function(e){
  5617. return `<tr>
  5618. <td>${moment(e.date).format('DD/MMM')}</td>
  5619. <td><a href="${e.url}">${e.name}</a><br>${e.series}</td>
  5620. <td>${e.finished ? e.champion : (e.url.match(/tournament/i) ? "in progress" : "not started")}</td>
  5621. </tr>`
  5622. }).join("")
  5623. tbody.append(eventRows)
  5624. tbody.append(`<tr class="lastRow"><td colspan="3"><span><a target="_blank" href="https://docs.google.com/spreadsheets/d/1Ao0SlM6Kv6CE1-Ha5mBIrI6nj4Uft2lMaE25qbXxWHs/pub?gid=648212339&output=html">Show All</a></span><span class="awpUpdated">Updated ${lastUpdated.from()}</span></td></tr>`)
  5625. table.append(tbody);
  5626. $(".awp").append(table.outerHTML())
  5627. }
  5628. window.parseAWPRankingData = function(data) {
  5629. var entries = data.feed.entry
  5630. var lastUpdated = moment(data.feed.updated.$t)
  5631. var table = $('<table class="AWPRanking dataTable"><thead><tr><td colspan="3" class="dataTableTitleRow"><h3 style="margin: 0px"><a href="https://www.warlight.net/Forum/156042-awp-world-tour">AWP World Tour</a>: Rankings</h3></td></tr><tr><td>Rank</td><td>Name</td><td>Points</td></tr></thead><tbody></tbody></table>')
  5632. var tbody = $("<tbody></tbody>")
  5633. var tr = $("<tr></tr>");
  5634. var url;
  5635. try {
  5636. $.each(entries, function(key, entry){
  5637. var col = entry.gs$cell.col
  5638. var row = entry.gs$cell.row
  5639. if(col == 1) {
  5640. url = entry.content.$t;
  5641. } else if(col == 3) {
  5642. //rank
  5643. tr.append($(`<td>${entry.content.$t}</td>`))
  5644. } else if(col == 5) {
  5645. //name
  5646. tr.append($(`<td><a href="${url}">${entry.content.$t}</a></td>`))
  5647. } else if(col == 25) {
  5648. //points
  5649. tr.append($(`<td>${entry.content.$t}</td>`))
  5650. tbody.append(tr)
  5651. tr = $("<tr></tr>");
  5652. }
  5653. })
  5654. } catch(e) {
  5655. log("error parsing awp event data")
  5656. log(JSON.parse(e))
  5657. }
  5658. table.append(tbody);
  5659. tbody.append(`<tr class="lastRow"><td colspan="3"><span><a target="_blank" href="https://docs.google.com/spreadsheets/d/1Ao0SlM6Kv6CE1-Ha5mBIrI6nj4Uft2lMaE25qbXxWHs/pubhtml">Show All</a></span><span class="awpUpdated">Updated ${lastUpdated.from()}</span></td></tr>`)
  5660.  
  5661. $(".awp").prepend(table.outerHTML())
  5662. }
  5663.  
  5664. /**************************************
  5665.  
  5666. Community Levels
  5667.  
  5668. **************************************/
  5669.  
  5670. function setupCommunityLevels() {
  5671. var fonts = $("#LevelsTable tr td:nth-of-type(2) font:nth-of-type(1)")
  5672. $.each(fonts, function(key, font){
  5673. $(font).html($(font).html().replace(" 0 wins", "<span style='color: khaki'> 0 wins</span>"))
  5674. })
  5675.  
  5676. $("#MainSiteContent").wrapInner("<div id='newestLevels'></div>")
  5677. $("#MainSiteContent").wrapInner("<div id='content'></div>")
  5678. $("#content").append(`
  5679. <div id='sorted'>
  5680. <div id='tabs'>
  5681. <ul>
  5682. <li><a class="tab_hot" href='#tab_hot'>Hot</a></li>
  5683. <li><a class="tab_liked" href='#tab_liked'>Most Liked</a></li>
  5684. <li><a class="tab_hardest" href='#tab_hardest'>Most Difficult</a></li>
  5685. <li><a class="tab_mostplayed" href='#tab_mostplayed'>Most Played</a></li>
  5686. <li><a href='#tab_records_player'>Most Records (Player)</a></li>
  5687. <li><a href='#tab_records_clan'>Most Records (Clan)</a></li>
  5688. <li><a href='#tab_topCreators'>Top Creators</a></li>
  5689. <li><a href='#tab_ownLevels'>Your Levels</a></li>
  5690. </ul>
  5691. <div id='tab_hot'>
  5692. <h2>Popular New Levels</h2>
  5693. </div>
  5694. <div id='tab_liked'>
  5695. <h2>Most Liked Levels</h2>
  5696. </div>
  5697. <div id='tab_hardest'>
  5698. <h2>Most Difficult Levels</h2>
  5699. </div>
  5700. <div id='tab_mostplayed'>
  5701. <h2>Most Played Levels</h2>
  5702. </div>
  5703. <div id='tab_records_player'>
  5704. <h2>Most Records (Player)</h2>
  5705. </div>
  5706. <div id='tab_records_clan'>
  5707. <h2>Most Records (Clan)</h2>
  5708. </div>
  5709. <div id='tab_topCreators'>
  5710. <h2>Top Creators</h2>
  5711. </div>
  5712. <div id='tab_ownLevels'>
  5713. <h2>Your Levels</h2>
  5714. </div>
  5715. </div>
  5716. <p>This data is updated every 12 hours.</p>
  5717. </div>
  5718. <div id="searchLevel">
  5719. <h2>Search Level</h2>
  5720. <input class="searchLevelInput"></input>
  5721. <button class="searchLevelBtn">Search</button>
  5722. <div class="foundLevels"></div>
  5723. </div>`)
  5724.  
  5725. $("#content").prepend(`
  5726. <ul>
  5727. <li><a href='#newestLevels'>Newest Levels</a></li>
  5728. <li><a class='tab_hot' href='#sorted'>Advanced </a></li>
  5729. <li><a class='search' href='#searchLevel'>Search </a></li>
  5730. </ul>`)
  5731. $("h1").prependTo("#MainSiteContent")
  5732. $("#content").tabs();
  5733. $("#sorted").tabs();
  5734.  
  5735. $(".searchLevelBtn").on("click", function() {
  5736. searchLevel()
  5737. })
  5738. $('.searchLevelInput').keyup(function(e){
  5739. if(e.keyCode == 13) {
  5740. searchLevel()
  5741. }
  5742. });
  5743. addCSS(`
  5744. .ui-tabs {
  5745. border: none;
  5746. background: none;
  5747. }
  5748. .ui-tabs-nav {
  5749. background: none;
  5750. border: none;
  5751. border-bottom: 1px gray solid;
  5752. }
  5753. .striped th, .striped td {
  5754. border-bottom: 1px gray solid;
  5755. text-align: left;
  5756. }
  5757. `)
  5758. var mainjsReady = $.Deferred();
  5759. $(".tab_hot").on("click", function() {
  5760. $.when(mainjsReady).done(function () {
  5761. $.each($("#tab_hot tr[data-levelid]:visible"), function(key, row) {
  5762. var id = $(row).attr("data-levelid")
  5763. loadLevelData(id)
  5764. })
  5765. })
  5766. })
  5767. $(".tab_liked").on("click", function() {
  5768. $.when(mainjsReady).done(function () {
  5769. $.each($("#tab_liked tr[data-levelid]:visible"), function(key, row) {
  5770. var id = $(row).attr("data-levelid")
  5771. loadLevelData(id)
  5772. })
  5773. })
  5774. })
  5775. $(".tab_hardest").on("click", function() {
  5776. $.when(mainjsReady).done(function () {
  5777. $.each($("#tab_hardest tr[data-levelid]:visible"), function(key, row) {
  5778. var id = $(row).attr("data-levelid")
  5779. loadLevelData(id)
  5780. })
  5781. })
  5782. })
  5783. $(".tab_mostplayed").on("click", function() {
  5784. $.when(mainjsReady).done(function () {
  5785. $.each($("#tab_mostplayed tr[data-levelid]:visible"), function(key, row) {
  5786. var id = $(row).attr("data-levelid")
  5787. loadLevelData(id)
  5788. })
  5789. })
  5790. })
  5791. $.ajax({
  5792. type: 'GET',
  5793. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=7`,
  5794. dataType: 'jsonp',
  5795. crossDomain: true,
  5796. }).done(function (response) {
  5797. if (response.data) {
  5798. var levels = response.data
  5799. $("#tab_hot").append(`<table id="HotLevelsTable" cellpadding="8"></table>`)
  5800. $.each(levels, function (key, level) {
  5801. $("#HotLevelsTable").append(renderLevelRow(level, key))
  5802. $(`[data-levelid='${level.levelId}']`).attr("data-rating", level.rating)
  5803. })
  5804. $("#HotLevelsTable").append("<button id='loadMoreHot'>Load More</button>")
  5805. $("#loadMoreHot").on("click", function() {
  5806. $.each($("#tab_hot tr:hidden:lt(5)"), function(key, row) {
  5807. $(this).fadeIn()
  5808. $.when(mainjsReady).done(function () {
  5809. loadLevelData($(row).attr("data-levelid"))
  5810. })
  5811. })
  5812. if($("#tab_hot tr:hidden:lt(5)").length == 0) {
  5813. $("#loadMoreHot").remove();
  5814. }
  5815. })
  5816. }
  5817. });
  5818. $.ajax({
  5819. type: 'GET',
  5820. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=8`,
  5821. dataType: 'jsonp',
  5822. crossDomain: true,
  5823. }).done(function (response) {
  5824. if (response.data) {
  5825. var levels = response.data
  5826. $("#tab_liked").append(`<table id="MostLikedLevels" cellpadding="8"></table>`)
  5827. $.each(levels, function (key, level) {
  5828. $("#MostLikedLevels").append(renderLevelRow(level, key))
  5829. $(`[data-levelid='${level.levelId}']`).attr("data-rating", level.rating)
  5830. })
  5831. $("#MostLikedLevels").append("<button id='loadMoreLiked'>Load More</button>")
  5832. $("#loadMoreLiked").on("click", function() {
  5833. $.each($("#tab_liked tr:hidden:lt(5)"), function(key, row) {
  5834. $(this).fadeIn()
  5835. $.when(mainjsReady).done(function () {
  5836. loadLevelData($(row).attr("data-levelid"))
  5837. })
  5838. })
  5839. if($("#tab_liked tr:hidden:lt(5)").length == 0) {
  5840. $("#loadMoreLiked").remove();
  5841. }
  5842. })
  5843. }
  5844. });
  5845. $.ajax({
  5846. type: 'GET',
  5847. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=1`,
  5848. dataType: 'jsonp',
  5849. crossDomain: true,
  5850. }).done(function (response) {
  5851. if (response.data) {
  5852. var levels = response.data
  5853. $("#tab_hardest").append(`<table id="HardestLevelsTable" cellpadding="8"></table>`)
  5854. $.each(levels, function (key, level) {
  5855. $("#HardestLevelsTable").append(renderLevelRow(level, key))
  5856. })
  5857. $("#HardestLevelsTable").append("<button id='loadMoreDifficult'>Load More</button>")
  5858. $("#loadMoreDifficult").on("click", function() {
  5859. $.each($("#tab_hardest tr:hidden:lt(5)"), function(key, row) {
  5860. $(this).fadeIn()
  5861. $.when(mainjsReady).done(function () {
  5862. loadLevelData($(row).attr("data-levelid"))
  5863. })
  5864. })
  5865. if($("#tab_hardest tr:hidden:lt(5)").length == 0) {
  5866. $("#loadMoreDifficult").remove();
  5867. }
  5868. })
  5869. }
  5870. });
  5871. $.ajax({
  5872. type: 'GET',
  5873. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=2`,
  5874. dataType: 'jsonp',
  5875. crossDomain: true,
  5876. }).done(function (response) {
  5877. if (response.data) {
  5878. var levels = response.data
  5879. $("#tab_mostplayed").append(`<table id="MostPlayedLevelsTable" cellpadding="8"></table>`)
  5880. $.each(levels, function (key, level) {
  5881. $("#MostPlayedLevelsTable").append(renderLevelRow(level, key))
  5882. })
  5883. $("#MostPlayedLevelsTable").append("<button id='loadMoreMostPlayed'>Load More</button>")
  5884. $("#loadMoreMostPlayed").on("click", function() {
  5885. $.each($("#tab_mostplayed tr:hidden:lt(5)"), function(key, row) {
  5886. $(this).fadeIn()
  5887. $.when(mainjsReady).done(function () {
  5888. loadLevelData($(row).attr("data-levelid"))
  5889. })
  5890. })
  5891. if($("#tab_mostplayed tr:hidden:lt(5)").length == 0) {
  5892. $("#loadMoreMostPlayed").remove();
  5893. }
  5894. })
  5895. }
  5896. });
  5897. $.ajax({
  5898. type: 'GET',
  5899. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=3`,
  5900. dataType: 'jsonp',
  5901. crossDomain: true,
  5902. }).done(function (response) {
  5903. if (response.data) {
  5904. var players = response.data
  5905. $("#tab_records_player").append(`<table id="PlayerRecordsTable" cellpadding="8" class="striped"></table>`)
  5906. $("#PlayerRecordsTable").prepend(`<thead><th>#</th><th>Name</th><th>Number of Records</th></thead>`)
  5907. $.each(players, function (key, player) {
  5908. $("#PlayerRecordsTable").append(renderRecordPlayerRow(player, key))
  5909. })
  5910. }
  5911. });
  5912. $.ajax({
  5913. type: 'GET',
  5914. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=4`,
  5915. dataType: 'jsonp',
  5916. crossDomain: true,
  5917. }).done(function (response) {
  5918. if (response.data) {
  5919. var clans = response.data
  5920. $("#tab_records_clan").append(`<table id="ClanRecordsTable" cellpadding="8" class="striped"></table>`)
  5921. $("#ClanRecordsTable").prepend(`<thead><th>#</th><th>Name</th><th>Number of Records</th></thead>`)
  5922. $.each(clans, function (key, clan) {
  5923. $("#ClanRecordsTable").append(renderClanRow(clan, key))
  5924. })
  5925. }
  5926. });
  5927. $.ajax({
  5928. type: 'GET',
  5929. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=6`,
  5930. dataType: 'jsonp',
  5931. crossDomain: true,
  5932. }).done(function (response) {
  5933. if (response.data) {
  5934. var players = response.data
  5935. $("#tab_topCreators").append(`<table id="CreatorsTable" cellpadding="8" class="striped"></table>`)
  5936. $("#CreatorsTable").prepend(`<thead><th>#</th><th>Name</th><th>Total Likes</th><th>Total Attempts</th><th>Total Wins</th><th>Overall Win Rate</th><th>Total Levels</th><th>-</th></thead><tbody></tbody>`)
  5937. $.each(players, function (key, player) {
  5938. $("#CreatorsTable tbody").append(renderCreatorPlayerRow(player, key))
  5939. })
  5940. var dataTable = $$$("#CreatorsTable").DataTable({
  5941. paging: false,
  5942. sDom: 't',
  5943. });
  5944. }
  5945. });
  5946. var id = $(".TopRightBar a:nth-of-type(2)").attr("href").match("[0-9]+")[0];
  5947. $.ajax({
  5948. type: 'GET',
  5949. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?p=${id}`,
  5950. dataType: 'jsonp',
  5951. crossDomain: true,
  5952. }).done(function (response) {
  5953. if (response.data) {
  5954. var levels = response.data
  5955. $("#tab_ownLevels").append(`<table id="OwnLevelsTable" cellpadding="8"></table>`)
  5956. $.each(levels, function (key, level) {
  5957. $("#OwnLevelsTable").append(renderLevelRow(level, key, true))
  5958. })
  5959. }
  5960. });
  5961. var div = $("<div></div>")
  5962. var mainjs = "";
  5963. div.load('https://www.warlight.net/SinglePlayer/Level?ID=882053', function(){
  5964. mainjs = div.find("script:contains(MainJS.Init)").html()
  5965. $.getScript("https://d2wcw7vp66n8b3.cloudfront.net/js/Release/wl.js?v=636045359309573936")
  5966. .done(function() {
  5967. eval(mainjs);
  5968. $("#WaitDialogJSWhiteBox").remove();
  5969. $("#WaitDialogJSBacking").remove();
  5970. mainjsReady.resolve();
  5971. })
  5972. });
  5973. }
  5974.  
  5975. function searchLevel() {
  5976. var query = $(".searchLevelInput").val().toLowerCase();
  5977. $(".foundLevels *").remove();
  5978. $.ajax({
  5979. type: 'GET',
  5980. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?q=${query}`,
  5981. dataType: 'jsonp',
  5982. crossDomain: true,
  5983. }).done(function (response) {
  5984. if (response.data) {
  5985. if(response.data.length > 0) {
  5986. var levels = response.data
  5987. $(".foundLevels").append(`<table id="FoundLevelTable" cellpadding="8"></table>`)
  5988. $.each(levels, function (key, level) {
  5989. $("#FoundLevelTable").append(renderLevelRow(level, key))
  5990. })
  5991. } else {
  5992. $(".foundLevels").append(`<span>No levels found!</span>`)
  5993. }
  5994. } else {
  5995. $(".foundLevels").append(`<span>Error searching for levels</span>`)
  5996. }
  5997. });
  5998. }
  5999.  
  6000. function addCSS(css) {
  6001. head = document.head || document.getElementsByTagName('head')[0],
  6002. style = document.createElement('style');
  6003.  
  6004. style.type = 'text/css';
  6005. if (style.styleSheet) {
  6006. style.styleSheet.cssText = css;
  6007. } else {
  6008. style.appendChild(document.createTextNode(css));
  6009. }
  6010. head.appendChild(style);
  6011. }
  6012.  
  6013. function decode (str) {
  6014. var decoded = "";
  6015. try {
  6016. decoded = decodeURIComponent((str + '')
  6017. .replace(/%(?![\da-f]{2})/gi, function () {
  6018. return '%25'
  6019. })
  6020. .replace(/\+/g, '%20'))
  6021. } catch(e) {
  6022. decoded = unescape(str);
  6023. }
  6024. return decoded;
  6025. return decodeURIComponent((str + '')
  6026. .replace(/%(?![\da-f]{2})/gi, function () {
  6027. // PHP tolerates poorly formed escape sequences
  6028. return '%25'
  6029. })
  6030. .replace(/\+/g, '%20'))
  6031. }
  6032.  
  6033. function renderRecordPlayerRow(player, key) {
  6034. var rank = getRankHtml(key+1)
  6035. return `
  6036. <tr>
  6037. <td>${rank}</td>
  6038. <td>
  6039. ${player.recordClanId > 0 ? '<a href="/Clans/?ID=' + player.recordClanId + '" title="' + player.recordClanName + '"><img border="0" style="vertical-align: middle" src="' + player.recordClanImage + '"></a>' : ''}
  6040. <a href="${player.recordHolderUrl}"> ${decode(player.recordHolderName)} </a>
  6041. </td>
  6042. <td>
  6043. ${player.numOfRecords}
  6044. </td>
  6045. </tr>`
  6046. }
  6047.  
  6048. function renderCreatorPlayerRow(player, key) {
  6049. var id = player.createdByUrl.match(/[0-9]+/)[0]
  6050. var rank = getRankHtml(key+1)
  6051. return `
  6052. <tr>
  6053. <td style="text-align:center;padding:0" data-sort="${key+1}">${rank}</td>
  6054. <td>
  6055. ${player.creatorClanId > 0 ? '<a href="/Clans/?ID=' + player.creatorClanId + '" title="' + player.creatorClanName + '"><img border="0" style="vertical-align: middle" src="' + player.creatorClanImage + '"></a>' : ''}
  6056. <a href="${player.createdByUrl}"> ${decode(player.createdByName)} </a>
  6057. </td>
  6058. <td>
  6059. ${player.numOfTotalLikes}
  6060. </td>
  6061. <td>
  6062. ${player.numOfTotalAttempts}
  6063. </td>
  6064. <td>
  6065. ${player.numOfTotalWins}
  6066. </td>
  6067. <td>
  6068. ${(player.numOfTotalWins / player.numOfTotalAttempts * 100).toFixed(2)}%
  6069. </td>
  6070. <td>
  6071. ${player.numOfCreatedLevels}
  6072. </td>
  6073. <td>
  6074. <a href="https://www.warlight.net/SinglePlayer/LevelsByCreator?p=${id.substring(2, id.length-2)}">Show Levels</a>
  6075. </td>
  6076. </tr>`
  6077. }
  6078.  
  6079. function renderClanRow(clan, key) {
  6080. var rank = getRankHtml(key+1)
  6081. return `
  6082. <tr>
  6083. <td>${rank}</td>
  6084. <td>
  6085. <a href="/Clans/?ID=${clan.recordClanId}" title="${clan.recordClanId}"><img border="0" style="vertical-align: middle" src="${clan.recordClanImage}">${decode(clan.recordClanName)}</a>
  6086. </td>
  6087. <td>
  6088. ${clan.numOfRecords}
  6089. </td>
  6090. </tr>`
  6091. }
  6092.  
  6093. function renderLevelRow(level, key, showAll) {
  6094. return `
  6095. <tr data-levelid="${level.levelId}" ${(key >= 10 && showAll != true) ? 'style="display:none"' : ''}>
  6096. <td style="position: relative">
  6097. <img src="${level.mapImage}" width="140" height="80" style="position:relative">
  6098. </td>
  6099. <td>
  6100. <a style="font-size: 17px; color: white"
  6101. href="/SinglePlayer/Level?ID=${level.levelId}">${key+1}. ${decode(level.name)}
  6102. </a> &nbsp;&nbsp;
  6103. <font color="gray">${level.likes} likes, ${level.wins} wins in ${level.attempts} attempts</font><br>
  6104.  
  6105. <font color="gray">Created by</font> ${level.creatorClanId > 0 ? '<a href="/Clans/?ID=' + level.creatorClanId + '" title="' + level.creatorClanName + '"><img border="0" style="vertical-align: middle" src="' + level.creatorClanImage + '"></a>' : ''} <a href="${level.createdByUrl}">${decode(level.createdByName)}</a><br>
  6106.  
  6107. <font color="gray">Record holder:</font> ${level.recordClanId > 0 ? '<a href="/Clans/?ID=' + level.recordClanId + '" title="' + level.recordClanId + '"><img border="0" style="vertical-align: middle" src="' + level.recordClanImage + '"></a>' : ''} ${level.recordHolderName ? '<a href="' + level.recordHolderUrl + '">' + decode(level.recordHolderName) + '</a>' + getTurnText(level.recordHolderText) : 'None'}<br>
  6108.  
  6109. <font color="gray">Win rate: </font>${level.percentage}%<br>
  6110. </td>
  6111. <td><span style="font-size: 17px"><a href="/SinglePlayer?Level=${level.levelId}">Play</a></span></td>
  6112. </tr>`
  6113. }
  6114.  
  6115. function getTurnText(turns) {
  6116. return ` in ${turns} ${turns > 1 ? 'turns' : 'turn'}`
  6117. }
  6118.  
  6119. function getRankHtml(rank) {
  6120. if(rank == 1) {
  6121. return `<img height=30 width=30 style="padding:0" src="https://i.imgur.com/dG4hKlp.gif">`
  6122. } else if(rank == 2) {
  6123. return `<img height=30 width=30 style="padding:0" src="https://imgur.com/qmpjRNs.gif">`
  6124. } else if(rank == 3) {
  6125. return `<img height=30 width=30 style="padding:0" src="https://imgur.com/DgtbQDN.gif">`
  6126. }
  6127. return rank;
  6128. }
  6129.  
  6130. function loadLevelData(id) {
  6131. warlight_shared_viewmodels_spe_SPEManager.GetLevelResult(id, function (levelData) {
  6132. if(levelData && levelData.WinCount > 0) {
  6133. $(`[data-levelid="${id}"] td:nth-of-type(2)`).append(`You won ${getTurnText(levelData.WonInTurns)}`)
  6134. $(`[data-levelid="${id}"] td:nth-of-type(1)`).append('<img src="https://d2wcw7vp66n8b3.cloudfront.net/Images/TransparentCheck.png" width="61" height="53" style="position: absolute; right: 0px; bottom: 0px">')
  6135. }
  6136. $(`[data-levelid="${id}"]`).attr("data-levelid", "done")
  6137.  
  6138. })
  6139. }
  6140.  
  6141. //*************** TWITCH ************************//
  6142. function setupExtendedTwitch() {
  6143. $.getJSON('https://api.twitch.tv/kraken/streams?client_id=m2cojjidnvim6g0go9g2epmafcpv14&game=WarLight', function(data) {
  6144. $(".streamBox").remove();
  6145. if(data && data.streams.length > 1) {
  6146. var last = $("body > div:nth-of-type(1) > div > div:last");
  6147. var offset = last.offset().left + last.width();
  6148. var container = $("<div/>");
  6149. container.css("left", 0)
  6150. container.css("position", "absolute")
  6151. container.css("top", "42px")
  6152. container.css("display", "none")
  6153. container.css("background", "black")
  6154. container.css("padding", "10px")
  6155. container.css("width", "200px")
  6156. container.css("z-index", "100")
  6157. container.css("border", "1px gray solid")
  6158. container.addClass("streamContainer")
  6159. var box = $("<div/>")
  6160. box.html("<a>View all " + data.streams.length + " streams »</a>")
  6161. box.css("position", "relative")
  6162. box.css("display", "inline")
  6163. box.css("padding", "15px 120px 15px 10px")
  6164. box.css("left", offset)
  6165. box.addClass("streamBox")
  6166. var streams = data.streams;
  6167. var html = "";
  6168. $.each(streams, function (key, stream) {
  6169. var streamHTML = getStreamHtml(stream);
  6170. html += streamHTML
  6171. console.log(stream)
  6172. })
  6173. container.html(html)
  6174. box.append(container)
  6175. $("body > div:nth-of-type(1) > div").append(box)
  6176. // $("body").append(container)
  6177. // $(".streamBox").on("mouseover", function() {
  6178. // $(".streamContainer").css("display", "inline");
  6179. // })
  6180. }
  6181.  
  6182. });
  6183. }
  6184.  
  6185. function getStreamHtml(stream) {
  6186. var name = stream.channel.display_name;
  6187. var title = stream.channel.status;
  6188. var url = stream.channel.url;
  6189. var viewers = stream.viewers;
  6190. var startingTime = new Date(stream.created_at).getTime();
  6191. return '<div class="LivestreamInner" title="Streaming now on Twitch.tv by ' + name + '" data-started="' + startingTime + '"><a target="_blank" href="' + url + '"><img src="https://d2wcw7vp66n8b3.cloudfront.net/Images/LiveIcon.jpg" width="29" height="8"> <span class="LivestreamTimer">time</span> <img src="https://d2wcw7vp66n8b3.cloudfront.net/Images/FollowerIcon.png" width="10" height="10"> <span id="LivestreamViewers">' + viewers + '</span><br>' + title + '<br>by ' + name+'</a></div>'
  6192. }
  6193.  
  6194. function StartLivestream() {
  6195. $(".LivestreamInner").tooltip();
  6196. window.setInterval(function() {
  6197. LivestreamTick()
  6198. }, 1000)
  6199. addCSS(`
  6200. .LivestreamTimer {
  6201. color: gray;
  6202. }
  6203. .LivestreamInner {
  6204. font-size: 9px;
  6205. padding-bottom: 5px;
  6206. border-bottom: 1px #222 solid;
  6207. margin-top: 5px;
  6208. }
  6209. .streamBox:hover > .streamContainer, .streamContainer:hover {
  6210. display: inline!important
  6211. }
  6212. .streamBox > a {
  6213. font-size: 9px;
  6214. position: absolute;
  6215. margin-top: 13px;
  6216. cursor:pointer;
  6217. }
  6218. `)
  6219. }
  6220.  
  6221. function LivestreamTick() {
  6222. $.each($(".LivestreamInner"), function(key, elem) {
  6223. var timer = $(elem).find(".LivestreamTimer")
  6224. $(timer).text(GetHMS((new Date).getTime() - parseInt($(elem).attr("data-started"))))
  6225. })
  6226. // var a = $(".LivestreamTimer"),
  6227. // b = $(".LivestreamInner");
  6228. // a.text(GetHMS((new Date).getTime() - parseInt(b.attr("data-started"))))
  6229. }
  6230.  
  6231. function Pad0sTo2(a) {
  6232. return 0 == a.length ? "00" : 1 == a.length ? "0" + a : a
  6233. }
  6234.  
  6235. function GetHMS(a) {
  6236. var b = a / 1E3,
  6237. c = b / 60;
  6238. a = c / 60;
  6239. c = Math.floor(c % 60).toString();
  6240. b = Math.floor(b % 60).toString();
  6241. return 1 <= a ? Math.floor(a) + ":" + Pad0sTo2(c) + ":" + Pad0sTo2(b) : c + ":" + Pad0sTo2(b)
  6242. };

QingJ © 2025

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