Tidy up your Dashboard

Customizable Userscript which tidies up your Dashboard!

当前为 2016-08-31 提交的版本,查看 最新版本

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

QingJ © 2025

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