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.3
  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.3";
  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 torunament data")
  696. loadTournamentData();
  697. }
  698. if(pageIsTournament()) {
  699. updateTournamentData()
  700. $("#JoinBtn").on("click", updateTournamentData)
  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 updateTournamentData() {
  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. if(this.checked) {
  2798. hideElimatedTournaments();
  2799. } else {
  2800. showElimnatedTournaments();
  2801. }
  2802. });
  2803. }
  2804.  
  2805. function loadTournamentData() {
  2806. $.each($("#MyTournamentsTable [data-tournamentid]"), function(key, row) {
  2807. if(!$(row).find("[style='color: red']:not(.BootTimeLabel)").length > 0) {
  2808. var id = $(row).attr("data-tournamentid")
  2809. Database.readIndex(Database.Table.TournamentData, Database.Row.TournamentData.Id, Number(id), function(tourn) {
  2810. if(!tourn) {
  2811. Database.update(Database.Table.TournamentData, {tournamentId: Number(id), value: "-", name: "-"}, undefined, function() {})
  2812. }
  2813. })
  2814. }
  2815. })
  2816. Database.readAll(Database.Table.TournamentData, function(tournamentDatas) {
  2817. $.each(tournamentDatas, function(key, tournamentData) {
  2818. if($(`[data-tournamentid='${tournamentData.tournamentId}']`).length) {
  2819. $(`[data-tournamentid='${tournamentData.tournamentId}']`).append(`<td class="tournamentData">${tournamentData.value ? tournamentData.value : "-"}</td>`)
  2820. } else if(tournamentData.value && tournamentData.name) {
  2821. $("#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>`);
  2822. }
  2823. })
  2824. $(".removeTournament").on("click", function() {
  2825. var row = $(this).closest("tr");
  2826. var id = row.attr("data-tournament")
  2827. Database.update(Database.Table.TournamentData, {tournamentId: Number(id), value: false, name: false}, undefined, function() {
  2828. row.remove();
  2829. })
  2830. })
  2831. setDefaultElimnatedTournamentStatus();
  2832. })
  2833. }
  2834.  
  2835. function showElimnatedTournaments() {
  2836. $(".TournamentRow").show();
  2837. updateTournamentCounter();
  2838. }
  2839.  
  2840. function hideElimatedTournaments () {
  2841. $.each($("#MyTournamentsTable [data-tournamentid]"), function(key, row) {
  2842. if($(row).find(".tournamentData").text().indexOf("None") != -1) {
  2843. $(row).hide();
  2844. }
  2845. });
  2846. updateTournamentCounter();
  2847. }
  2848.  
  2849. function updateTournamentCounter() {
  2850. var total = $("#MyTournamentsTable .TournamentRow").length;
  2851. var visible = $("#MyTournamentsTable .TournamentRow:visible").length;
  2852. if(total > visible) {
  2853. $("#MyTournamentsTable h2").text("My Tournaments (" + visible + "/" + total + ")")
  2854. } else {
  2855. $("#MyTournamentsTable h2").text("My Tournaments (" + total + ")")
  2856. }
  2857. };
  2858. window.updateAllTournamentData = function() {
  2859. addCSS(`
  2860. .ui-progressbar {
  2861. position: relative;
  2862. width: 139px;
  2863. height: 20px;
  2864. float: right;
  2865. margin-right: 15px;
  2866. }
  2867. .progress-label {
  2868. position: absolute;
  2869. top: 2px;
  2870. width: 139px;
  2871. text-align: center;
  2872. }
  2873. `)
  2874. $("#dataTournamanetButton").replaceWith('<div id="progressbar"><div class="progress-label"></div></div>')
  2875. var progressbar = $( "#progressbar" );
  2876. var progressLabel = $( ".progress-label" );
  2877. var numOfMyTournaments = $("#MyTournamentsTable [data-tournamentid]").length;
  2878. progressbar.progressbar({
  2879. value: false,
  2880. change: function() {
  2881. progressLabel.text( `${Math.round(progressbar.progressbar("value") * numOfMyTournaments / 100, 0)} / ${$("#MyTournamentsTable [data-tournamentid]").length}` );
  2882. },
  2883. complete: function() {
  2884. progressLabel.text( "Done!" );
  2885. }
  2886. });
  2887. $.each($("#MyTournamentsTable [data-tournamentid]"), function(key, row){
  2888. var id = $(row).attr("data-tournamentid")
  2889. loadTournamentDetails(id, function() {
  2890. progressTournamentData(progressbar, numOfMyTournaments)
  2891. })
  2892. })
  2893. }
  2894.  
  2895. function progressTournamentData(progressbar, max) {
  2896. var val = progressbar.progressbar("value") || 0;
  2897. progressbar.progressbar("value", val + 100 / max +0.001);
  2898.  
  2899. }
  2900.  
  2901. function loadTournamentDetails(id, cb) {
  2902. $(".tournamentData").remove();
  2903. warlight_shared_messages_Message.GetTournamentDetailsAsync(null, warlight_shared_viewmodels_SignIn.Auth, id, new system_Nullable_$Float(999999999), null, function(a,b,c){
  2904. var tournament = c["Tournament"]
  2905. var name = tournament.Settings.Name
  2906. var players = new wljs_multiplayer_tournaments_display_Players(tournament)["_players"];
  2907. var details = getTournamentPlayerInfo(tournament, players, warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID)
  2908. $(`[data-tournamentid='${id}']`).append(`<td class="tournamentData">${details}</td>`)
  2909. Database.update(Database.Table.TournamentData, {tournamentId: Number(id), value: details, name: name}, undefined, function() {
  2910. })
  2911. if(cb) {
  2912. cb();
  2913. }
  2914.  
  2915. })
  2916. }
  2917.  
  2918. window.getTournamentPlayerInfo = function(tournament, players, id) {
  2919. var playerInfo = players["store"]["h"][id]
  2920. var playing = playerInfo.NumInProgress
  2921. var won = playerInfo.NumWins
  2922. var lost = playerInfo.NumLosses
  2923. var myGames = playing + won + lost
  2924. var allowVacations = tournament.Settings.AllowVacations
  2925. // 0 -> Single Elimination, 1 -> Double Elimination, 2 -> Robin Round
  2926. var tournamentType = tournament.Type
  2927. var myMaxGames;
  2928. var tournamentTotalGames;
  2929. var tournamentGamesStarted = tournament.Games.length
  2930. var teamsPerGame = tournament.TeamsPerGame.val;
  2931. var joker = 0;
  2932. if(tournamentType == 0) {
  2933. tournamentTotalGames = (Math.pow(teamsPerGame,tournament.NumberOfRoundsOrNumberOfTeams)-1)/(teamsPerGame-1);
  2934. if(lost == 1) {
  2935. myMaxGames = undefined;
  2936. } else {
  2937. myMaxGames = [0, tournament.NumberOfRoundsOrNumberOfTeams]
  2938. }
  2939. } else if(tournamentType == 1) {
  2940. tournamentTotalGames = 2*Math.pow(2, tournament.NumberOfRoundsOrNumberOfTeams)-1 ;
  2941. if(lost == 0) {
  2942. joker = 1;
  2943. }
  2944. if(lost == 2) {
  2945. myMaxGames = undefined;
  2946. } else {
  2947. myMaxGames = [0, tournament.NumberOfRoundsOrNumberOfTeams * 2]
  2948. }
  2949. } else if(tournamentType == 2) {
  2950. joker = 0;
  2951. var count = 0;
  2952. $.each(players.store.h, function(index, player) {
  2953. if(player.TP.State == 1) {
  2954. count++
  2955. }
  2956. });
  2957. myMaxGames = count / tournament.TeamSize - 1
  2958. tournamentTotalGames = (myMaxGames * myMaxGames +myMaxGames ) / 2
  2959. } else {
  2960. myMaxGames = undefined;
  2961. tournamentTotalGames = undefined;
  2962. }
  2963. var details;
  2964. if(myMaxGames == undefined) {
  2965. details = `
  2966. <font color="#858585">Won:</font> ${won} <br>
  2967. <font color="#858585">Lost:</font> ${lost} <br>
  2968. <font color="#858585">Games left:</font> None <br>
  2969. <font color="#858585">Progress: </font>${getTournamentProgress(tournamentGamesStarted, tournamentTotalGames)} <br>`
  2970. } else if(tournamentGamesStarted == 0) {
  2971. details = `
  2972. <font color="#858585">Games left:</font> ${getGamesLeftString(myGames, myMaxGames, playing, joker)} <br>
  2973. <font color="#858585">Progress: </font>Not started`
  2974. } else {
  2975. details = `
  2976. <font color="#858585">Playing:</font> ${playing} <br>
  2977. <font color="#858585">Won:</font> ${won} <br>
  2978. <font color="#858585">Lost:</font> ${lost} <br>
  2979. <font color="#858585">Games left:</font> ${getGamesLeftString(myGames, myMaxGames, playing, joker)} <br>
  2980. <font color="#858585">Progress: </font>${getTournamentProgress(tournamentGamesStarted, tournamentTotalGames)} <br>`
  2981. }
  2982. log(details)
  2983. return details;
  2984. }
  2985.  
  2986. function getTournamentProgress(tournamentGamesStarted, tournamentTotalGames) {
  2987. var progress = Math.round(tournamentGamesStarted / tournamentTotalGames * 100,0)
  2988. if(progress == 100) {
  2989. return "Almost done"
  2990. } else {
  2991. return progress + "%"
  2992. }
  2993. }
  2994.  
  2995. function getGamesLeftString(myGames, myMaxGames, playing, joker) {
  2996. if (typeof myMaxGames == "number") {
  2997. return (myMaxGames - myGames == 0 ? "None" : (myMaxGames - myGames))
  2998. } else if(typeof myMaxGames == "object") {
  2999. if(playing == 1) {
  3000. if(myMaxGames[1]-myGames == 0) {
  3001. return "None"
  3002. } else {
  3003. return (Math.max(joker, myMaxGames[0]-myGames)) + " - " + (myMaxGames[1]-myGames)
  3004. }
  3005. } else {
  3006. return (Math.max(joker + 1, myMaxGames[0]-myGames)) + " - " + (myMaxGames[1]-myGames)
  3007. }
  3008. } else {
  3009. return "undefined"
  3010. }
  3011. }
  3012.  
  3013. function setTournamentTableHeight() {
  3014. $("#MyTournamentsTable").parent().height(window.innerHeight - 100);
  3015. }
  3016.  
  3017. window.findMeIndex = -1;
  3018. window.findNextInTournament = function() {
  3019. var boxes = getPlayerBoxes();
  3020. var max = boxes.length - 1;
  3021. findMeIndex = findMeIndex == max ? 0 : findMeIndex + 1;
  3022. panzoomMatrix = undefined;
  3023. findInTournament();
  3024. }
  3025.  
  3026. function setupPlayerDataTable() {
  3027. var dataTable = $$$("#PlayersContainer > table").DataTable({
  3028. "order": [],
  3029. paging: false,
  3030. sDom: 't',
  3031. columnDefs: [ {
  3032. targets: [ 0 ],
  3033. orderData: [ 0, 3 ]
  3034. },{
  3035. targets: [ 1 ],
  3036. orderData: [ 1, 0 ]
  3037. },{
  3038. targets: [ 2 ],
  3039. orderData: [ 2, 1, 0 ],
  3040. type: "rank"
  3041. },{
  3042. targets: [ 3 ],
  3043. orderData: [ 3, 1, 0 ]
  3044. },{
  3045. targets: [ 4 ],
  3046. orderData: [ 4, 1, 0 ]
  3047. },{
  3048. targets: [ 5 ],
  3049. orderData: [ 5, 1, 0 ]
  3050. } ],
  3051. "aoColumns": [
  3052. { "orderSequence": [ "asc", "desc" ] },
  3053. { "orderSequence": [ "asc", "desc" ] },
  3054. { "orderSequence": [ "asc", "desc" ] },
  3055. { "orderSequence": [ "desc", "asc" ] },
  3056. { "orderSequence": [ "desc", "asc" ] },
  3057. { "orderSequence": [ "desc", "asc" ] },
  3058. ]
  3059. });
  3060. loadDataTableCSS();
  3061. }
  3062.  
  3063. function setupCommonGamesDataTable() {
  3064. var $$$$$ = jQuery.noConflict(true);
  3065. var dataTable = $$$("#MainSiteContent > table").DataTable({
  3066. "order": [],
  3067. paging: false,
  3068. sDom: 't',
  3069. columnDefs: [ {
  3070. targets: [ 0 ],
  3071. orderData: [ 0, 3 ]
  3072. },{
  3073. targets: [ 1 ],
  3074. orderData: [ 1, 2, 3, 0 ]
  3075. },{
  3076. targets: [ 2 ],
  3077. orderData: [ 2, 3, 0 ]
  3078. },{
  3079. targets: [ 3 ],
  3080. orderData: [ 3, 2, 0 ]
  3081. } ],
  3082. "aoColumns": [
  3083. { "orderSequence": [ "asc", "desc" ] },
  3084. { "orderSequence": [ "asc", "desc" ] },
  3085. { "orderSequence": [ "asc", "desc" ] },
  3086. { "orderSequence": [ "asc", "desc" ] },
  3087. ]
  3088. });
  3089. loadDataTableCSS();
  3090. }
  3091.  
  3092. window.setCurrentplayer = function (player, noSearch) {
  3093. window.currentPlayer = {
  3094. id: player.id,
  3095. name: player.name,
  3096. fullID: player.fullID,
  3097. team: player.team
  3098. };
  3099. $("#selectContainer").toggle(100);
  3100. $("#activePlayer").html(htmlEscape(player.name == self.name ? "Me" : player.name));
  3101. $("#playerSelectInput").val("");
  3102. panzoomMatrix = undefined;
  3103. findMeIndex = 0;
  3104. $(".gold").removeClass("gold")
  3105. $("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").addClass("gold")
  3106. $("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "'] a").addClass("gold")
  3107. if(window.WL_Tournament.Tourn.Type == 2 ) { //Robin Round
  3108. $(".TeamTip_" + (window.currentPlayer.team == "" ? window.currentPlayer.id : window.currentPlayer.team.replace("Team ", "").charCodeAt(0)-65)).addClass("gold")
  3109. } else { //Elimination Tournament
  3110. getPlayerBoxes().find("a").addClass("gold")
  3111. }
  3112. if(noSearch != true) {
  3113. window.findInTournament();
  3114. }
  3115.  
  3116. }
  3117.  
  3118. function setupTournamentFindMe() {
  3119. $("body").keyup(function (event) {
  3120. // "Left" is pressed
  3121. var boxes = getPlayerBoxes();
  3122. var max = boxes.length - 1;
  3123. if(event.which == 37) {
  3124. findMeIndex = findMeIndex == 0 ? max : findMeIndex - 1;
  3125. panzoomMatrix = undefined;
  3126. findInTournament();
  3127. }
  3128. // "Right" is pressed
  3129. else if(event.which == 39) {
  3130. findMeIndex = findMeIndex == max ? 0 : findMeIndex + 1;
  3131. panzoomMatrix = undefined;
  3132. findInTournament();
  3133. }
  3134. // "Home" is pressed
  3135. else if(event.which == 36) {
  3136. findMeIndex = 0;
  3137. panzoomMatrix = undefined;
  3138. findInTournament();
  3139. }
  3140. // "End" is pressed
  3141. else if(event.which == 35) {
  3142. findMeIndex = boxes.length - 1;
  3143. panzoomMatrix = undefined;
  3144. findInTournament();
  3145. }
  3146. });
  3147. window.players = []
  3148. $("[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>');
  3149. 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')
  3150. createSelector('#findMe', 'border: 1px solid #666666;border-bottom-width: 0')
  3151.  
  3152. 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;}'
  3153. addCSS(css)
  3154.  
  3155.  
  3156. $("#findMe").append('<div id="selectContainer"><div id="playerSelectInputContainer"><input placeholder="Search a Player" type="text" id="playerSelectInput"></input></div><div id="playerContainer"></div></div>');
  3157. self = {
  3158. id: warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID,
  3159. name: warlight_shared_viewmodels_SignIn.get_CurrentPlayer().Name,
  3160. 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),
  3161. team: $("[data-playerid='" + warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID + "'] td:nth-of-type(2)").text()
  3162. };
  3163. window.setCurrentplayer(self, true);
  3164. $.each($("#PlayingPlayers tr"), function (key, playerRow) {
  3165. var id = $(playerRow).attr("data-playerid");
  3166. var fullID = $(playerRow).find("a").get($(playerRow).find("a").length - 1).href.replace(/.*warlight.net\/Profile\?p=/, "");
  3167. var name = $(playerRow).find("td a").text();
  3168. var img = $(playerRow).find("td img").attr("src");
  3169. var team = $("[data-playerid='" + id + "'] td:nth-of-type(2)").text();
  3170. if (img && img.indexOf("MemberIcon") > -1) {
  3171. img = "";
  3172. }
  3173. window.players.push({
  3174. id: id,
  3175. fullID: fullID,
  3176. name: name,
  3177. img: img,
  3178. team: team
  3179. });
  3180. });
  3181.  
  3182. $("#playerSelectInput").on('input', function (data) {
  3183. $(".playerElement").remove();
  3184. var search = $(this).val().toLowerCase();
  3185. $("#playerContainer").append("<div class='playerElement' onclick='setCurrentplayer(self)'>" + self.name + " (Me)</div>")
  3186. $.each(window.players, function (key, player) {
  3187. if (player.name.toLowerCase().indexOf(search) > -1 && self.name != player.name) {
  3188. var img = player.img ? "<img src='" + player.img + "'>" : "";
  3189. $("#playerContainer").append("<div onclick='setCurrentplayer(players[" + key + "])' class='playerElement'>" + img + "<span>" + htmlEscape(player.name) + "</span>" + "</div>")
  3190. }
  3191. });
  3192.  
  3193. $("#activePlayer").html(window.currentPlayer.name == self.name ? "Me" : window.currentPlayer.name);
  3194. $("#playerContainer").scrollTop(0)
  3195.  
  3196. });
  3197. $("#playerSelectInput").trigger("input");
  3198.  
  3199. $("#showPlayerSelect").on("click", function () {
  3200. $("#selectContainer").toggle(100);
  3201. $("#playerContainer").scrollTop(0);
  3202. $("#playerSelectInput").trigger("input");
  3203. $("#playerSelectInput").focus();
  3204. });
  3205. createSelector("#playerSelectInputContainer", "height: 28px; ");
  3206. createSelector(".border-red", "border: 3px red solid !important; ");
  3207. createSelector(".playerElement span, .playerElement img", "display:inline-block; margin-right: 10px");
  3208. createSelector("#showPlayerSelect", "color: #DDDDDD;font-size: 14px;margin: 5px 5px 0 -3px;cursor: pointer; display: inline-block;margin-right: 10px;");
  3209. createSelector("#playerSelectInput", "display: block;margin: 5px 3%;width: 93%;");
  3210. createSelector("#activePlayer", "cursor:pointer");
  3211. createSelector(".playerElement", "border-bottom: 1px gray solid;padding: 7px;color: white; clear:both; height: 14px; font-weight: normal;");
  3212. createSelector(".playerElement:hover", "background: rgb(102, 102, 102);");
  3213. createSelector("#playerContainer", "border: 2px gray solid; overflow-y: auto; overflow-x: hidden;max-height: 275px; min-width: 175px; ");
  3214. createSelector(".gold", "color: gold")
  3215. 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");
  3216. }
  3217.  
  3218.  
  3219. window.panzoomMatrix;
  3220. window.findInTournament = function () {
  3221. var id;
  3222. $("#selectContainer").hide(100);
  3223. if ($("[href='#PlayersTab']").parent().hasClass("ui-state-active")) {
  3224. id = window.currentPlayer.id;
  3225. if ($("#PlayingPlayers [data-playerid='" + id + "']").length > 0) {
  3226. var player = $("#PlayingPlayers [data-playerid='" + id + "']");
  3227. var box = $("#CenterTabs").parent()
  3228. var offset = player.offset().top - box.offset().top - box.height() / 2
  3229.  
  3230. box.stop().animate({
  3231. scrollTop: offset
  3232. }, '500', 'swing');
  3233.  
  3234. window.setTimeout(function () {
  3235. $("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").addClass("pulsate");
  3236. window.setTimeout(function () {
  3237. $(".pulsate").removeClass("pulsate");
  3238. }, 1000);
  3239. }, 250);
  3240. } else {
  3241. showInfo("You didn't join this tournament.", $("#findMe").offset().top + 25, $("#findMe").offset().left + 25);
  3242. }
  3243.  
  3244. // Elimination Tournament
  3245. } else if ($("[href='#BracketTab']").parent().hasClass("ui-state-active") && window.WL_Tournament.Tourn.Type != 2) {
  3246. id = window.currentPlayer.fullID;
  3247. //Started
  3248. if (window.WL_Tournament.Tourn.State >= 1 && $("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").length > 0) {
  3249.  
  3250. if (!panzoomMatrix) {
  3251. var currentMatrix = $("#Visualize").panzoom("getMatrix");
  3252. $("#Visualize").panzoom("reset", {
  3253. animate: false
  3254. });
  3255.  
  3256. VisualizePanzoom.panzoom("zoom", {
  3257. increment: 0.75,
  3258. animate: false
  3259. })
  3260. var boxes = getPlayerBoxes();
  3261. $(".TeamBoxHighlighted").removeClass("TeamBoxHighlighted");
  3262. boxes.addClass("TeamBoxHighlighted");
  3263. var offsetTop = $(boxes.get(findMeIndex)).offset().top - $("#VisualizeContainer").offset().top - $("#VisualizeContainer").height() / 4;
  3264. var offsetLeft = $(boxes.get(findMeIndex)).offset().left - $("#VisualizeContainer").offset().left - $("#VisualizeContainer").width() / 2;
  3265.  
  3266. $(".border-red").removeClass("border-red");
  3267. $(boxes.get(findMeIndex)).addClass("border-red");
  3268. $("#Visualize").panzoom("pan", 0 - offsetLeft, 100 - offsetTop, {
  3269. relative: true,
  3270. animate: false
  3271. });
  3272.  
  3273. panzoomMatrix = $("#Visualize").panzoom("getMatrix");
  3274. $("#Visualize").panzoom("setMatrix", currentMatrix, {
  3275. animate: false
  3276. });
  3277. }
  3278.  
  3279. window.setTimeout(function () {
  3280. $("#Visualize").panzoom("setMatrix", panzoomMatrix, {
  3281. animate: true
  3282. })
  3283. window.setTimeout(function () {
  3284. //getPlayerBoxes().addClass("pulsate-border");
  3285. window.setTimeout(function() {
  3286. $(".pulsate-border").removeClass("pulsate-border");
  3287. }, 2000)
  3288. }, 400);
  3289. }, 10)
  3290.  
  3291. } else {
  3292. showFindMeError();
  3293. }
  3294. // Robin Round Tournament
  3295. } else if ($("[href='#BracketTab']").parent().hasClass("ui-state-active") && window.WL_Tournament.Tourn.Type == 2) {
  3296. //Started
  3297. if ($("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").length > 0) {
  3298. $(".TeamTip_" + (window.WL_Tournament.Tourn.TeamSize == 1 ? window.currentPlayer.id : window.currentPlayer.team.replace("Team ", "").charCodeAt(0)-65)).addClass("pulsate")
  3299. window.setTimeout(function() {
  3300. $(".pulsate").removeClass("pulsate")
  3301. }, 2000)
  3302. } else {
  3303. showFindMeError()
  3304. }
  3305. }
  3306. }
  3307.  
  3308. function showFindMeError() {
  3309. if ($("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").length == 0) {
  3310. showInfo("You didn't join this tournament.", $("#findMe").offset().top + 25, $("#findMe").offset().left + 25);
  3311.  
  3312. } else {
  3313. showInfo("This tournament didn't start yet.", $("#findMe").offset().top + 25, $("#findMe").offset().left + 25);
  3314.  
  3315. }
  3316. }
  3317.  
  3318. function getPlayerBoxes() {
  3319. var boxes = $(".GameBox [href='/Profile?p=" + window.currentPlayer.fullID + "']").closest(".TeamBox");
  3320. if(boxes.length == 0) {
  3321. boxes = $("[title='" + window.currentPlayer.team + "']").closest(".TeamBox");
  3322. }
  3323. return boxes;
  3324. }
  3325.  
  3326. function htmlEscape(str) {
  3327. return String(str)
  3328. .replace(/&/g, '&amp;')
  3329. .replace(/"/g, '&quot;')
  3330. .replace(/'/g, '&#39;')
  3331. .replace(/</g, '&lt;')
  3332. .replace(/>/g, '&gt;');
  3333. }
  3334.  
  3335. function bindBookmarkTable() {
  3336. $("#BookmarkTable").bind("contextmenu", function (event) {
  3337. $(".highlightedBookmark").removeClass("highlightedBookmark")
  3338. var row = $(event.target).closest("tr");
  3339. bookmarkId = row.attr("data-bookmarkid")
  3340. bookmarkOrder = row.attr("data-order")
  3341. if(bookmarkId && bookmarkOrder) {
  3342. event.preventDefault();
  3343. row.addClass("highlightedBookmark")
  3344. // Show contextmenu
  3345. $(".bookmark-context").finish().toggle(100).
  3346. css({
  3347. top: event.pageY + "px",
  3348. left: event.pageX + "px"
  3349. });
  3350. }
  3351. });
  3352. }
  3353.  
  3354.  
  3355.  
  3356. function bindCustomContextMenu() {
  3357. // If the document is clicked somewhere
  3358. $(document).bind("mousedown", function (e) {
  3359.  
  3360. // If the clicked element is not the menu
  3361. if (!$(e.target).parents(".context-menu").length > 0) {
  3362.  
  3363. // Hide it
  3364. $(".context-menu").hide(100);
  3365. $(".highlightedBookmark").removeClass("highlightedBookmark")
  3366. }
  3367. });
  3368.  
  3369.  
  3370. // If the menu element is clicked
  3371. $(".context-menu li").click(function(){
  3372.  
  3373. // This is the triggered action name
  3374. switch($(this).attr("data-action")) {
  3375.  
  3376. // A case for each action. Your actions here
  3377. case "first": alert("first"); break;
  3378. case "second": alert("second"); break;
  3379. case "third": alert("third"); break;
  3380. }
  3381.  
  3382. // Hide it AFTER the action was triggered
  3383. $(".context-menu").hide(100);
  3384. });
  3385.  
  3386. }
  3387.  
  3388.  
  3389.  
  3390. function setupRealTimeLadderTable() {
  3391. if($("#RealTimeLadderTable").length == 0) {
  3392. return;
  3393. }
  3394. if( $(".extendedRTLadderRow").length == 0) {
  3395. createSelector(".extendedRTLadderRow .rtBox", "width: calc(100%/2);");
  3396. createSelector(".extendedRTLadderRow span", "");
  3397. createSelector(".rtLeft", "float:left");
  3398. createSelector(".rtRight", "float:Right");
  3399. createSelector(".rtRight a", " padding: 10px 30px;position: absolute;margin-left: -75px;");
  3400. createSelector(".newGamesRT", "display:block");
  3401. createSelector(".rtLabelBig", "font-size: 18px; margin: 5px");
  3402. }
  3403. var joinLeaveText = $(".rtRight a").text()
  3404. var joinLeaveLink = $(".rtRight a").attr("href")
  3405. $(".extendedRTLadderRow").remove();
  3406. $("#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>')
  3407. $("[href='/LadderSeason?ID=3']").text("Ladder Page")
  3408. WLPost("/LadderSeason?ID=3", "WaiterData=1", function(data) {
  3409. if(JSON.parse(data).length > 0) {
  3410. $(".rtRight a").attr("href", "https://www.warlight.net/LadderLeave?Ladder=RealTime")
  3411. $(".rtRight a").text("Leave!")
  3412. } else {
  3413. $(".rtRight a").attr("href", "https://www.warlight.net/LadderJoin?Ladder=RealTime")
  3414. $(".rtRight a").text("Join!")
  3415. }
  3416. });
  3417. setRTLadderTime()
  3418. }
  3419.  
  3420. function setupRealTimeLadderPageTimer() {
  3421. $("#LadderJoinBtn").after("<div>New Games in " + getRealTimeLadderTimerHTML() +"</div>")
  3422. $("#LeaveLadderBtn").after("<div>New Games in " + getRealTimeLadderTimerHTML() +"</div>")
  3423. setRTLadderTime()
  3424. }
  3425.  
  3426. function getRealTimeLadderTimerHTML() {
  3427. return '<span class="rtMin">00</span>:<span class="rtSec">00</span></div></div><div class="rtRight rtBox">'
  3428. }
  3429.  
  3430.  
  3431. function setRTLadderTime() {
  3432. var date = new Date()
  3433. date.setMinutes(Math.ceil((new Date().getMinutes() + date.getSeconds() / 60) / 5) * 5)
  3434. date.setSeconds(0)
  3435. var diff = (date - new Date()) / 1000
  3436. var min = Math.floor(diff / 60) % 60
  3437. diff -= min * 60
  3438. var sec = diff % 60
  3439. $(".rtMin").text(padLeft(min))
  3440. $(".rtSec").text(padLeft(sec))
  3441. }
  3442.  
  3443. function padLeft(str) {
  3444. str = Math.round(str)
  3445. len = 2
  3446. symbol = '0'
  3447. while(String(str).length < len) {
  3448. str = symbol + str;
  3449. }
  3450. return str
  3451. }
  3452.  
  3453. function setupLeagueTable() {
  3454. if($("#LeagueTable").length == 0) {
  3455. $(".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>')
  3456. }
  3457. parseLeagueTable()
  3458. loadClots()
  3459. createSelector(".clotLabel", "display: inline-block; width: 70px")
  3460. createSelector(".clotPlayers", "display: inline-block; margin-left: 5px; color:gray; ")
  3461. }
  3462.  
  3463. function setupLadderClotOverview() {
  3464. $("h1").text($("h1").text() + " & Community Events")
  3465. var clotInfo = getClots()
  3466. if(!clotInfo) {
  3467. return
  3468. }
  3469. var clots = clotInfo
  3470. var ladders = clots['leagues']
  3471. var md = ""
  3472. var rt = ""
  3473. var leagues = ""
  3474. var counter = 0
  3475. $.each(ladders, function (key, val) {
  3476. if (val.type == "realtime") {
  3477. rt += "<li><big><a target='_blank' href=" + val.url + ">" + val.name + "</a> using Real-Time boot times</big></li><br><br>"
  3478. counter++
  3479. } else if (val.type == "multiday") {
  3480. md += "<li><big><a target='_blank' href = " + val.url + ">" + val.name + "</a> using Multi-Day boot times</big></li><br><br>"
  3481. counter++
  3482. } else {
  3483. leagues += `<li><big><a target='_blank' href="${val.url}">${val.name}</a> ${getPlayerString(val.players)}</big></li><br><br>`
  3484. counter++
  3485. }
  3486. })
  3487. $("#MainSiteContent > div").append("Warlight currently has " + toWords(counter) + " Community Events:<br><br>")
  3488. $("#MainSiteContent > div").append("<ul id='clotInfo'></ul>")
  3489. $("#clotInfo").append(rt)
  3490. $("#clotInfo").append(md)
  3491. $("#clotInfo").append(leagues)
  3492. }
  3493.  
  3494. function parseLeagueTable() {
  3495. try {
  3496. var clotInfo = getClots()
  3497. if(!clotInfo) {
  3498. return
  3499. }
  3500. var ladders = clots['leagues']
  3501. var md = ""
  3502. var rt = ""
  3503. var leagues = ""
  3504. $.each(ladders, function (key, val) {
  3505. if (val.type == "realtime") {
  3506. rt += `<tr><td><a target='_blank' href="${val.url}">${val.name} (RT)</a> ${getPlayerString(val.players)}</td></tr>`
  3507. } else if (val.type == "multiday") {
  3508. md += `<tr><td><a target='_blank' href="${val.url}">${val.name} (MD)</a>${getPlayerString(val.players)}</td></tr>`
  3509. } else {
  3510. leagues += `<tr><td><a target='_blank' href="${val.url}">${val.name}</a>${getPlayerString(val.players)}</td></tr>`
  3511. }
  3512. })
  3513. $("#LeagueTable tbody tr").remove()
  3514. $("#LeagueTable tbody").append(leagues)
  3515. $("#LeagueTable tbody").append(md)
  3516. $("#LeagueTable tbody").append(rt)
  3517. $(window).trigger('resize');
  3518. } catch (e) {
  3519. log("Error reading CLOTs")
  3520. log(e.message)
  3521. hideTable("#LeagueTable")
  3522. }
  3523. }
  3524.  
  3525. function getPlayerString(players) {
  3526. if(players) {
  3527. return `<span class='clotPlayers'>${players} players participating</span>`
  3528. }
  3529. return ""
  3530. }
  3531.  
  3532. function getClots() {
  3533. try {
  3534. return clots = $.parseJSON(sessionStorage.getItem('clots'))
  3535. } catch (e) {
  3536. log("Error reading CLOTs")
  3537. log(e.message)
  3538. hideTable("#LeagueTable")
  3539. }
  3540. return undefined
  3541. }
  3542.  
  3543. function loadClots() {
  3544. $.ajax({
  3545. type: 'GET',
  3546. //url: 'https://php-psenough.rhcloud.com/hub/list.php',
  3547. //url: 'https://w115l144.hoststar.ch/test.php',
  3548. url: 'https://php-psenough.rhcloud.com/hub/list_jsonp.php',
  3549. dataType: 'jsonp',
  3550. crossDomain: true,
  3551. }).done(function(response){
  3552. try {
  3553. var json = response.data
  3554. sessionStorage.setItem('clots', JSON.stringify(json));
  3555. parseLeagueTable()
  3556. var datetime = json.datetime
  3557. log("clot update " + datetime)
  3558. } catch (e) {
  3559. log("Error parsing CLOTs")
  3560. log(e)
  3561. }
  3562. }).fail(function(e){
  3563. log("Error loading CLOTs")
  3564. log(e);
  3565. });
  3566. }
  3567.  
  3568.  
  3569. function isJson(str) {
  3570. try {
  3571. JSON.parse(str);
  3572. } catch (e) {
  3573. log(e)
  3574. return false;
  3575. }
  3576. return true;
  3577. }
  3578.  
  3579.  
  3580. function setupRightColumn(isInit) {
  3581. if(isInit) {
  3582. createSelector(".SideColumn > table", "margin-bottom: 17px;")
  3583. }
  3584. //Bookmarks
  3585. if(isInit) {
  3586. setupBookmarkTable()
  3587. } else {
  3588. refreshBookmarks()
  3589. }
  3590. //Tournament
  3591. // #MyTournamentsTable
  3592. //Clots
  3593. setupLeagueTable()
  3594. //RT Ladder
  3595. setupRealTimeLadderTable()
  3596. //Map of the Week
  3597. //Forum Posts
  3598. // hideBlacklistedThreads()
  3599. //Blog Posts
  3600. //Coin Leaderboard
  3601. sortRightColumnTables(function() {
  3602. if(isInit) {
  3603. ifSettingIsEnabled('scrollGames', function() {
  3604. setupFixedTitlesInSideColumn();
  3605. })
  3606. }
  3607. })
  3608. }
  3609.  
  3610. function sortRightColumnTables(callback) {
  3611. var sideColumn = $(".SideColumn")
  3612. getSortTables(function(tables) {
  3613. $.each(tables, function(key, table) {
  3614. if(table.hidden == true) {
  3615. hideTable(table.id)
  3616. } else {
  3617. var table = $(table.id)
  3618. if(table.prev().hasClass("followWrap")) {
  3619. var wrap = table.prev().remove()
  3620. sideColumn.append(wrap)
  3621. }
  3622. table = table.detach()
  3623. sideColumn.append(table)
  3624. }
  3625. })
  3626.  
  3627. $(".SideColumn > br").remove()
  3628. callback();
  3629. })
  3630. }
  3631.  
  3632. function toWords(number) {
  3633. var NS = [
  3634. {value: 1000000000000000000000, str: "sextillion"},
  3635. {value: 1000000000000000000, str: "quintillion"},
  3636. {value: 1000000000000000, str: "quadrillion"},
  3637. {value: 1000000000000, str: "trillion"},
  3638. {value: 1000000000, str: "billion"},
  3639. {value: 1000000, str: "million"},
  3640. {value: 1000, str: "thousand"},
  3641. {value: 100, str: "hundred"},
  3642. {value: 90, str: "ninety"},
  3643. {value: 80, str: "eighty"},
  3644. {value: 70, str: "seventy"},
  3645. {value: 60, str: "sixty"},
  3646. {value: 50, str: "fifty"},
  3647. {value: 40, str: "forty"},
  3648. {value: 30, str: "thirty"},
  3649. {value: 20, str: "twenty"},
  3650. {value: 19, str: "nineteen"},
  3651. {value: 18, str: "eighteen"},
  3652. {value: 17, str: "seventeen"},
  3653. {value: 16, str: "sixteen"},
  3654. {value: 15, str: "fifteen"},
  3655. {value: 14, str: "fourteen"},
  3656. {value: 13, str: "thirteen"},
  3657. {value: 12, str: "twelve"},
  3658. {value: 11, str: "eleven"},
  3659. {value: 10, str: "ten"},
  3660. {value: 9, str: "nine"},
  3661. {value: 8, str: "eight"},
  3662. {value: 7, str: "seven"},
  3663. {value: 6, str: "six"},
  3664. {value: 5, str: "five"},
  3665. {value: 4, str: "four"},
  3666. {value: 3, str: "three"},
  3667. {value: 2, str: "two"},
  3668. {value: 1, str: "one"}
  3669. ];
  3670.  
  3671. var result = '';
  3672. for (var n of NS) {
  3673. if(number>=n.value){
  3674. if(number<=20){
  3675. result += n.str;
  3676. number -= n.value;
  3677. if(number>0) result += ' ';
  3678. }else{
  3679. var t = Math.floor(number / n.value);
  3680. var d = number % n.value;
  3681. if(d>0){
  3682. return intToEnglish(t) + ' ' + n.str +' ' + intToEnglish(d);
  3683. }else{
  3684. return intToEnglish(t) + ' ' + n.str;
  3685. }
  3686.  
  3687. }
  3688. }
  3689. }
  3690. return result;
  3691. }
  3692.  
  3693. function hideTable(seletor) {
  3694. if( $(seletor).prev().hasClass("followWrap")) {
  3695. $(seletor).prev().remove()
  3696. }
  3697. $(seletor).remove()
  3698. }
  3699.  
  3700. window.findMostCommonGames = function() {
  3701. $("#foundPlayers").empty()
  3702. warlight_shared_viewmodels_WaitDialogVM.Start("Searching Players...")
  3703. warlight_shared_messages_Message.GetFriendsAsync(null, warlight_shared_viewmodels_SignIn.Auth, null, function (b, c, players) {
  3704. if (null != c) throw c;
  3705. var myId = warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID;
  3706. warlight_shared_SharedUtility.RemoveWhere(players, function (p) {
  3707. return p.PlayerID == myId
  3708. });
  3709. var topPlayers = [];
  3710. var limit = -1;
  3711. for (var i = 0; i < players.length; i++) {
  3712. var player = players[i];
  3713. if(player.TimesPlayedWithYou > limit || topPlayers.length < 10) {
  3714. topPlayers.push(player)
  3715. topPlayers.sort(function (p1, p2) {
  3716. return p2.TimesPlayedWithYou - p1.TimesPlayedWithYou
  3717. });
  3718. topPlayers = topPlayers.slice(0, 10);
  3719. limit = topPlayers.slice(-1)[0].TimesPlayedWithYou
  3720. }
  3721. }
  3722. warlight_shared_viewmodels_WaitDialogVM.Stop()
  3723. parseFoundFriendPlayers(topPlayers)
  3724. })
  3725. }
  3726.  
  3727. function setupDashboardSearch() {
  3728. loadDataTableCSS();
  3729. $("body").append(`<div class='popup popup840 playersearch-show' style='display: none'>
  3730. <div class='head'>Search<img class='close-popup-img' src='${IMAGES.CROSS}' height='25' width='25'></div>
  3731. <div id="searchTabs">
  3732. <ul>
  3733. <li><a href="#tabs-playerSearch">Player</a></li>
  3734. <li><a href="#tabs-clanSearch">Clan</a></li>
  3735. </ul>
  3736. <div id="tabs-playerSearch">
  3737.  
  3738. <input placeholder='Player Name' id='playerSearchQuery'>
  3739. <button id='searchPlayerBtn'>Search</button>
  3740. <div class='playerSearchTypeSelect'>
  3741. <label for='playerSearchFriend'>Friends</label>
  3742. <input type='radio' id='playerSearchFriend' name='playerSearchType' value='playerSearchFriend' >
  3743. <label for='playerSearchGlobal'>All Players</label>
  3744. <input type='radio' id='playerSearchGlobal' name='playerSearchType' value='playerSearchGlobal' checked>
  3745. </div>
  3746. <button id='findPlayerExtra'>More ▼</button>
  3747. <div id='foundPlayers'></div>
  3748. </div>
  3749. <div id="tabs-clanSearch">
  3750. <!--<input placeholder='Clan Name' id='clanSearchQuery'>
  3751. <button id='searchClanBtn'>Search</button>-->
  3752. <div id='foundClans'></div>
  3753. </div>
  3754. </div>
  3755. </div>`);
  3756. window.tabsInit = false;
  3757. $("#searchTabs").tabs();
  3758. $( "#searchTabs" ).on( "tabsactivate", function( event, ui ) {
  3759. $(ui.newPanel[0]).find("input").focus();
  3760. if($(ui.newPanel[0]).attr("id") == "tabs-clanSearch" && !tabsInit) {
  3761. initClanSearch();
  3762. tabsInit = true;
  3763. }
  3764. } );
  3765. createSelector("#searchTabs", "background: rgb(23, 23, 23);border: none;")
  3766. createSelector(".ui-tabs-nav", "border: none;border-bottom: 2px gray solid;border-radius: 0;background:none;")
  3767. createSelector("#tabs-playerSearch, #tabs-clanSearch", "padding: 15px 0px")
  3768.  
  3769. $("#SubTabRow").append('<td nowrap="nowrap" id="searchPlayerLink" data-subtabcell="Search Player" class="SubTabCell"><a>Search</a></td>');
  3770. $("#searchPlayerLink").on("click", function() {
  3771. showPopup(".playersearch-show")
  3772. $("#playerSearchQuery").val("")
  3773. $("#playerSearchQuery").focus()
  3774. })
  3775. $("#searchPlayerBtn").on("click", function() {
  3776. searchPlayer()
  3777. })
  3778. $("#findPlayerExtra").on("click", function(event) {
  3779. $(".playersearch-context").finish().toggle(100).
  3780. css({
  3781. top: event.pageY + "px",
  3782. left: event.pageX + "px"
  3783. });
  3784. })
  3785. $('#playerSearchQuery').keyup(function(e){
  3786. if(e.keyCode == 13) {
  3787. searchPlayer()
  3788. }
  3789. });
  3790. createSelector(".SubTabCell", "cursor: pointer")
  3791. createSelector(".playersearch-show button", "padding: 5px;float: left; margin: 10px")
  3792. createSelector("#playerSearchQuery, #clanSearchQuery", "width: 200px; padding: 5px; margin: 10px;float: left")
  3793. createSelector(".foundPlayer", "display: block; height: 25px; padding: 2px; clear:both")
  3794. createSelector(".foundPlayer a", "line-height: 25px; float: left")
  3795. createSelector(".foundPlayer img", "height: 15px; display: block; float: left; margin: 5px")
  3796. createSelector(".notFound", "clear: both; display: block; color: gray;")
  3797. createSelector("#foundPlayers span", "color: gray; padding: 0 5px; line-height: 25px")
  3798. createSelector("#foundPlayers > span", "display: block; clear: both; margin: 0px; padding: 10px 0")
  3799. createSelector(".playerSearchName", "float: left")
  3800. createSelector(".playerSearchTypeSelect", "float: left; width: 30%")
  3801. createSelector(".playerSearchTypeSelect label", "color: gray; font-size: 13px; margin: 2px")
  3802. createSelector("#foundClansTable", "float: left; table-layout: fixed;width: 100%")
  3803. createSelector("#foundClansTable thead", "text-align: left")
  3804. createSelector("#foundClansTable td a", "display: block; width: 100%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;height: 19px;")
  3805. createSelector("#foundClansTable img", "margin-right: 5px;")
  3806. }
  3807.  
  3808. function initClanSearch() {
  3809. warlight_shared_viewmodels_WaitDialogVM.Start("Setting up clans...")
  3810. warlight_shared_messages_Message.GetClansAsync(null, null, function (a, b, clans) {
  3811. parseFoundClans(clans)
  3812. warlight_shared_viewmodels_WaitDialogVM.Stop();
  3813. })
  3814. }
  3815.  
  3816. window.blockSearch = false;
  3817. function searchPlayer() {
  3818. if(blockSearch) {
  3819. return;
  3820. }
  3821. blockSearch = true;
  3822. window.setTimeout(function() {
  3823. blockSearch = false;
  3824. }, 3000)
  3825. $("#foundPlayers").empty()
  3826. var query = $("#playerSearchQuery").val().toLowerCase()
  3827. if($('#playerSearchFriend').is(':checked')) {
  3828. warlight_shared_viewmodels_WaitDialogVM.Start("Searching Players...")
  3829. warlight_shared_messages_Message.GetFriendsAsync(null, warlight_shared_viewmodels_SignIn.Auth, null, function (b, c, players) {
  3830. if (null != c) throw c;
  3831. var myId = warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID;
  3832. warlight_shared_SharedUtility.RemoveWhere(players, function (p) {
  3833. return p.Name.toLowerCase().indexOf(query) < 0 || p.PlayerID == myId
  3834. });
  3835. warlight_shared_viewmodels_WaitDialogVM.Stop()
  3836. parseFoundFriendPlayers(players)
  3837. })
  3838. } else {
  3839. if(query.length < 3) {
  3840. warlight_shared_viewmodels_AlertVM.DoPopup("Please enter at least 3 characters to search for");
  3841. return
  3842. }
  3843. warlight_shared_viewmodels_main_manageplayers_ManagePlayersVM.SearchPlayers(query, function (players) {
  3844. players = players.Results
  3845. if(players.length >= 25) {
  3846. $("#foundPlayers").append("<span>This query found more than 25 results. Only the first 25 results are shown below.</span>")
  3847. }
  3848. parseFoundGlobalPlayers(players)
  3849. $("#playerSearchQuery").focus()
  3850. $("#playerSearchQuery").select()
  3851. })
  3852. }
  3853. }
  3854. function parseFoundFriendPlayers(players) {
  3855. if(!players || players.length == 0) {
  3856. $("#foundPlayers").append("<span class='notFound'>No Players found.</span>");
  3857. return;
  3858. }
  3859. players.sort(function (p1, p2) {
  3860. return (p2.TimesPlayedWithYou - p1.TimesPlayedWithYou != 0) ? p2.TimesPlayedWithYou - p1.TimesPlayedWithYou : p1.Level > p2.Level
  3861. });
  3862. for (var i = 0; i < players.length; i++) {
  3863. var player = players[i];
  3864. var id = String(player.ProfileToken).substr(0, 2) + String(player.PlayerID) + String(player.ProfileToken).substr(2, 2);
  3865. var nameLink = '<a href="/Profile?p=' + id + '">' + player.Name + '</a>'
  3866. 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>' : "";
  3867. var member = player.IsMember ? '<img class="playerSearchMember" src="https://d2wcw7vp66n8b3.cloudfront.net/Images/MemberIcon.png">' : "";
  3868. var description = '<div class="playerSearchName">' + nameLink + member + "<span>(Level " + player.Level + ", " + player.TimesPlayedWithYou + " common games)</span></div>";
  3869. $("#foundPlayers").append('<div class="foundPlayer">' + clan + description + '</div>')
  3870. }
  3871. }
  3872.  
  3873. function parseFoundClans(clans) {
  3874. clans.sort(function (c1, c2) {
  3875. return (c2.TotalPointsInThousands - c1.TotalPointsInThousands)
  3876. });
  3877. 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>'
  3878. for (var i = 0; i < clans.length; i++) {
  3879. var clan = clans[i];
  3880. var name = clan.Name;
  3881. var id = clan.ID;
  3882. var createdBy = clan.CreatedBy;
  3883. var iconId = clan.IconIncre;
  3884. var imgTag = iconId == 0 ? "" : `<img src="https://d32kaghj56y4ei.cloudfront.net/Data/Clans/${id}/Icon/${iconId}.png">`;
  3885. var totalpoints = (clan.TotalPointsInThousands * 1000).toLocaleString("en")
  3886. var createdDate = moment(clan.CreatedDate.date).format('MM/DD/YYYY')
  3887. var nameHTML = `<a target="_blank" href="https://www.warlight.net/Clans/?ID=${id}">${imgTag}${name}</a>`;
  3888. 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>`
  3889. }
  3890. clanTableHTML += "</table>"
  3891. $("#foundClans").append(clanTableHTML)
  3892. var dataTable = $$$("#foundClansTable").DataTable({
  3893. "order": [],
  3894. paging: true,
  3895. "pageLength": 10,
  3896. "bLengthChange": false,
  3897. "autoWidth": false,
  3898. columnDefs: [ {
  3899. targets: [ 0 ],
  3900. searchable: false
  3901. },{
  3902. targets: [ 1 ],
  3903. orderData: [ 1, 0 ],
  3904. sortable: false
  3905. },{
  3906. targets: [ 2 ],
  3907. orderData: [ 2, 1, 0 ],
  3908. sortable: false,
  3909. searchable: false
  3910. },{
  3911. targets: [ 3 ],
  3912. orderData: [ 3, 1, 0 ],
  3913. type: "numeric-comma"
  3914. } ,{
  3915. targets: [ 4 ],
  3916. orderData: [ 4, 1]
  3917. } ],
  3918. "aoColumns": [
  3919. { "orderSequence": [ "desc", "asc" ] },
  3920. {"orderSequence": [ "asc", "desc" ] },
  3921. { "orderSequence": [ "asc", "desc" ] },
  3922. { "orderSequence": [ "asc", "desc" ] },
  3923. { "orderSequence": [ "desc", "asc" ] },
  3924. ],
  3925. initComplete: function() {
  3926. window.setTimeout(loadClanCreators, 200);
  3927. },
  3928. "language": {
  3929. "zeroRecords": "No matching clans found",
  3930. "info": "Showing _START_ to _END_ of _TOTAL_ clans",
  3931. "infoEmpty": "Showing 0 to 0 of 0 clans",
  3932. "infoFiltered": "(filtered from _MAX_ total clans)",
  3933. }
  3934.  
  3935. });
  3936.  
  3937. dataTable.on('draw.dt', function () {
  3938. loadClanCreators()
  3939. })
  3940.  
  3941. }
  3942.  
  3943. function loadClanCreators() {
  3944. $.each($(".data-player"), function(k, cell) {
  3945. if($(cell).hasClass("data-player") && $(cell).is(":visible")) {
  3946. var id = $(cell).attr("data-player-id")
  3947. $.ajax({
  3948. type: 'GET',
  3949. url: `https://w115l144.hoststar.ch/wl/wl_profile.php?p=${id}`,
  3950. dataType: 'jsonp',
  3951. crossDomain: true,
  3952. }).done(function(response){
  3953. if(isFinite(response.data) ){
  3954. $(`[data-player-id="${id}"]`).html(`<a target="_blank" href="https://www.warlight.net/Profile?p=${response.data}">${decodeURI(atob(response.name)) || "Unknown"}</a>`)
  3955. } else {
  3956. $(`[data-player-id="${id}"]`).html(`Unknown`)
  3957. }
  3958. if($(cell).is(":visible")) {
  3959. $(cell).removeClass("data-player");
  3960. }
  3961.  
  3962. });
  3963. }
  3964.  
  3965. });
  3966. }
  3967.  
  3968. function parseFoundGlobalPlayers(players) {
  3969. if(!players || players.length == 0) {
  3970. $("#foundPlayers").append("<span class='notFound'>No Players found.</span>");
  3971. return;
  3972. }
  3973. players.sort(function(p1, p2){
  3974. return (p2.Level - p1.Level != 0) ? p2.Level - p1.Level : p1.Name > p2.Name
  3975. });
  3976.  
  3977. for (var i = 0; i < players.length; i++) {
  3978. var player = players[i];
  3979. var id = String(player.ProfileToken).substr(0, 2) + String(player.PlayerID) + String(player.ProfileToken).substr(2, 2);
  3980. var nameLink = '<a href="/Profile?p=' + id + '">' + player.Name + '</a>'
  3981. 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>' : "";
  3982. var member = player.IsMember ? '<img class="playerSearchMember" src="https://d2wcw7vp66n8b3.cloudfront.net/Images/MemberIcon.png">' : "";
  3983. var name = '<div class="playerSearchName">' + nameLink + "<span>(" + player.Level + ")</span></div>";
  3984. $("#foundPlayers").append('<div class="foundPlayer">' + clan + name + member + '</div>');
  3985. }
  3986. }
  3987.  
  3988. function validateUser() {
  3989. if(pageIsLogin()) {
  3990. setUserInvalid();
  3991. }
  3992. if(WLJSDefined() && warlight_shared_viewmodels_ConfigurationVM.Settings) {
  3993. ifSettingIsEnabled("wlUserIsValid", function() {
  3994. }, function() {
  3995. var player = warlight_shared_viewmodels_SignIn.get_CurrentPlayer();
  3996. $.ajax({
  3997. type: 'GET',
  3998. 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,
  3999. dataType: 'jsonp',
  4000. crossDomain: true,
  4001. }).done(function(response){
  4002. if(response.data.valid) {
  4003. log(atob(response.data.name) + " was validated on "+ new Date(response.data.timestamp * 1000));
  4004. setUserValid();
  4005. }
  4006. });
  4007. })
  4008. }
  4009. }
  4010.  
  4011.  
  4012. function setUserInvalid() {
  4013. Database.update(Database.Table.Settings, {name: "wlUserIsValid", value: false}, undefined, function() {
  4014. })
  4015. }
  4016.  
  4017. function setUserValid() {
  4018. Database.update(Database.Table.Settings, {name: "wlUserIsValid", value: true}, undefined, function() {
  4019. })
  4020. }
  4021.  
  4022. var mapData;
  4023. function setupMapSearch() {
  4024. $("#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>')
  4025. $('#mapSearchQuery').on('keypress', function (event) {
  4026. if(event.which === 13){
  4027. searchMaps();
  4028. }
  4029. });
  4030. $("#mapSearchBtn").on("click", function() {
  4031. searchMaps();
  4032. })
  4033. $("#FilterBox, #SortBox, #PerPageBox").on("change", function() {
  4034. $("#mapSearchQuery").val("")
  4035. $("#searchResultsTitle").remove()
  4036. })
  4037.  
  4038. }
  4039.  
  4040. function searchMaps() {
  4041. if(mapData == undefined) {
  4042. $("<div />").load('Ajax/EnumerateMaps?Filter=' + 1 + '&Sort=' + 1 + "&PerPage=" + 2147483647 + "&Offset=" + 0, function(data) {
  4043. mapData = data;
  4044. filterMaps(this);
  4045. })
  4046. } else {
  4047. var maps = $("<div />").html(mapData)
  4048. filterMaps(maps);
  4049. }
  4050. }
  4051.  
  4052. function filterMaps(selector) {
  4053. var query = $("#mapSearchQuery").val()
  4054. $.each($(selector).find("div"), function(key, div) {
  4055. if($(div).text().trim().toLowerCase().replace(/(rated.*$)/, "").indexOf(query.toLowerCase()) == -1) {
  4056. $(div).remove()
  4057. }
  4058. })
  4059. var count = $(selector).find("div").length
  4060. $('#MapsContainer').empty()
  4061. $(selector).detach().appendTo('#MapsContainer')
  4062. $("#MapsContainer tr:last-of-type").html("Showing maps 1 - " + count + " of " + count);
  4063. $("#ReceivePager").html("Showing maps 1 - " + count + " of " + count);
  4064. $("#searchResultsTitle").length > 0 ? $("#searchResultsTitle").html("Searchresults for <i>" + query +"</i>") : $("#ReceivePager").after("<h2 id='searchResultsTitle'>Searchresults for <i>" + query +"</i></h2>")
  4065. }
  4066.  
  4067. function setupLevelBookmark() {
  4068. $("h1").after(`
  4069. <a style="cursor:pointer" onclick="bookmarkLevel()">Bookmark</a><br>
  4070. `)
  4071. }
  4072.  
  4073. function setupPlayerAttempDataTable() {
  4074. var playerData = []
  4075. $("#MainSiteContent ul").find("li").map(function(){
  4076. var player = $(this).children().map(function(){return $(this).outerHTML()}).get().join("")
  4077. var str = $(this).clone().children().remove().end().text();
  4078. var attemps = str.split(", ")[0].replace(/[^0-9]/g, '')
  4079. var wins = str.split(", ")[1].replace(/[^0-9]/g, '')
  4080. playerData.push({
  4081. player: player,
  4082. attemps: attemps,
  4083. wins: wins
  4084. })
  4085. })
  4086. var table = "<table id='playlogPreview'><thead><th>Name</th><th>Attemps</th><th>Wins</th></thead>"
  4087. $.each(playerData, function(k, player) {
  4088. var tr = `<tr><td>${player.player}</td><td>${player.attemps}</td><td>${player.wins}</td></tr>`;
  4089. table += tr;
  4090. })
  4091. table += "</table>"
  4092. $("#MainSiteContent ul").replaceWith(table)
  4093. loadDataTableCSS();
  4094. var dataTable = $$$("#playlogPreview").DataTable({
  4095. "order": [2],
  4096. paging: false,
  4097. sDom: 't',
  4098. columnDefs: [ {
  4099. targets: [ 0, 1, 2 ],
  4100. },{
  4101. targets: [ 1 ],
  4102. orderData: [ 1, 2, 0 ]
  4103. },{
  4104. targets: [ 2 ],
  4105. orderData: [ 2, 1, 0 ],
  4106.  
  4107. }],
  4108. "aoColumns": [
  4109. { "orderSequence": [ "asc", "desc" ] },
  4110. { "orderSequence": [ "desc", "asc" ] },
  4111. { "orderSequence": [ "desc", "asc" ] },
  4112. ],
  4113.  
  4114. });
  4115. addCSS(`
  4116. #playlogPreview a {
  4117. margin-right: 10px;
  4118. }
  4119. #playlogPreview td {
  4120. white-space: nowrap;
  4121. }
  4122. `)
  4123.  
  4124. }
  4125.  
  4126.  
  4127. /**************************************
  4128.  
  4129. MANAGER LEAGUE
  4130. **************************************/
  4131.  
  4132. function setupManagerLeague() {
  4133. var script = document.createElement("script");
  4134. script.type = "text/javascript";
  4135. document.body.appendChild( script );
  4136. script.src = "https://cdn.jsdelivr.net/jqplot/1.0.8/jquery.jqplot.min.js";
  4137. script.onload = function() {
  4138. log("loaded1")
  4139. var script2 = document.createElement("script");
  4140. script2.type = "text/javascript";
  4141. document.body.appendChild( script2 );
  4142. script2.src = "https://cdn.jsdelivr.net/jqplot/1.0.8/plugins/jqplot.highlighter.min.js";
  4143. script2.onload = function() {
  4144. log("loaded2")
  4145. }
  4146. }
  4147. var styles = document.createElement("style");
  4148. styles.type = "text/css";
  4149. styles.innerHTML = getPlotCSS();
  4150. document.body.appendChild(styles);
  4151. var cosPoints = [];
  4152. for (var i=0; i<2*Math.PI; i+=0.1){
  4153. cosPoints.push([i, Math.cos(i)]);
  4154. }
  4155. log(cosPoints)
  4156. $.ajax({
  4157. type: 'GET',
  4158. url: 'https://w115l144.hoststar.ch/wl/managerleague.php',
  4159. dataType: 'jsonp',
  4160. crossDomain: true,
  4161. }).done(function(response){
  4162. try {
  4163. var max = 100;
  4164. var json = response.data
  4165. $.jqplot.config.enablePlugins = true;
  4166. this.tooltipOffset = 100
  4167. $("#MainSiteContent > table tr:nth-of-type(2) > td:nth-of-type(3)").append('<div id="ManagerLeaguePrice" style="width:500px; height:200px;"></div>')
  4168. var points = [];
  4169. var ticksx = [];
  4170. for (var i = 1; i < json[0]["prices"].length; i++){
  4171. var price = json[0]["prices"][i]
  4172. max = price > 100 ? price : max
  4173. points.push([i, price])
  4174. ticksx.push([i, "Week " + i])
  4175. }
  4176. log(points)
  4177. var plot1 = $.jqplot('ManagerLeaguePrice', [points], {
  4178. series:[{color: '#5FAB78'}],
  4179. title: 'Ranking',
  4180. axes:{
  4181. xaxis:{
  4182. label:'Time',
  4183. min: 0,
  4184. ticks: ticksx,
  4185. tickOptions:{
  4186. formatString:'Time %s'
  4187. }
  4188. },
  4189. yaxis:{
  4190. label:'Rank',
  4191. min: 0,
  4192. max: Math.ceil(max/25)*25,
  4193. numberTicks: max / 25 + 1,
  4194. tickOptions:{
  4195. formatString:'%d r'
  4196. }
  4197. },
  4198. axesDefaults: {
  4199. labelRenderer: $.jqplot.CanvasAxisLabelRenderer
  4200. },
  4201. grid: {
  4202. backgroundColor: '#DEA493'
  4203. },
  4204. }
  4205. });
  4206. } catch (e) {
  4207. log("Error parsing Manager League")
  4208. log(e)
  4209. }
  4210. }).fail(function(e){
  4211. log("Error loading Manager League")
  4212. log(e);
  4213. });
  4214. }
  4215.  
  4216. /**************************************
  4217.  
  4218. SPAMMERS BE GONE BLACKLISTEDTHREADS
  4219. **************************************/
  4220.  
  4221. window.undoIgnore = function() {
  4222. // reset blacklisted threads to empty list
  4223. Database.clear(Database.Table.BlacklistedForumThreads, function() {
  4224. if(pageIsForumOverview() || pageIsSubForum()) {
  4225. $("#MainSiteContent > table tbody table:nth-of-type(2) tr .checkbox").prop("checked", false)
  4226. $("#MainSiteContent > table tbody table:nth-of-type(2) tr").show()
  4227. } else if(pageIsDashboard()) {
  4228. $("#ForumTable tr").show()
  4229. } else {
  4230. location.reload;
  4231. }
  4232. })
  4233. }
  4234.  
  4235. function replaceAndFilterForumTable(tableHTML) {
  4236. var table = $.parseHTML(tableHTML);
  4237. var promises = [];
  4238. $.each($(table).find("tr"), function (key, row) {
  4239. if(threadId = $(row).html().match(/href="\/Forum\/([^-]*)/mi)) {
  4240. promises[key] = $.Deferred();
  4241. Database.readIndex(Database.Table.BlacklistedForumThreads, Database.Row.BlacklistedForumThreads.ThreadId, threadId[1], function(thread) {
  4242. if(thread) {
  4243. $(row).hide();
  4244. }
  4245. promises[key].resolve();
  4246. })
  4247. }
  4248. })
  4249. $.when.apply($, promises).done(function () {
  4250. $("#ForumTable").replaceWith($(table).outerHTML())
  4251. ifSettingIsEnabled('disableHideThreadOnDashboard', function() {
  4252. }, function() {
  4253. $("#ForumTable").unbind();
  4254. $("#ForumTable").bind("contextmenu", function (event) {
  4255. $(".highlightedBookmark").removeClass("highlightedBookmark")
  4256. var row = $(event.target).closest("tr")
  4257. row.addClass("highlightedBookmark")
  4258. // Avoid the real one
  4259. if(row.is(":last-child")) {
  4260. return;
  4261. }
  4262. event.preventDefault();
  4263. threadId = row.html().match(/href="\/Forum\/([^-]*)/mi);
  4264. if (threadId) {
  4265. activeThreadId = threadId[1]
  4266. } else {
  4267. return
  4268. }
  4269.  
  4270. // Show contextmenu
  4271. $(".thread-context").finish().toggle(100).
  4272.  
  4273. // In the right position (the mouse)
  4274. css({
  4275. top: event.pageY + "px",
  4276. left: event.pageX + "px"
  4277. });
  4278. });
  4279. })
  4280. });
  4281. }
  4282.  
  4283. var activeThreadId;
  4284. function hideBlacklistedThreads() {
  4285. replaceAndFilterForumTable($("#ForumTable").outerHTML())
  4286. }
  4287.  
  4288. window.hideThread = function() {
  4289. clearOldBlacklistedThreads();
  4290. var thread = {
  4291. threadId: activeThreadId,
  4292. date: new Date().getTime()
  4293. }
  4294. Database.add(Database.Table.BlacklistedForumThreads, thread, function() {
  4295. hideBlacklistedThreads();
  4296. })
  4297. }
  4298.  
  4299. function hideOffTopicThreads() {
  4300. $.each($("#MainSiteContent > table tbody table:nth-of-type(2) tr:visible"), function(key, row) {
  4301. if($(row).find("td:first-of-type").text().trim() == "Off-topic") {
  4302. var threadId = $(row).html().match(/href="\/Forum\/([^-]*)/mi)
  4303. Database.add(Database.Table.BlacklistedForumThreads, {threadId: threadId[1], date: new Date().getTime()}, function() {
  4304. $(row).hide()
  4305. })
  4306. }
  4307. })
  4308. }
  4309.  
  4310. function formatHiddenThreads() {
  4311. $("#HiddenThreadsRow td").attr("colspan", "")
  4312. $("#HiddenThreadsRow td").before("<td/>")
  4313. $("#HiddenThreadsRow td").css("text-align", "left")
  4314. }
  4315.  
  4316. function setupSpammersBeGone() {
  4317. var path = window.location.pathname;
  4318. if(pageIsForumThread()) {
  4319. // TODO : Ignore posts from blacklisted players
  4320. }
  4321.  
  4322. if(pageIsForumOverview()) {
  4323. // Do nothing
  4324. }
  4325.  
  4326. if(pageIsForumOverview()) {
  4327. newColumnCountOnPage = 6;
  4328. showIgnoreCheckBox(newColumnCountOnPage);
  4329. hideIgnoredThreads();
  4330. }
  4331.  
  4332. if(pageIsSubForum()) {
  4333. newColumnCountOnPage = 5;
  4334. showIgnoreCheckBox(newColumnCountOnPage);
  4335. hideIgnoredThreads();
  4336. }
  4337. $(".thread-hide.eye-icon").on("click", function(){
  4338. clearOldBlacklistedThreads();
  4339. var threadId = $(this).closest("tr").html().match(/href="\/Forum\/([^-]*)/mi)
  4340. Database.add(Database.Table.BlacklistedForumThreads, {threadId : threadId[1], date: new Date().getTime()}, function() {
  4341. hideIgnoredThreads();
  4342. })
  4343. });
  4344.  
  4345. }
  4346.  
  4347. function clearOldBlacklistedThreads() {
  4348. Database.readAll(Database.Table.BlacklistedForumThreads, function(threads) {
  4349. $.each(threads, function(key, thread) {
  4350. if(thread.date < (new Date() - 60 * 24 * 60 * 60 * 1000)) {
  4351. Database.delete(Database.Table.BlacklistedForumThreads, thread.id, function(){})
  4352. }
  4353. })
  4354. })
  4355. }
  4356.  
  4357. /**
  4358. * Inserts a new column of check boxes for each Forum thread.
  4359. */
  4360. function showIgnoreCheckBox(columnCountOnPage) {
  4361. var $row = "<th> Hide</th>";
  4362. var header = $("table.region tr:first");
  4363.  
  4364. if(header.children("th").length < columnCountOnPage) {
  4365. header.append($row);
  4366. }
  4367.  
  4368. var allPosts = $('table.region tr').not(':first');
  4369.  
  4370. allPosts.each(function( index, post){
  4371. if($(this).children("td").length < columnCountOnPage) {
  4372. if(postId = $(this).find('a:first').attr('href')) {
  4373. $(this).append("<td><div class='thread-hide eye-icon'></div></td>");
  4374. }
  4375. }
  4376. });
  4377. }
  4378.  
  4379. addCSS(`
  4380. .eye-icon {
  4381. background-image: url(http://i.imgur.com/1i3UVSb.png);
  4382. height: 17px;
  4383. width: 17px;
  4384. cursor: pointer;
  4385. background-size: contain;
  4386. margin: auto;
  4387. background-repeat: no-repeat;
  4388. }
  4389. .eye-icon:hover {
  4390. background-image: url(http://i.imgur.com/4muX9IA.png);
  4391. }
  4392.  
  4393. `)
  4394.  
  4395. /**
  4396. * Hides all threads marked as "ignored" by a user.
  4397. */
  4398. function hideIgnoredThreads() {
  4399. var allPosts = $('table.region tr').not(':first');
  4400. $.each(allPosts, function(key, row) {
  4401. if(threadId = $(row).html().match(/href="\/Forum\/([^-]*)/mi)) {
  4402. Database.readIndex(Database.Table.BlacklistedForumThreads, Database.Row.BlacklistedForumThreads.ThreadId, threadId[1], function(thread) {
  4403. if(thread) {
  4404. $(row).hide();
  4405. }
  4406. })
  4407. }
  4408. })
  4409. }
  4410.  
  4411. function foldProfileStats() {
  4412. //$("#MainSiteContent table table h3")
  4413. addCSS(`
  4414. #accordion h3 {
  4415. cursor: pointer;
  4416. `)
  4417. $.each($("big").parent().contents(), function(key, val) {
  4418. if(val.nodeType == 3) {
  4419. $(val).replaceWith(`<span>${val.data}</span>`)
  4420. }
  4421. })
  4422. $.each($("#MainSiteContent table table h3"), function(key, val){
  4423. $(val).nextUntil("h3").wrapAll("<div class='exp'></div>")
  4424. })
  4425. $("#MainSiteContent table table h3:first").prev().nextUntil("").wrapAll("<div id='accordion'></div>")
  4426. $('#accordion h3').click(function(e){
  4427. $(this).next().slideToggle();
  4428. });
  4429. // var id = Number(sessionStorage.getItem("profileAccordion")) || false;
  4430. // $( "#accordion" ).accordion({
  4431. // collapsible: true,
  4432. // heightStyle: "content",
  4433. // active: id,
  4434. // activate: function( event, ui ) {
  4435. // var id = $("#MainSiteContent table table h3").index(ui.newHeader)
  4436. // sessionStorage.setItem("profileAccordion", id)
  4437. // },
  4438. // });
  4439. }
  4440.  
  4441.  
  4442. /**************************************
  4443.  
  4444. RANDOMIZED BONUSES
  4445.  
  4446. **************************************/
  4447.  
  4448. // Compute Player Ids
  4449.  
  4450. window.yourId;
  4451. window.opponentId;
  4452. window.gameName;
  4453.  
  4454. function setupRandomizedBonuses() {
  4455. if(pageIsProfile()) {
  4456. ifSettingIsEnabled("isMember", function() {
  4457. ifSettingIsEnabled("hideCreateRandomGameForm", function() {
  4458. }, function() {
  4459. var idRegex = /p=(\d+)/;
  4460. var yourProfileLink = document.evaluate('/html/body/div[1]/span/div/a[2]',
  4461. document, null, XPathResult.ANY_TYPE, null).iterateNext();
  4462. yourId = yourProfileLink.href.match(idRegex)[1];
  4463. opponentId = getParameterByName("p");
  4464. if (yourId == opponentId) {
  4465. opponentId = "OpenSeat";
  4466. }
  4467.  
  4468. // Add text box and button
  4469. addRandomizedControls();
  4470. })
  4471. })
  4472. }
  4473. }
  4474.  
  4475.  
  4476. function addRandomizedControls() {
  4477. /// <summary>
  4478. /// Add a text box(for sample game Id) and a button to create randomized
  4479. /// game.
  4480. /// </summary>
  4481. /// <param name="levelElement" type="Element">
  4482. /// The parent element if text box and button.
  4483. /// </param>
  4484.  
  4485. $("#FeedbackMsg").after("<div class='randomGameContainer profileBox'><h3>Randomized Bonuses Game</h3></div>")
  4486. var br = document.createElement('br');
  4487. $(".randomGameContainer").append('<label for="gameName">Game Name:</label><input id="gameName" type="text" placeholder="Game Name" value="Game - Randomized Bonuses"><br>')
  4488. $(".randomGameContainer").append('<label for="gameId">Game ID:</label><input id="gameId" type="text" placeholder="Game ID" value="">')
  4489. $(".randomGameContainer").append('<button id="createGame">Create Game</button>')
  4490. $("#createGame").on("click", function() {
  4491. $("#createGame").attr('disabled', true);
  4492. $("#createGame").text('...processing...');
  4493.  
  4494. setTimeout(function(){
  4495. $("#createGame").attr('disabled', false);
  4496. $("#createGame").text('Create Game');
  4497. }, 1000);
  4498. extractGameSettings();
  4499. })
  4500. $(".randomGameContainer").append('<button id="bookmarkRandomBonus"><img src="' + IMAGES.BOOKMARK + '"></button>')
  4501. $("#bookmarkRandomBonus").on("click", function() {
  4502. var templateId = getSampleGameId()
  4503. if(isNaN(templateId)) {
  4504. warlight_shared_viewmodels_AlertVM.DoPopup("Please enter a valid Game ID");
  4505. return;
  4506. }
  4507. $("#bookmarkURL").val("javascript:randomBonusGame('" + $("#gameName").val().replace("'", "`").replace('"', "`") + "', '" + templateId + "', '" + yourId + "', '" + opponentId + "')");
  4508. $("#bookmarkName").val($("#gameName").val());
  4509. showAddBookmark();
  4510. })
  4511.  
  4512.  
  4513. var saveButton = document.createElement("input");
  4514. saveButton.setAttribute("type", "button");
  4515. saveButton.setAttribute("value", "<img src='" + IMAGES.SAVE + "'>");
  4516. saveButton.onclick = function () {
  4517. var oldValue = saveButton.value;
  4518. saveButton.setAttribute('disabled', true);
  4519. saveButton.value = '...saving...';
  4520.  
  4521. setTimeout(function(){
  4522. saveButton.value = oldValue;
  4523. saveButton.removeAttribute('disabled');
  4524. }, 500);
  4525. //extractGameSettings();
  4526. };
  4527. var bookmarkButton = document.createElement("input");
  4528. bookmarkButton.setAttribute("type", "button");
  4529. bookmarkButton.setAttribute("value", "Bookmark");
  4530. bookmarkButton.onclick = function () {
  4531. var oldValue = bookmarkButton.value;
  4532. bookmarkButton.setAttribute('disabled', true);
  4533. bookmarkButton.value = '...saving...';
  4534.  
  4535. setTimeout(function(){
  4536. bookmarkButton.value = oldValue;
  4537. bookmarkButton.removeAttribute('disabled');
  4538. }, 500);
  4539. //extractGameSettings();
  4540. };
  4541. createSelector(".randomGameContainer button", "min-width: 10%; margin: 3px 6px 3px 0")
  4542. createSelector(".randomGameContainer button img", "height: 12px")
  4543. createSelector(".randomGameContainer input[type='text']", "margin: 3px")
  4544. createSelector(".randomGameContainer label", "width: 100px; display: inline-block; color: #858585")
  4545. }
  4546.  
  4547. function getSampleGameId() {
  4548. /// <summary>
  4549. /// Gets the sample game Id and checks if it is a number.
  4550. /// </summary>
  4551. /// <returns type="number">Game Id.</returns>
  4552. var gameIdElement = document.getElementById("gameId");
  4553. if (gameIdElement !== undefined) {
  4554. return parseInt(gameIdElement.value, 10);
  4555. }
  4556. }
  4557.  
  4558. function extractGameSettings(gameId) {
  4559. /// <summary>
  4560. /// Extract game settings from the sample game using GameFeed API.
  4561. /// </summary>
  4562.  
  4563. var sampleGameId = gameId || getSampleGameId();
  4564. if (isNaN(sampleGameId)) {
  4565. alert("Invalid GameId");
  4566. } else {
  4567. doAsyncRequest("POST",
  4568. 'https://www.warlight.net/API/GameFeed?GameID=' +
  4569. sampleGameId.toString() + '&GetHistory=true', {},
  4570. "GameFeed");
  4571. }
  4572. }
  4573.  
  4574. function setupRandomizedGame(response) {
  4575. /// <summary>
  4576. /// From the GameFeed API response, randomize bonuses and create a game
  4577. /// using the template.
  4578. /// </summary>
  4579. /// <param name="response" type="string">
  4580. /// The GameFeed API response for the provided sample game.
  4581. /// </param>
  4582. var obj = JSON.parse(response);
  4583. if (obj != undefined) {
  4584. var templateId = obj.templateID;
  4585. var bonuses = [];
  4586. if(obj && obj.map) {
  4587. for (var i = 0; i < obj.map.bonuses.length; i++) {
  4588. var bonusObj = obj.map.bonuses[i];
  4589. console.log(bonusObj)
  4590. if (bonusObj.value != 0) {
  4591. var bonus = [];
  4592. var originalBonusValue = parseInt(bonusObj.value, 10);
  4593.  
  4594. // set the bonus value to (original-1, original+1)
  4595. bonus.push(bonusObj.name);
  4596. bonus.push(originalBonusValue - 1);
  4597. bonus.push(originalBonusValue + 1);
  4598. bonuses.push(bonus);
  4599. }
  4600. }
  4601. } else {
  4602. 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")
  4603. warlight_shared_viewmodels_WaitDialogVM.Stop();
  4604. return
  4605. }
  4606. }
  4607. createGame(templateId, bonuses, yourId, opponentId);
  4608. }
  4609.  
  4610. window.randomBonusGame = function(name, templateId, yID, oID) {
  4611. ifSettingIsEnabled("isMember", function() {
  4612. warlight_shared_viewmodels_WaitDialogVM.Start("Creating Game...")
  4613. yourId = yID;
  4614. opponentId = oID;
  4615. gameName = name;
  4616. extractGameSettings(templateId)
  4617. }, function() {
  4618. warlight_shared_viewmodels_AlertVM.DoPopup("You need to be a Warlight Member to use this Feature");
  4619. })
  4620. }
  4621. function createGame(templateId, bonuses, yourId, opponentId) {
  4622. /// <summary>
  4623. /// Create a game on Warlight between the two players on given settings.
  4624. /// </summary>
  4625. /// <param name="templateId" type="number">
  4626. /// The game template Id.
  4627. /// </param>
  4628. /// <param name="bonuses" type="array">
  4629. /// All bonuses on the map and the range of values they can take.
  4630. /// </param>
  4631.  
  4632. var template = templateId;
  4633. var postDataObject = {
  4634. "gameName": typeof gameName == "string" ? gameName : $("#gameName").val() || "Randomized bonuses game",
  4635. "personalMessage": "Check bonuses carefully as they may have been altered",
  4636. "templateID": template,
  4637. "players": [{
  4638. "token": yourId,
  4639. "team": "None"
  4640. }, {
  4641. "token": opponentId,
  4642. "team": "None"
  4643. }],
  4644. "overriddenBonuses": []
  4645. };
  4646. if (bonuses !== null) {
  4647. for (var i = 0; i < bonuses.length; i++) {
  4648. var bonusName = bonuses[i][0];
  4649. var min = bonuses[i][1];
  4650. var max = bonuses[i][2];
  4651. postDataObject.overriddenBonuses.push({
  4652. "bonusName": bonusName,
  4653. value: getRandomInt(min, max) // Randomize the bonus
  4654. });
  4655. }
  4656. }
  4657. var response = doAsyncRequest("POST", 'https://www.warlight.net/API/CreateGame', JSON.stringify(postDataObject), "CreateGame");
  4658. }
  4659.  
  4660. function getRandomInt(min, max) {
  4661.  
  4662. return Math.floor(Math.random() * (max - min + 1)) + min;
  4663. }
  4664.  
  4665. function doAsyncRequest(method, url, data, api) {
  4666. var xhr = new XMLHttpRequest();
  4667. xhr.onreadystatechange = function() {
  4668. //if (xhr.readyState === 4){
  4669. if (xhr.readyState != 4) return;
  4670. if (api === "GameFeed") {
  4671. setupRandomizedGame(xhr.responseText);
  4672. } else if (api === "CreateGame") {
  4673. var obj = JSON.parse(xhr.responseText);
  4674. if (obj.gameID !== undefined) {
  4675. if(pageIsDashboard()) {
  4676. refreshMyGames()
  4677. warlight_shared_viewmodels_WaitDialogVM.Stop();
  4678. } else {
  4679. window.location.href = "https://www.warlight.net/MultiPlayer?GameID=" + obj.gameID
  4680. }
  4681. } else if (obj.error !== undefined) {
  4682. if(!obj.hasOwnProperty('templateID')) {
  4683. alert("Please make sure the game you are providing uses an existing Template and not \"Custom\"")
  4684. log(xhr.responseText)
  4685. } else {
  4686. alert("Cannot create game. Warlight says: " + obj.error);
  4687. }
  4688. try {
  4689. warlight_shared_viewmodels_WaitDialogVM.Stop();
  4690. } catch(e){}
  4691. }
  4692. }
  4693. };
  4694.  
  4695. xhr.open(method, url, true);
  4696. xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  4697. xhr.send(data);
  4698. }
  4699.  
  4700. function setIsMember() {
  4701. if (WLJSDefined()) {
  4702. window.setTimeout(function() {
  4703. if(warlight_shared_viewmodels_ConfigurationVM.Settings) {
  4704. var isMember = {name: "isMember", value: warlight_shared_viewmodels_SignIn.get_CurrentPlayer().IsMember}
  4705. Database.update(Database.Table.Settings, isMember, undefined, function() {
  4706. })
  4707. }
  4708. }, 2000)
  4709. }
  4710. }
  4711.  
  4712. function getParameterByName(name, url) {
  4713. url = url || location.search
  4714. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  4715. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  4716. results = regex.exec(url);
  4717. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  4718. }
  4719.  
  4720. /**************************************
  4721.  
  4722. Textarea HTML Box
  4723.  
  4724. **************************************/
  4725.  
  4726.  
  4727. function setupTextarea() {
  4728. var controls_default = [
  4729. {title: "<b>B</b>", class: ["tag"], openClose: true, tag: "b"},
  4730. {title: "<i>I</i>", class: ["tag"], openClose: true, tag: "i"},
  4731. {title: "code", class: ["tag"], openClose: true, tag: "code"},
  4732. {title: "img", class: ["tag"], openClose: true, tag: "img"},
  4733. {title: "hr", class: ["tag"], openClose: false, tag: "hr"},
  4734. {title: "quote", class: ["tag"], openClose: true, tag: "quote"},
  4735. {title: "list", class: ["tag"], openClose: true, tag: "list"},
  4736. {title: "*", class: ["tag"], openClose: false, tag: "*"},
  4737. ]
  4738. var controls = "";
  4739. $.each(controls_default, function(key, control) {
  4740. controls += `<span class="button ${control.class.join(" ")}" ${(control.openClose ? `open-close` : ``)} data-tag="${control.tag}">${control.title}</span>`
  4741. })
  4742. $(".region textarea").before(`<div class="editor">${controls}</div>`)
  4743. $("textarea").attr("style", "")
  4744. addCSS(`
  4745. .editor {
  4746. padding: 5px;
  4747. background: brown;
  4748. margin: 5px 5px 0 0;
  4749. }
  4750. .editor .button {
  4751. margin-right: 10px;
  4752. background: rgb(185,122,122);
  4753. padding: 3px 5px;
  4754. border-radius: 5px;
  4755. cursor: pointer;
  4756. }
  4757. textarea {
  4758. padding: 5px 0 0 5px;
  4759. box-sizing: border-box;
  4760. width: calc(100% - 5px);
  4761. max-width: 774px;
  4762. height: 300px
  4763. }
  4764. `)
  4765. createSelector("pre, textarea", "-moz-tab-size: 8;-o-tab-size: 8;tab-size: 8;")
  4766.  
  4767. $(document).on("click", ".editor .tag", function(e) {
  4768. var areaId = $(this).closest(".editor").next().attr("id")
  4769. var area = document.getElementById(areaId)
  4770. var tag = $(e.target).closest(".tag").attr("data-tag")
  4771. if(area) {
  4772. var startPos = area.selectionStart || 0;
  4773. var endPos = area.selectionEnd || 0;
  4774. if($(this).is("[open-close]")) {
  4775. addTagInEditor(area, startPos, endPos, tag)
  4776. } else {
  4777. addCodeInEditor(area, startPos, tag)
  4778. }
  4779. }
  4780. })
  4781. $("textarea").on('keydown', function(e) {
  4782. var keyCode = e.keyCode || e.which;
  4783. if (keyCode == 9) {
  4784. e.preventDefault();
  4785. var areaId = $(this).attr("id")
  4786. var area = document.getElementById(areaId)
  4787. if(area) {
  4788. var oldVal = $(area).val();
  4789. var start = area.selectionStart || 0;
  4790. var end = area.selectionEnd || 0;
  4791. var newVal = oldVal.substring(0, start) + "\t" + oldVal.substring(end)
  4792. if(browserIsFirefox()) {
  4793. $(area).val(newVal)
  4794. area.setSelectionRange(start + 1, start + 1)
  4795. } else {
  4796. document.execCommand("insertText", false, "\t")
  4797. }
  4798. }
  4799. }
  4800. });
  4801.  
  4802. }
  4803.  
  4804. function addCodeInEditor(area, place, tag) {
  4805. var oldVal = $(area).val()
  4806. var newVal = oldVal.substring(0, place) + "[" + tag + "]" + oldVal.substring(place)
  4807. $(area).focus();
  4808. if(browserIsFirefox()) {
  4809. $(area).val(newVal)
  4810. } else {
  4811. document.execCommand("insertText", false, "[" + tag + "]")
  4812. }
  4813. area.setSelectionRange(place + tag.length + 2, place + tag.length + 2)
  4814. $(area).focus();
  4815. }
  4816.  
  4817. function addTagInEditor(area, start, end, tag) {
  4818. var oldVal = $(area).val()
  4819. var selection = oldVal.substring(start, end)
  4820. var newContent = "[" + tag + "]" + selection + "[/" + tag + "]"
  4821. var newVal = oldVal.substring(0, start) + newContent + oldVal.substring(end)
  4822. $(area).focus();
  4823. if(browserIsFirefox()) {
  4824. $(area).val(newVal)
  4825. } else {
  4826. document.execCommand("insertText", false, newContent)
  4827. }
  4828. if(start == end) {
  4829. area.setSelectionRange(start + tag.length + 2, start + tag.length + 2)
  4830. } else {
  4831. area.setSelectionRange(end + 5 + (2 * tag.length), end + 5 + (2 * tag.length))
  4832. }
  4833. $(area).focus();
  4834. }
  4835.  
  4836. function browserIsFirefox() {
  4837. return navigator.userAgent.toLowerCase().indexOf('firefox') > -1
  4838. }
  4839.  
  4840.  
  4841. /**************************************
  4842.  
  4843. INDEXED DB
  4844.  
  4845. **************************************/
  4846.  
  4847.  
  4848. function setupDatabase() {
  4849. log("indexedDB start setup")
  4850. window.Database = {
  4851. db: null,
  4852. Table: {
  4853. Bookmarks: "Bookmarks",
  4854. Settings: "Settings",
  4855. BlacklistedForumThreads: "BlacklistedForumThreads",
  4856. TournamentData: "TournamentData"
  4857. },
  4858. Exports: {
  4859. Bookmarks: "Bookmarks",
  4860. Settings: "Settings",
  4861. BlacklistedForumThreads: "BlacklistedForumThreads"
  4862. },
  4863. Row: {
  4864. BlacklistedForumThreads: {
  4865. ThreadId: "threadId",
  4866. Date: "date"
  4867. },
  4868. Bookmarks: {
  4869. Order: "order"
  4870. },
  4871. Settings: {
  4872. Name: "name"
  4873. },
  4874. TournamentData: {
  4875. Id: "tournamentId",
  4876. }
  4877. },
  4878. init: function(callback) {
  4879. log("indexedDB start init")
  4880. if(!"indexedDB" in window) {
  4881. log("IndexedDB not supported")
  4882. return;
  4883. }
  4884. var openRequest = indexedDB.open("TidyUpYourDashboard_v3", 3);
  4885. openRequest.onupgradeneeded = function(e) {
  4886. var thisDB = e.target.result;
  4887. if(!thisDB.objectStoreNames.contains("Bookmarks")) {
  4888. var objectStore = thisDB.createObjectStore("Bookmarks", {autoIncrement:true});
  4889. objectStore.createIndex("order", "order", {unique:true});
  4890. }
  4891. if(!thisDB.objectStoreNames.contains("Settings")) {
  4892. var objectStore = thisDB.createObjectStore("Settings", { keyPath: "name" });
  4893. objectStore.createIndex("name", "name", {unique: true});
  4894. objectStore.createIndex("value", "value", {unique: false});
  4895. }
  4896. if(!thisDB.objectStoreNames.contains("BlacklistedForumThreads")) {
  4897. var objectStore = thisDB.createObjectStore("BlacklistedForumThreads", {autoIncrement:true});
  4898. objectStore.createIndex("threadId", "threadId", {unique:true});
  4899. objectStore.createIndex("date", "date", {unique:false});
  4900. }
  4901. if(!thisDB.objectStoreNames.contains("TournamentData")) {
  4902. var objectStore = thisDB.createObjectStore("TournamentData",{ keyPath: "tournamentId" });
  4903. objectStore.createIndex("tournamentId", "tournamentId", {unique:true});
  4904. objectStore.createIndex("value", "value", {unique: false});
  4905. }
  4906. }
  4907.  
  4908. openRequest.onsuccess = function(e) {
  4909. log("indexedDB init sucessful");
  4910. db = e.target.result;
  4911. callback()
  4912. }
  4913.  
  4914. openRequest.onerror = function(e) {
  4915. log("Error Init IndexedDB")
  4916. log(e.target.error)
  4917. // alert("Sorry, Tidy Up Your Dashboard is not supported")
  4918. $("<div>Sorry,<br> Tidy Up Your Dashboard is not supported.</div>").dialog();
  4919. }
  4920. },
  4921. update: function(table, value, key, callback) {
  4922. var transaction = db.transaction([table],"readwrite");
  4923. var store = transaction.objectStore(table);
  4924.  
  4925.  
  4926. //Perform the add
  4927. try {
  4928. var request = store.put(value, key != undefined ? Number(key) : undefined);
  4929. request.onerror = function(e) {
  4930. log(`Error saving ${JSON.stringify(value)} in ${table}`)
  4931. log(JSON.stringify(e));
  4932. }
  4933.  
  4934. request.onsuccess = function(e) {
  4935. log(`Saved ${JSON.stringify(value)} in ${table}`)
  4936. callback()
  4937. }
  4938. } catch(e) {
  4939. log(`Error saving ${JSON.stringify(value)} in ${table}`)
  4940. log(JSON.stringify(e));
  4941. }
  4942.  
  4943. },
  4944. read: function(table, key, callback) {
  4945. var transaction = db.transaction([table], "readonly");
  4946. var objectStore = transaction.objectStore(table);
  4947.  
  4948. var ob = objectStore.get(Number(key));
  4949.  
  4950. ob.onsuccess = function(e) {
  4951. var result = e.target.result;
  4952. callback(result)
  4953. }
  4954. },
  4955. readIndex: function(table, row, value, callback) {
  4956. var transaction = db.transaction([table], "readonly");
  4957. var objectStore = transaction.objectStore(table);
  4958.  
  4959. var index = objectStore.index(row);
  4960. //name is some value
  4961. var ob = index.get(value);
  4962.  
  4963. ob.onsuccess = function(e) {
  4964. var result = e.target.result;
  4965. callback(result)
  4966. }
  4967. },
  4968. readAll: function(table, callback) {
  4969. var transaction = db.transaction([table], "readonly");
  4970. var objectStore = transaction.objectStore(table);
  4971. var items = []
  4972.  
  4973. var ob = objectStore.openCursor()
  4974.  
  4975. ob.onsuccess = function(e) {
  4976. var cursor = e.target.result;
  4977. if (cursor) {
  4978. var item = cursor.value;
  4979. item.id = cursor.primaryKey;
  4980. items.push(item);
  4981. cursor.continue();
  4982. } else {
  4983. callback(items)
  4984. }
  4985. }
  4986. },
  4987. add: function(table, value, callback) {
  4988. var transaction = db.transaction([table],"readwrite");
  4989. var store = transaction.objectStore(table);
  4990.  
  4991. try {
  4992. var request = store.add(value);
  4993. request.onerror = function(e) {
  4994. log(`Error saving ${JSON.stringify(value)} in ${table}`)
  4995. log(JSON.stringify(e));
  4996. }
  4997.  
  4998. request.onsuccess = function(e) {
  4999. log(`Saved ${JSON.stringify(value)} in ${table}`)
  5000. callback()
  5001. }
  5002. } catch(e) {
  5003. log(`Error saving ${JSON.stringify(value)} in ${table}`)
  5004. log(JSON.stringify(e));
  5005. }
  5006.  
  5007. request.onerror = function(e) {
  5008. log(`Error saving ${JSON.stringify(value)} in ${table}`)
  5009. log(JSON.stringify(e));
  5010. }
  5011.  
  5012. request.onsuccess = function(e) {
  5013. log(`Saved ${JSON.stringify(value)} in ${table}`)
  5014. callback()
  5015. }
  5016. },
  5017. delete: function(table, key, callback) {
  5018. var transaction = db.transaction([table],"readwrite");
  5019. var store = transaction.objectStore(table);
  5020.  
  5021.  
  5022. //Perform the add
  5023. var request = store.delete(key)
  5024.  
  5025. request.onerror = function(e) {
  5026. log("Error deleting in " + table)
  5027. log(e.target.error);
  5028. //some type of error handler
  5029. }
  5030.  
  5031. request.onsuccess = function(e) {
  5032. log("Deleted in " + table)
  5033. callback()
  5034. }
  5035. },
  5036. clear: function(table, callback) {
  5037. var transaction = db.transaction([table],"readwrite");
  5038. var store = transaction.objectStore(table);
  5039.  
  5040.  
  5041. //Perform the add
  5042. var request = store.clear();
  5043.  
  5044. request.onerror = function(e) {
  5045. log("Error clearing " + table)
  5046. log(e.target.error);
  5047. //some type of error handler
  5048. }
  5049.  
  5050. request.onsuccess = function(e) {
  5051. log("Cleared " + table)
  5052. callback()
  5053. }
  5054. },
  5055.  
  5056. }
  5057.  
  5058. }
  5059.  
  5060. /**************************************
  5061.  
  5062. Other
  5063.  
  5064. **************************************/
  5065.  
  5066. function addCSS(css) {
  5067. head = document.head || document.getElementsByTagName('head')[0],
  5068. style = document.createElement('style');
  5069.  
  5070. style.type = 'text/css';
  5071. if (style.styleSheet) {
  5072. style.styleSheet.cssText = css;
  5073. } else {
  5074. style.appendChild(document.createTextNode(css));
  5075. }
  5076. head.appendChild(style);
  5077. }
  5078.  
  5079. function addVersionLabel() {
  5080. if(!pageIsGame() && !pageIsExamineMap() && !pageIsDesignMap()) {
  5081. $("body").append('<div class="versionLabel">' + GM_info.script.version +'</div>')
  5082. createSelector(".versionLabel", "position:fixed; right:0; bottom: 0; padding: 5px; color: #555; font-size: 10px; cursor:pointer")
  5083. $(".versionLabel").on("click", showUserscriptMenu)
  5084. }
  5085. }
  5086.  
  5087. function WLJSDefined() {
  5088. return (typeof WLJSLoaded) != "undefined" && WLJSLoaded();
  5089. }
  5090.  
  5091. function loadDataTableCSS() {
  5092. var styles = document.createElement("style");
  5093. styles.type = "text/css";
  5094. styles.innerHTML = getDataTableCSS();
  5095. document.body.appendChild(styles);
  5096. }
  5097. function getDataTableCSS() {
  5098. 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}
  5099.  
  5100. .dataTables_filter {
  5101. float: left;
  5102. margin-right: -7px;
  5103. }
  5104.  
  5105. .dataTables_filter label {
  5106. display: inline!important;
  5107. }
  5108.  
  5109. .dataTables_filter input {
  5110. padding: 3px;
  5111. border-radius: 5px;
  5112. margin: 5px;
  5113. }
  5114.  
  5115. .dataTables_info {
  5116. clear: both;
  5117. padding-top: 10px;
  5118. }
  5119.  
  5120. .pagination {
  5121. display: inline-block;
  5122. float: right;
  5123. margin-top: -16px;
  5124.  
  5125. }
  5126. .paginate_button {
  5127. display: inline;
  5128. padding: 5px;
  5129. }.paginate_button.active {
  5130. text-decoration: underline;
  5131. }`
  5132. }
  5133.  
  5134. function getPlotCSS() {
  5135. 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);}`
  5136. }
  5137.  
  5138. function setupImages() {
  5139. window.IMAGES = {
  5140. EYE: 'https://i.imgur.com/kekYrsO.png',
  5141. CROSS: 'https://i.imgur.com/RItbpDS.png',
  5142. QUESTION: 'https://i.imgur.com/TUyoZOP.png',
  5143. PLUS: 'https://i.imgur.com/lT6SvSY.png',
  5144. SAVE: 'https://i.imgur.com/Ze4h3NQ.png',
  5145. BOOKMARK: 'https://i.imgur.com/c6IxAql.png'
  5146.  
  5147. }
  5148. }
  5149.  
  5150. function setupAWPWorldTour() {
  5151. if($("title").text().toLowerCase().indexOf("awp world tour") != -1) {
  5152. setupAWPRanking();
  5153. setupAWPEvents();
  5154. $("#MainSiteContent div:first").after("<div class='awp'></div>")
  5155. $("#MainSiteContent div:first").css("float", "left")
  5156. $("#MainSiteContent div:first").css("width", "60%")
  5157. $("#MainSiteContent > table").css("width", "100%")
  5158. addCSS(`
  5159. .awp {
  5160. float: left;
  5161. margin: 60px 0 20px 20px;
  5162. width: 30%;
  5163. max-width: 400px;
  5164. }
  5165. .AWPRanking {
  5166. margin-bottom: 20px;
  5167. width: 100%;
  5168. }
  5169. .awpUpdated {
  5170. color: gray;
  5171. float: right;
  5172. font-size: 11px;
  5173. `)
  5174. }
  5175. }
  5176.  
  5177. function setupAWPRanking() {
  5178. var minRow = 12;
  5179. var maxRow = 30;
  5180. var minCol = 1;
  5181. var maxCol = 25;
  5182. 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`
  5183. $.ajax({
  5184. url: url,
  5185. dataType: "script",
  5186. });
  5187. }
  5188.  
  5189. function setupAWPEvents() {
  5190. var minRow = 10;
  5191. var minCol = 1;
  5192. var maxCol = 6;
  5193. 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`
  5194. $.ajax({
  5195. url: url,
  5196. dataType: "script",
  5197. });
  5198. }
  5199.  
  5200. window.parseAWPEventData = function(data) {
  5201. var entries = data.feed.entry
  5202. var lastUpdated = moment(data.feed.updated.$t)
  5203. 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>')
  5204. var tbody = $("<tbody></tbody>")
  5205. var tr = $("<tr></tr>");
  5206. var events = [];
  5207. var event = {finished: true};
  5208. var currentRow = entries[0].gs$cell.row
  5209. try {
  5210. $.each(entries, function(key, entry){
  5211. var col = entry.gs$cell.col
  5212. var row = entry.gs$cell.row
  5213.  
  5214. if((row - currentRow) >= 3) {
  5215. currentRow = row;
  5216. events.push(event)
  5217. if(event.url.match(/forum/i)) {
  5218. return;
  5219. }
  5220. event = {finished: true}
  5221. }
  5222.  
  5223. if(col == 1 && entry.content.$t) {
  5224. event.url = entry.content.$t.match(/docs.google.com/i) ? undefined : entry.content.$t
  5225. } else if(col == 3) {
  5226. event.date = entry.content.$t
  5227. } else if(col == 4) {
  5228. if(event.name == undefined) {
  5229. event.name = entry.content.$t
  5230. } else if(event.series == undefined) {
  5231. event.series = entry.content.$t
  5232. }
  5233. } else if(col == 5) {
  5234. event.champion = entry.content.$t
  5235. } else if(col == 6) {
  5236. event.finished = false
  5237. }
  5238. })
  5239. } catch(e) {
  5240. log("error parsing awp event data")
  5241. log(e)
  5242. }
  5243. var eventRows = events.filter(function(e){
  5244. return e.url && Math.abs(moment().diff(moment(e.date), 'days')) < 150
  5245. }).map(function(e){
  5246. return `<tr>
  5247. <td>${moment(e.date).format('DD/MMM')}</td>
  5248. <td><a href="${e.url}">${e.name}</a><br>${e.series}</td>
  5249. <td>${e.finished ? e.champion : (e.url.match(/tournament/i) ? "in progress" : "not started")}</td>
  5250. </tr>`
  5251. }).join("")
  5252. tbody.append(eventRows)
  5253. 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>`)
  5254. table.append(tbody);
  5255. $(".awp").append(table.outerHTML())
  5256. }
  5257. window.parseAWPRankingData = function(data) {
  5258. var entries = data.feed.entry
  5259. var lastUpdated = moment(data.feed.updated.$t)
  5260. 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>')
  5261. var tbody = $("<tbody></tbody>")
  5262. var tr = $("<tr></tr>");
  5263. var url;
  5264. try {
  5265. $.each(entries, function(key, entry){
  5266. var col = entry.gs$cell.col
  5267. var row = entry.gs$cell.row
  5268. if(col == 1) {
  5269. url = entry.content.$t;
  5270. } else if(col == 3) {
  5271. //rank
  5272. tr.append($(`<td>${entry.content.$t}</td>`))
  5273. } else if(col == 5) {
  5274. //name
  5275. tr.append($(`<td><a href="${url}">${entry.content.$t}</a></td>`))
  5276. } else if(col == 25) {
  5277. //points
  5278. tr.append($(`<td>${entry.content.$t}</td>`))
  5279. tbody.append(tr)
  5280. tr = $("<tr></tr>");
  5281. }
  5282. })
  5283. } catch(e) {
  5284. log("error parsing awp event data")
  5285. log(JSON.parse(e))
  5286. }
  5287. table.append(tbody);
  5288. 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>`)
  5289.  
  5290. $(".awp").prepend(table.outerHTML())
  5291. }
  5292.  
  5293. /**************************************
  5294.  
  5295. Community Levels
  5296.  
  5297. **************************************/
  5298.  
  5299. function setupCommunityLevels() {
  5300. var fonts = $("#LevelsTable tr td:nth-of-type(2) font:nth-of-type(1)")
  5301. $.each(fonts, function(key, font){
  5302. $(font).html($(font).html().replace(" 0 wins", "<span style='color: khaki'> 0 wins</span>"))
  5303. })
  5304.  
  5305. $("#MainSiteContent").wrapInner("<div id='newestLevels'></div>")
  5306. $("#MainSiteContent").wrapInner("<div id='content'></div>")
  5307. $("#content").append(`
  5308. <div id='sorted'>
  5309. <div id='tabs'>
  5310. <ul>
  5311. <li><a class="tab_hot" href='#tab_hot'>Hot</a></li>
  5312. <li><a class="tab_liked" href='#tab_liked'>Most Liked</a></li>
  5313. <li><a class="tab_hardest" href='#tab_hardest'>Most Difficult</a></li>
  5314. <li><a class="tab_mostplayed" href='#tab_mostplayed'>Most Played</a></li>
  5315. <li><a href='#tab_records_player'>Most Records (Player)</a></li>
  5316. <li><a href='#tab_records_clan'>Most Records (Clan)</a></li>
  5317. <li><a href='#tab_topCreators'>Top Creators</a></li>
  5318. <li><a href='#tab_ownLevels'>Your Levels</a></li>
  5319. </ul>
  5320. <div id='tab_hot'>
  5321. <h2>Popular New Levels</h2>
  5322. </div>
  5323. <div id='tab_liked'>
  5324. <h2>Most Liked Levels</h2>
  5325. </div>
  5326. <div id='tab_hardest'>
  5327. <h2>Most Difficult Levels</h2>
  5328. </div>
  5329. <div id='tab_mostplayed'>
  5330. <h2>Most Played Levels</h2>
  5331. </div>
  5332. <div id='tab_records_player'>
  5333. <h2>Most Records (Player)</h2>
  5334. </div>
  5335. <div id='tab_records_clan'>
  5336. <h2>Most Records (Clan)</h2>
  5337. </div>
  5338. <div id='tab_topCreators'>
  5339. <h2>Top Creators</h2>
  5340. </div>
  5341. <div id='tab_ownLevels'>
  5342. <h2>Your Levels</h2>
  5343. </div>
  5344. </div>
  5345. <p>This data is updated every 12 hours.</p>
  5346. </div>
  5347. <div id="searchLevel">
  5348. <h2>Search Level</h2>
  5349. <input class="searchLevelInput"></input>
  5350. <button class="searchLevelBtn">Search</button>
  5351. <div class="foundLevels"></div>
  5352. </div>`)
  5353.  
  5354. $("#content").prepend(`
  5355. <ul>
  5356. <li><a href='#newestLevels'>Newest Levels</a></li>
  5357. <li><a class='tab_hot' href='#sorted'>Advanced </a></li>
  5358. <li><a class='search' href='#searchLevel'>Search </a></li>
  5359. </ul>`)
  5360. $("h1").prependTo("#MainSiteContent")
  5361. $("#content").tabs();
  5362. $("#sorted").tabs();
  5363.  
  5364. $(".searchLevelBtn").on("click", function() {
  5365. searchLevel()
  5366. })
  5367. $('.searchLevelInput').keyup(function(e){
  5368. if(e.keyCode == 13) {
  5369. searchLevel()
  5370. }
  5371. });
  5372. addCSS(`
  5373. .ui-tabs {
  5374. border: none;
  5375. background: none;
  5376. }
  5377. .ui-tabs-nav {
  5378. background: none;
  5379. border: none;
  5380. border-bottom: 1px gray solid;
  5381. }
  5382. .striped th, .striped td {
  5383. border-bottom: 1px gray solid;
  5384. text-align: left;
  5385. }
  5386. `)
  5387. var mainjsReady = $.Deferred();
  5388. $(".tab_hot").on("click", function() {
  5389. $.when(mainjsReady).done(function () {
  5390. $.each($("#tab_hot tr[data-levelid]:visible"), function(key, row) {
  5391. var id = $(row).attr("data-levelid")
  5392. loadLevelData(id)
  5393. })
  5394. })
  5395. })
  5396. $(".tab_liked").on("click", function() {
  5397. $.when(mainjsReady).done(function () {
  5398. $.each($("#tab_liked tr[data-levelid]:visible"), function(key, row) {
  5399. var id = $(row).attr("data-levelid")
  5400. loadLevelData(id)
  5401. })
  5402. })
  5403. })
  5404. $(".tab_hardest").on("click", function() {
  5405. $.when(mainjsReady).done(function () {
  5406. $.each($("#tab_hardest tr[data-levelid]:visible"), function(key, row) {
  5407. var id = $(row).attr("data-levelid")
  5408. loadLevelData(id)
  5409. })
  5410. })
  5411. })
  5412. $(".tab_mostplayed").on("click", function() {
  5413. $.when(mainjsReady).done(function () {
  5414. $.each($("#tab_mostplayed tr[data-levelid]:visible"), function(key, row) {
  5415. var id = $(row).attr("data-levelid")
  5416. loadLevelData(id)
  5417. })
  5418. })
  5419. })
  5420. $.ajax({
  5421. type: 'GET',
  5422. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=7`,
  5423. dataType: 'jsonp',
  5424. crossDomain: true,
  5425. }).done(function (response) {
  5426. if (response.data) {
  5427. var levels = response.data
  5428. $("#tab_hot").append(`<table id="HotLevelsTable" cellpadding="8"></table>`)
  5429. $.each(levels, function (key, level) {
  5430. $("#HotLevelsTable").append(renderLevelRow(level, key))
  5431. $(`[data-levelid='${level.levelId}']`).attr("data-rating", level.rating)
  5432. })
  5433. $("#HotLevelsTable").append("<button id='loadMoreHot'>Load More</button>")
  5434. $("#loadMoreHot").on("click", function() {
  5435. $.each($("#tab_hot tr:hidden:lt(5)"), function(key, row) {
  5436. $(this).fadeIn()
  5437. $.when(mainjsReady).done(function () {
  5438. loadLevelData($(row).attr("data-levelid"))
  5439. })
  5440. })
  5441. if($("#tab_hot tr:hidden:lt(5)").length == 0) {
  5442. $("#loadMoreHot").remove();
  5443. }
  5444. })
  5445. }
  5446. });
  5447. $.ajax({
  5448. type: 'GET',
  5449. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=8`,
  5450. dataType: 'jsonp',
  5451. crossDomain: true,
  5452. }).done(function (response) {
  5453. if (response.data) {
  5454. var levels = response.data
  5455. $("#tab_liked").append(`<table id="MostLikedLevels" cellpadding="8"></table>`)
  5456. $.each(levels, function (key, level) {
  5457. $("#MostLikedLevels").append(renderLevelRow(level, key))
  5458. $(`[data-levelid='${level.levelId}']`).attr("data-rating", level.rating)
  5459. })
  5460. $("#MostLikedLevels").append("<button id='loadMoreLiked'>Load More</button>")
  5461. $("#loadMoreLiked").on("click", function() {
  5462. $.each($("#tab_liked tr:hidden:lt(5)"), function(key, row) {
  5463. $(this).fadeIn()
  5464. $.when(mainjsReady).done(function () {
  5465. loadLevelData($(row).attr("data-levelid"))
  5466. })
  5467. })
  5468. if($("#tab_liked tr:hidden:lt(5)").length == 0) {
  5469. $("#loadMoreLiked").remove();
  5470. }
  5471. })
  5472. }
  5473. });
  5474. $.ajax({
  5475. type: 'GET',
  5476. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=1`,
  5477. dataType: 'jsonp',
  5478. crossDomain: true,
  5479. }).done(function (response) {
  5480. if (response.data) {
  5481. var levels = response.data
  5482. $("#tab_hardest").append(`<table id="HardestLevelsTable" cellpadding="8"></table>`)
  5483. $.each(levels, function (key, level) {
  5484. $("#HardestLevelsTable").append(renderLevelRow(level, key))
  5485. })
  5486. $("#HardestLevelsTable").append("<button id='loadMoreDifficult'>Load More</button>")
  5487. $("#loadMoreDifficult").on("click", function() {
  5488. $.each($("#tab_hardest tr:hidden:lt(5)"), function(key, row) {
  5489. $(this).fadeIn()
  5490. $.when(mainjsReady).done(function () {
  5491. loadLevelData($(row).attr("data-levelid"))
  5492. })
  5493. })
  5494. if($("#tab_hardest tr:hidden:lt(5)").length == 0) {
  5495. $("#loadMoreDifficult").remove();
  5496. }
  5497. })
  5498. }
  5499. });
  5500. $.ajax({
  5501. type: 'GET',
  5502. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=2`,
  5503. dataType: 'jsonp',
  5504. crossDomain: true,
  5505. }).done(function (response) {
  5506. if (response.data) {
  5507. var levels = response.data
  5508. $("#tab_mostplayed").append(`<table id="MostPlayedLevelsTable" cellpadding="8"></table>`)
  5509. $.each(levels, function (key, level) {
  5510. $("#MostPlayedLevelsTable").append(renderLevelRow(level, key))
  5511. })
  5512. $("#MostPlayedLevelsTable").append("<button id='loadMoreMostPlayed'>Load More</button>")
  5513. $("#loadMoreMostPlayed").on("click", function() {
  5514. $.each($("#tab_mostplayed tr:hidden:lt(5)"), function(key, row) {
  5515. $(this).fadeIn()
  5516. $.when(mainjsReady).done(function () {
  5517. loadLevelData($(row).attr("data-levelid"))
  5518. })
  5519. })
  5520. if($("#tab_mostplayed tr:hidden:lt(5)").length == 0) {
  5521. $("#loadMoreMostPlayed").remove();
  5522. }
  5523. })
  5524. }
  5525. });
  5526. $.ajax({
  5527. type: 'GET',
  5528. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=3`,
  5529. dataType: 'jsonp',
  5530. crossDomain: true,
  5531. }).done(function (response) {
  5532. if (response.data) {
  5533. var players = response.data
  5534. $("#tab_records_player").append(`<table id="PlayerRecordsTable" cellpadding="8" class="striped"></table>`)
  5535. $("#PlayerRecordsTable").prepend(`<thead><th>#</th><th>Name</th><th>Number of Records</th></thead>`)
  5536. $.each(players, function (key, player) {
  5537. $("#PlayerRecordsTable").append(renderRecordPlayerRow(player, key))
  5538. })
  5539. }
  5540. });
  5541. $.ajax({
  5542. type: 'GET',
  5543. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=4`,
  5544. dataType: 'jsonp',
  5545. crossDomain: true,
  5546. }).done(function (response) {
  5547. if (response.data) {
  5548. var clans = response.data
  5549. $("#tab_records_clan").append(`<table id="ClanRecordsTable" cellpadding="8" class="striped"></table>`)
  5550. $("#ClanRecordsTable").prepend(`<thead><th>#</th><th>Name</th><th>Number of Records</th></thead>`)
  5551. $.each(clans, function (key, clan) {
  5552. $("#ClanRecordsTable").append(renderClanRow(clan, key))
  5553. })
  5554. }
  5555. });
  5556. $.ajax({
  5557. type: 'GET',
  5558. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=6`,
  5559. dataType: 'jsonp',
  5560. crossDomain: true,
  5561. }).done(function (response) {
  5562. if (response.data) {
  5563. var players = response.data
  5564. $("#tab_topCreators").append(`<table id="CreatorsTable" cellpadding="8" class="striped"></table>`)
  5565. $("#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>`)
  5566. $.each(players, function (key, player) {
  5567. $("#CreatorsTable tbody").append(renderCreatorPlayerRow(player, key))
  5568. })
  5569. var dataTable = $$$("#CreatorsTable").DataTable({
  5570. paging: false,
  5571. sDom: 't',
  5572. });
  5573. }
  5574. });
  5575. var id = $(".TopRightBar a:nth-of-type(2)").attr("href").match("[0-9]+")[0];
  5576. $.ajax({
  5577. type: 'GET',
  5578. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?p=${id}`,
  5579. dataType: 'jsonp',
  5580. crossDomain: true,
  5581. }).done(function (response) {
  5582. if (response.data) {
  5583. var levels = response.data
  5584. $("#tab_ownLevels").append(`<table id="OwnLevelsTable" cellpadding="8"></table>`)
  5585. $.each(levels, function (key, level) {
  5586. $("#OwnLevelsTable").append(renderLevelRow(level, key, true))
  5587. })
  5588. }
  5589. });
  5590. var div = $("<div></div>")
  5591. var mainjs = "";
  5592. div.load('https://www.warlight.net/SinglePlayer/Level?ID=882053', function(){
  5593. mainjs = div.find("script:contains(MainJS.Init)").html()
  5594. $.getScript("https://d2wcw7vp66n8b3.cloudfront.net/js/Release/wl.js?v=636045359309573936")
  5595. .done(function() {
  5596. eval(mainjs);
  5597. $("#WaitDialogJSWhiteBox").remove();
  5598. $("#WaitDialogJSBacking").remove();
  5599. mainjsReady.resolve();
  5600. })
  5601. });
  5602. }
  5603.  
  5604. function searchLevel() {
  5605. var query = $(".searchLevelInput").val().toLowerCase();
  5606. $(".foundLevels *").remove();
  5607. $.ajax({
  5608. type: 'GET',
  5609. url: `https://w115l144.hoststar.ch/wl/communityLevels.php?q=${query}`,
  5610. dataType: 'jsonp',
  5611. crossDomain: true,
  5612. }).done(function (response) {
  5613. if (response.data) {
  5614. if(response.data.length > 0) {
  5615. var levels = response.data
  5616. $(".foundLevels").append(`<table id="FoundLevelTable" cellpadding="8"></table>`)
  5617. $.each(levels, function (key, level) {
  5618. $("#FoundLevelTable").append(renderLevelRow(level, key))
  5619. })
  5620. } else {
  5621. $(".foundLevels").append(`<span>No levels found!</span>`)
  5622. }
  5623. } else {
  5624. $(".foundLevels").append(`<span>Error searching for levels</span>`)
  5625. }
  5626. });
  5627. }
  5628.  
  5629. function addCSS(css) {
  5630. head = document.head || document.getElementsByTagName('head')[0],
  5631. style = document.createElement('style');
  5632.  
  5633. style.type = 'text/css';
  5634. if (style.styleSheet) {
  5635. style.styleSheet.cssText = css;
  5636. } else {
  5637. style.appendChild(document.createTextNode(css));
  5638. }
  5639. head.appendChild(style);
  5640. }
  5641.  
  5642. function decode (str) {
  5643. var decoded = "";
  5644. try {
  5645. decoded = decodeURIComponent((str + '')
  5646. .replace(/%(?![\da-f]{2})/gi, function () {
  5647. return '%25'
  5648. })
  5649. .replace(/\+/g, '%20'))
  5650. } catch(e) {
  5651. decoded = unescape(str);
  5652. }
  5653. return decoded;
  5654. return decodeURIComponent((str + '')
  5655. .replace(/%(?![\da-f]{2})/gi, function () {
  5656. // PHP tolerates poorly formed escape sequences
  5657. return '%25'
  5658. })
  5659. .replace(/\+/g, '%20'))
  5660. }
  5661.  
  5662. function renderRecordPlayerRow(player, key) {
  5663. var rank = getRankHtml(key+1)
  5664. return `
  5665. <tr>
  5666. <td>${rank}</td>
  5667. <td>
  5668. ${player.recordClanId > 0 ? '<a href="/Clans/?ID=' + player.recordClanId + '" title="' + player.recordClanName + '"><img border="0" style="vertical-align: middle" src="' + player.recordClanImage + '"></a>' : ''}
  5669. <a href="${player.recordHolderUrl}"> ${decode(player.recordHolderName)} </a>
  5670. </td>
  5671. <td>
  5672. ${player.numOfRecords}
  5673. </td>
  5674. </tr>`
  5675. }
  5676.  
  5677. function renderCreatorPlayerRow(player, key) {
  5678. var id = player.createdByUrl.match(/[0-9]+/)[0]
  5679. var rank = getRankHtml(key+1)
  5680. return `
  5681. <tr>
  5682. <td style="text-align:center;padding:0" data-sort="${key+1}">${rank}</td>
  5683. <td>
  5684. ${player.creatorClanId > 0 ? '<a href="/Clans/?ID=' + player.creatorClanId + '" title="' + player.creatorClanName + '"><img border="0" style="vertical-align: middle" src="' + player.creatorClanImage + '"></a>' : ''}
  5685. <a href="${player.createdByUrl}"> ${decode(player.createdByName)} </a>
  5686. </td>
  5687. <td>
  5688. ${player.numOfTotalLikes}
  5689. </td>
  5690. <td>
  5691. ${player.numOfTotalAttempts}
  5692. </td>
  5693. <td>
  5694. ${player.numOfTotalWins}
  5695. </td>
  5696. <td>
  5697. ${(player.numOfTotalWins / player.numOfTotalAttempts * 100).toFixed(2)}%
  5698. </td>
  5699. <td>
  5700. ${player.numOfCreatedLevels}
  5701. </td>
  5702. <td>
  5703. <a href="https://www.warlight.net/SinglePlayer/LevelsByCreator?p=${id.substring(2, id.length-2)}">Show Levels</a>
  5704. </td>
  5705. </tr>`
  5706. }
  5707.  
  5708. function renderClanRow(clan, key) {
  5709. var rank = getRankHtml(key+1)
  5710. return `
  5711. <tr>
  5712. <td>${rank}</td>
  5713. <td>
  5714. <a href="/Clans/?ID=${clan.recordClanId}" title="${clan.recordClanId}"><img border="0" style="vertical-align: middle" src="${clan.recordClanImage}">${decode(clan.recordClanName)}</a>
  5715. </td>
  5716. <td>
  5717. ${clan.numOfRecords}
  5718. </td>
  5719. </tr>`
  5720. }
  5721.  
  5722. function renderLevelRow(level, key, showAll) {
  5723. return `
  5724. <tr data-levelid="${level.levelId}" ${(key >= 10 && showAll != true) ? 'style="display:none"' : ''}>
  5725. <td style="position: relative">
  5726. <img src="${level.mapImage}" width="140" height="80" style="position:relative">
  5727. </td>
  5728. <td>
  5729. <a style="font-size: 17px; color: white"
  5730. href="/SinglePlayer/Level?ID=${level.levelId}">${key+1}. ${decode(level.name)}
  5731. </a> &nbsp;&nbsp;
  5732. <font color="gray">${level.likes} likes, ${level.wins} wins in ${level.attempts} attempts</font><br>
  5733.  
  5734. <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>
  5735.  
  5736. <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>
  5737.  
  5738. <font color="gray">Win rate: </font>${level.percentage}%<br>
  5739. </td>
  5740. <td><span style="font-size: 17px"><a href="/SinglePlayer?Level=${level.levelId}">Play</a></span></td>
  5741. </tr>`
  5742. }
  5743.  
  5744. function getTurnText(turns) {
  5745. return ` in ${turns} ${turns > 1 ? 'turns' : 'turn'}`
  5746. }
  5747.  
  5748. function getRankHtml(rank) {
  5749. if(rank == 1) {
  5750. return `<img height=30 width=30 style="padding:0" src="https://i.imgur.com/dG4hKlp.gif">`
  5751. } else if(rank == 2) {
  5752. return `<img height=30 width=30 style="padding:0" src="https://imgur.com/qmpjRNs.gif">`
  5753. } else if(rank == 3) {
  5754. return `<img height=30 width=30 style="padding:0" src="https://imgur.com/DgtbQDN.gif">`
  5755. }
  5756. return rank;
  5757. }
  5758.  
  5759. function loadLevelData(id) {
  5760. warlight_shared_viewmodels_spe_SPEManager.GetLevelResult(id, function (levelData) {
  5761. if(levelData && levelData.WinCount > 0) {
  5762. $(`[data-levelid="${id}"] td:nth-of-type(2)`).append(`You won ${getTurnText(levelData.WonInTurns)}`)
  5763. $(`[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">')
  5764. }
  5765. $(`[data-levelid="${id}"]`).attr("data-levelid", "done")
  5766.  
  5767. })
  5768. }
  5769.  
  5770. //*************** TWITCH ************************//
  5771. function setupExtendedTwitch() {
  5772. $.getJSON('https://api.twitch.tv/kraken/streams?client_id=m2cojjidnvim6g0go9g2epmafcpv14&game=WarLight', function(data) {
  5773. $(".streamBox").remove();
  5774. if(data && data.streams.length > 1) {
  5775. var last = $("body > div:nth-of-type(1) > div > div:last");
  5776. var offset = last.offset().left + last.width();
  5777. var container = $("<div/>");
  5778. container.css("left", 0)
  5779. container.css("position", "absolute")
  5780. container.css("top", "42px")
  5781. container.css("display", "none")
  5782. container.css("background", "black")
  5783. container.css("padding", "10px")
  5784. container.css("width", "200px")
  5785. container.css("z-index", "100")
  5786. container.css("border", "1px gray solid")
  5787. container.addClass("streamContainer")
  5788. var box = $("<div/>")
  5789. box.html("<a>View all " + data.streams.length + " streams »</a>")
  5790. box.css("position", "relative")
  5791. box.css("display", "inline")
  5792. box.css("padding", "15px 120px 15px 10px")
  5793. box.css("left", offset)
  5794. box.addClass("streamBox")
  5795. var streams = data.streams;
  5796. var html = "";
  5797. $.each(streams, function (key, stream) {
  5798. var streamHTML = getStreamHtml(stream);
  5799. html += streamHTML
  5800. console.log(stream)
  5801. })
  5802. container.html(html)
  5803. box.append(container)
  5804. $("body > div:nth-of-type(1) > div").append(box)
  5805. // $("body").append(container)
  5806. // $(".streamBox").on("mouseover", function() {
  5807. // $(".streamContainer").css("display", "inline");
  5808. // })
  5809. }
  5810.  
  5811. });
  5812. }
  5813.  
  5814. function getStreamHtml(stream) {
  5815. var name = stream.channel.display_name;
  5816. var title = stream.channel.status;
  5817. var url = stream.channel.url;
  5818. var viewers = stream.viewers;
  5819. var startingTime = new Date(stream.created_at).getTime();
  5820. 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>'
  5821. }
  5822.  
  5823. function StartLivestream() {
  5824. $(".LivestreamInner").tooltip();
  5825. window.setInterval(function() {
  5826. LivestreamTick()
  5827. }, 1000)
  5828. addCSS(`
  5829. .LivestreamTimer {
  5830. color: gray;
  5831. }
  5832. .LivestreamInner {
  5833. font-size: 9px;
  5834. padding-bottom: 5px;
  5835. border-bottom: 1px #222 solid;
  5836. margin-top: 5px;
  5837. }
  5838. .streamBox:hover > .streamContainer, .streamContainer:hover {
  5839. display: inline!important
  5840. }
  5841. .streamBox > a {
  5842. font-size: 9px;
  5843. position: absolute;
  5844. margin-top: 13px;
  5845. cursor:pointer;
  5846. }
  5847. `)
  5848. }
  5849.  
  5850. function LivestreamTick() {
  5851. $.each($(".LivestreamInner"), function(key, elem) {
  5852. var timer = $(elem).find(".LivestreamTimer")
  5853. $(timer).text(GetHMS((new Date).getTime() - parseInt($(elem).attr("data-started"))))
  5854. })
  5855. // var a = $(".LivestreamTimer"),
  5856. // b = $(".LivestreamInner");
  5857. // a.text(GetHMS((new Date).getTime() - parseInt(b.attr("data-started"))))
  5858. }
  5859.  
  5860. function Pad0sTo2(a) {
  5861. return 0 == a.length ? "00" : 1 == a.length ? "0" + a : a
  5862. }
  5863.  
  5864. function GetHMS(a) {
  5865. var b = a / 1E3,
  5866. c = b / 60;
  5867. a = c / 60;
  5868. c = Math.floor(c % 60).toString();
  5869. b = Math.floor(b % 60).toString();
  5870. return 1 <= a ? Math.floor(a) + ":" + Pad0sTo2(c) + ":" + Pad0sTo2(b) : c + ":" + Pad0sTo2(b)
  5871. };

QingJ © 2025

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