Tidy up your Dashboard

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

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

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

QingJ © 2025

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