Tidy up your Dashboard

Customizable Userscript which tidies up your Dashboard!

当前为 2016-09-07 提交的版本,查看 最新版本

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

QingJ © 2025

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