Tidy up your Dashboard

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

当前为 2018-02-09 提交的版本,查看 最新版本

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

QingJ © 2025

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