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-20 提交的版本,查看 最新版本

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

QingJ © 2025

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