Tidy up your Dashboard

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

当前为 2017-08-11 提交的版本,查看 最新版本

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

QingJ © 2025

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