Tidy up your Dashboard

Customizable Userscript which tidies up your Dashboard!

当前为 2016-06-13 提交的版本,查看 最新版本

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

QingJ © 2025

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