Tidy up your Dashboard

Customizable Userscript which tidies up your Dashboard!

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

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

QingJ © 2025

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