Tidy up your Dashboard

Customizable Userscript which tidies up your Dashboard!

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

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

QingJ © 2025

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