Tidy up your Dashboard

Customizable Userscript which tidies up your Dashboard!

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

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

QingJ © 2025

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