Tidy up your Dashboard

Customizable Userscript which tidies up your Dashboard!

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

  1. // ==UserScript==
  2. // @name Tidy up your Dashboard
  3. // @namespace https://gf.qytechs.cn/users/10154
  4. // @grant none
  5. // @match https://www.warlight.net/*
  6. // @description Customizable Userscript which tidies up your Dashboard!
  7. // @version 1.10
  8. // @icon http://i.imgur.com/XzA5qMO.png
  9. /// @require https://gf.qytechs.cn/scripts/14620-randomized-bonus/code/Randomized%20Bonus.user.js
  10. // @require https://gf.qytechs.cn/scripts/8981-spammers-be-gone/code/Spammers%20be%20gone!.user.js
  11.  
  12. // ==/UserScript==
  13. //this.$ = this.jQuery = jQuery.noConflict(true);
  14.  
  15. var version = "1.10";
  16.  
  17. function checkVersion() {
  18. var currentVersion = localStorage.getItem('version');
  19.  
  20. if (currentVersion == version) {
  21. //Script Up to date
  22.  
  23. } else if (currentVersion == undefined) {
  24. //Script new installed
  25. $(".userscript-show").fadeIn();
  26. $(".overlay").fadeIn();
  27. if (!localStorage.getItem("bookmarks")) {
  28. addDefaultBookmark();
  29. }
  30. } else {
  31. //Script Updated
  32. //$("label[for='showPrivateNotesOnProfile']").addClass('newSetting');
  33. //$(".userscript-show").fadeIn();
  34. //$(".overlay").fadeIn();
  35. window.setTimeout(function() {
  36. warlight.shared.viewmodels.AlertVM.DoPopup("Tidy up Your Dashboard was sucessfully updated to Version " + version + "! Check out the forum thread to see what changed.");
  37. }, 1000)
  38. }
  39.  
  40. addVersionLabel()
  41. localStorage.setItem('version', version);
  42. }
  43.  
  44.  
  45. var lastRefresh;
  46. var myGamesTable = $("#MyGamesTable");
  47. var openGamesTable = $("#OpenGamesTable");
  48. var promotedGamesTable = $("#PromotedGamesTable");
  49. var lastClick = new Date();
  50.  
  51. var openGamesFilters;
  52. var bookmarks;
  53. var IMAGES;
  54. setupImages();
  55.  
  56. var userscriptSettings = [
  57. {
  58. id: 'scrollGames',
  59. text: 'Fixed Window with scrollable Games',
  60. selected: true,
  61. title: 'Dashboard',
  62. addBreak: false,
  63. 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. '
  64. },
  65. {
  66. id: 'hideMyGamesIcons',
  67. text: 'Hide Icons in "My Games"',
  68. selected: false,
  69. title: '',
  70. addBreak: false,
  71. 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"'
  72. },
  73. {
  74. id: 'autoRefreshOnFocus',
  75. text: 'Automatically refresh Games on Tab-Focus',
  76. selected: false,
  77. title: '',
  78. addBreak: false,
  79. 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.'
  80. },
  81. {
  82. id: 'highlightTournaments',
  83. text: 'Highlight Tournament invites',
  84. selected: false,
  85. title: '',
  86. addBreak: false,
  87. },
  88. {
  89. id: 'highlightNewForumPosts',
  90. text: 'Highlight new Clan Posts',
  91. selected: false,
  92. title: '',
  93. addBreak: false,
  94. help: 'This Option highlights Forum Posts in the Clan Forum Posts section which you haven\'t read yet.'
  95. },
  96. {
  97. id: 'hideRightColumn',
  98. text: 'Hide Right Column',
  99. selected: false,
  100. title: '',
  101. addBreak: false,
  102. help: 'This Option hides the right column completely and leaves you alone with My-, Open- and Coin-Games.'
  103. },
  104. {
  105. id: 'hidePromotedGames',
  106. text: 'Hide Promoted Games',
  107. selected: false,
  108. title: '',
  109. addBreak: false,
  110. help: 'This Option hides the Promoted Games on the Dashboard'
  111. },
  112. {
  113. id: 'useDefaultBootLabel',
  114. text: 'Use the Default Boot Time Label',
  115. selected: false,
  116. title: '',
  117. addBreak: false
  118. },
  119. {
  120. id: 'showOpenGamesTab',
  121. text: 'Show Open Games Tab in Menu Bar',
  122. selected: false,
  123. title: 'Global',
  124. addBreak: false,
  125. help: 'This Option displays a link to the "Open Games" site right next to the "Past Games" Link.'
  126. },
  127. {
  128. id: 'hideCoinsGlobally',
  129. text: 'Hide Coins Globally',
  130. selected: false,
  131. title: '',
  132. addBreak: false,
  133. help: 'This Option removes everything from Warlight related to Coins'
  134. },
  135. {
  136. id: 'showPrivateNotesOnProfile',
  137. text: 'Show Private Notes on Profile',
  138. selected: false,
  139. title: '',
  140. addBreak: false,
  141. 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.'
  142. },
  143. {
  144. id: 'unlinkDashboard',
  145. text: 'Link Dashboard to "old" My-Games Site',
  146. selected: false,
  147. title: '',
  148. addBreak: false,
  149. help: 'This Option links the Dashboard to the "old" My-Games Site'
  150. },
  151. {
  152. id: 'disableSnow',
  153. text: 'Disable Snow',
  154. selected: false,
  155. title: 'Special',
  156. addBreak: false,
  157. help: 'Turns off the snow animation on all sites'
  158. },
  159. {
  160. id: 'snowLight',
  161. text: 'Reduce the number of Snowflakes',
  162. selected: false,
  163. title: '',
  164. addBreak: false,
  165. help: 'Reduce the number of Snowflakes for a better performance'
  166. }
  167. ];
  168.  
  169. var filters = [
  170. {
  171. id: "disableAll",
  172. text: "Disable All Filters",
  173. selected: false,
  174. type: "checkbox"
  175. },
  176. {
  177. id: "",
  178. text: "<div style='display:inline-block;height:30px; width: 10px'> </div>",
  179. selected: false,
  180. type: "custom"
  181. },
  182. {
  183. id: "hideTeam",
  184. text: "Hide Team Games",
  185. selected: false,
  186. type: "checkbox"
  187. }, {
  188. id: "hideManualDistribution",
  189. text: "Hide Manual Distribution Games",
  190. selected: false,
  191. type: "checkbox"
  192. },
  193. {
  194. id: "hideFFA",
  195. text: "Hide FFA Games",
  196. selected: false,
  197. type: "checkbox"
  198. },
  199. {
  200. id: "hideAutoDistribution",
  201. text: "Hide Auto Distribution Games",
  202. selected: false,
  203. type: "checkbox"
  204. },
  205. {
  206. id: "hide1v1",
  207. text: "Hide 1 v 1 Games",
  208. selected: false,
  209. type: "checkbox"
  210. },
  211. {
  212. id: "hideCustomScenario",
  213. text: "Hide Custom Scenario Games",
  214. selected: false,
  215. type: "checkbox"
  216. },
  217. {
  218. id: "hideNoSplit",
  219. text: "Hide No-Split Games",
  220. selected: false,
  221. type: "checkbox"
  222. },
  223. {
  224. id: "hideNonCustomScenario",
  225. text: "Hide Non-Custom Scenario Games",
  226. selected: false,
  227. type: "checkbox"
  228. },
  229. {
  230. id: "hideLocalDeployments",
  231. text: "Hide Local Deployment Games",
  232. selected: false,
  233. type: "checkbox"
  234. },
  235. {
  236. id: "hidePractice",
  237. text: "Hide Practice Games",
  238. selected: false,
  239. type: "checkbox"
  240. },
  241. {
  242. id: "hideLuck",
  243. text: "<label for='hideLuck' style='width:169px'>Hide Luck greater than</label><input type='text' id='hideLuck' class='number'>",
  244. selected: false,
  245. type: "custom"
  246. },
  247. {
  248. id: "hideNonPractice",
  249. text: "Hide Non-Practice Games",
  250. selected: false,
  251. type: "checkbox"
  252. },
  253. {
  254. id: "limitPlayers",
  255. 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>',
  256. selected: false,
  257. type: "custom"
  258. },
  259. {
  260. id: "hideBootTime",
  261. 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>',
  262. selected: false,
  263. type: "custom"
  264. },
  265. {
  266. id: "hideKeyword",
  267. 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>',
  268. selected: false,
  269. type: "custom",
  270. }
  271.  
  272. ];
  273.  
  274. var showGamesActive = "ShowMyGames";
  275.  
  276.  
  277. var openGames = [];
  278. setIsMember();
  279. readLocalstorage();
  280. setGlobalStyles();
  281. setupUserscriptMenu();
  282. setupBookmarkMenu();
  283. checkVersion();
  284.  
  285. $.fn.settingIsEnabled = function (setting) {
  286. var selected = false;
  287. $.each(userscriptSettings, function (key, set) {
  288. if (set.id == setting) {
  289. selected = set.selected;
  290. }
  291. });
  292. return selected;
  293. };
  294.  
  295. if (isEnabled('unlinkDashboard')) {
  296. $("#MultiPlayerBtn").attr('href', 'https://www.warlight.net/MultiPlayer?MyGames=1');
  297. $("#SubTabRow td > a[href='/MultiPlayer/'").attr('href', 'https://www.warlight.net/MultiPlayer?MyGames=1');
  298.  
  299. }
  300.  
  301. if (pageIsForumThread() || pageIsClanForumThread()) {
  302. //Show Open Games Link
  303. $("[href='#Reply']").after(" | <a style='cursor:pointer' onclick='bookmarkForumThread()'>Bookmark</a>")
  304. $("#PostReply").after(" | <a style='cursor:pointer' onclick='bookmarkForumThread()'>Bookmark</a>")
  305. }
  306.  
  307. if (pageIsTournament()) {
  308. $(document).ready(function () {
  309. setupTournamentFindMe()
  310. });
  311. $("#HostLabel").after(" | <a style='cursor:pointer' onclick='bookmarkTournament()'>Bookmark</a>");
  312. $("#HostLabel").css("display", "inline-block")
  313. $("#LeftToStartMessage").text(" | " + $("#LeftToStartMessage").text())
  314. createSelector("#LeftToStartMessage:before", "content: ' | '")
  315. createSelector("#ChatContainer", "clear:both")
  316. }
  317.  
  318. if (pageIsMultiplayer()) {
  319. //Show Open Games Link
  320. if (isEnabled('showOpenGamesTab')) {
  321. showOpenGamesLink();
  322. }
  323. }
  324.  
  325. if(pageIsLadderOverview()) {
  326. setupLadderClotOverview()
  327. }
  328.  
  329. if (pageIsDashboard()) {
  330. window.StringTools.htmlEscape = function (a) {
  331. if (a.indexOf("##joined##") >= 0) {
  332. a = a.replace("##joined##", "");
  333. 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">';
  334. } else {
  335. return htmlEscape(a);
  336. }
  337.  
  338. }
  339. hideBlacklistedThreads();
  340. setupBasicDashboardStyles();
  341. refreshOpenGames();
  342. setupPlayerSearch()
  343.  
  344. setupOpenGamesFilter();
  345.  
  346.  
  347. if (isEnabled('hideCoinsGlobally')) {
  348. hideCoinsGlobally()
  349. }
  350.  
  351. if (isEnabled('highlightTournaments')) {
  352. createSelector("#MyTournamentsTable tbody", "background:#4C4C33;");
  353. }
  354.  
  355. if (isEnabled('hidePromotedGames') || isEnabled('hideCoinsGlobally')) {
  356. createSelector("#PromotedGamesTable", "display:none");
  357. }
  358.  
  359. if (isEnabled('hideMyGamesIcons')) {
  360. createSelector("#MyGamesTable td div img, #MyGamesTable td div a img", "display:none;");
  361. }
  362.  
  363. if (isEnabled('highlightNewForumPosts')) {
  364. hightlightNewClanForumPosts();
  365. }
  366.  
  367. if (isEnabled('scrollGames')) {
  368. setupFixedWindowWithScrollableGames();
  369. }
  370. setupRightColumn(true);
  371.  
  372. if (isEnabled('hideRightColumn')) {
  373. hideRightColumn();
  374. }
  375.  
  376. $("label[for='MultiDayRadio']").on("click", function () {
  377. registerGameTabClick()
  378.  
  379. });
  380.  
  381. $("label[for='RealTimeRadio']").on("click", function () {
  382. registerGameTabClick()
  383. });
  384.  
  385. $("label[for='BothRadio']").on("click", function () {
  386. registerGameTabClick()
  387. });
  388.  
  389. $(window).resize(function () {
  390. if (isEnabled('scrollGames')) {
  391. refreshSingleColumnSize();
  392. }
  393. });
  394.  
  395. checkBookmarkTable();
  396. setupRefreshFunction();
  397.  
  398. } else {
  399. if (isEnabled('hideCoinsGlobally')) {
  400. hideCoinsGlobally()
  401. }
  402. }
  403.  
  404. if(pageIsRealTimeLadder) {
  405. setupRealTimeLadderPageTimer()
  406. }
  407.  
  408. if(pageIsDashboard || pageIsRealTimeLadder()) {
  409. window.setInterval(setRTLadderTime, 1000)
  410. }
  411.  
  412. if (pageIsClanThread()) {
  413. registerClanThread();
  414. }
  415. if(pageIsProfile()) {
  416. createSelector(".profileBox", "background-image: url(\'https://d2wcw7vp66n8b3.cloudfront.net/Images/ProfileSpeedBackground.png\'); background-repeat: no-repeat; text-align: left; padding:10px;margin-top: 12px;")
  417. setupRandomizedBonus()
  418. }
  419. if (pageIsProfile() && isEnabled('showPrivateNotesOnProfile') && $("#BlackListImage").length > 0) {
  420. loadPrivateNotes();
  421. }
  422.  
  423.  
  424.  
  425.  
  426. function hideCoinsGlobally() {
  427. $("#CoinsBtn").parent().next().css('left', 512);
  428. $("#CoinsBtn").parent().next().next().css('left', 635);
  429. $("#CoinsBtn").parent().next().next().next().css('left', 740);
  430.  
  431. $("#LeaderboardTable").prev().remove();
  432. $("#LeaderboardTable").css({
  433. opacity: 0,
  434. cursor: 'default'
  435. });
  436. $("#LeaderboardTable a").css('display', 'none');
  437. $(".TopRightBar").find("a[href='/Coins/']").css('display', 'none');
  438. $(".dropdown-menu a[href='/Coins/']").parent().remove()
  439.  
  440. $("a[href='/Win-Money']").css('display', 'none');
  441.  
  442. $("#OpenTournamentsTable").css('display', 'none');
  443. }
  444.  
  445. /**
  446. * Reads the User-Settings from Localstorage
  447. */
  448. function readLocalstorage() {
  449.  
  450. //Settings
  451.  
  452. $.each(userscriptSettings, function (key, setting) {
  453. setting.selected = localStorage.getItem(setting.id) == "true";
  454. });
  455.  
  456. //Filters
  457. var filters = localStorage.getItem("openGamesFilters");
  458.  
  459. if (filters) {
  460. openGamesFilters = $.parseJSON(filters);
  461. } else {
  462. openGamesFilters = {};
  463. }
  464.  
  465. setBookmarks()
  466.  
  467. hideCoinSymbol = true;
  468. }
  469.  
  470. /**
  471. * Creates the Userscript-Menu
  472. */
  473. function setupUserscriptMenu() {
  474.  
  475. var inputs = '';
  476.  
  477. $.each(userscriptSettings, function (key, setting) {
  478. if (setting.title != '') {
  479. inputs += '<span class="title">' + setting.title + '</span><br>';
  480. }
  481. var help = setting.help != undefined ? '<img src="' + IMAGES.QUESTION + '" class="help-icon" onclick=\'showSettingHelp("' + setting.id + '", this)\'>' : ''
  482. inputs += '<label for="_' + setting.id + '">' + setting.text + help + '</label>' + '<input type="checkbox" id="' + setting.id + '"><br>';
  483. if (setting.addBreak) {
  484. inputs += '<hr>';
  485. }
  486. });
  487.  
  488. inputs += '<div class="close-userscript">Close and Refresh</div>';
  489. $("body").append('<ul class="custom-menu"><div class="content"></div></ul>');
  490. $("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>");
  491. $(".userscript-show").on("change", function () {
  492. storeSettingsVariables();
  493. });
  494. $("#TopRightDropDown .dropdown-divider").before('<li><div class="userscript-menu">Userscript</div></li>');
  495.  
  496. $(".userscript-menu").on("click", function () {
  497. showUserscriptMenu()
  498. });
  499.  
  500. $(".close-userscript").on("click", function () {
  501. $(".userscript-show").fadeOut();
  502. $(".overlay").fadeOut();
  503. location.reload();
  504. });
  505.  
  506. $(".close-popup-img").on("click", function () {
  507. $(".userscript-show").fadeOut();
  508. $(".overlay").fadeOut();
  509. $("embed#main").css('opacity', '1');
  510. });
  511. $("#hideRightColumn").after('<button id="sortTables">Sort Right Column Tables</button><br>')
  512. createSelector("#sortTables","margin-top: 5px")
  513. $("#sortTables").on("click", function() {
  514. showSortTables()
  515. })
  516. var tables = getSortTables()
  517. var tableCode = ''
  518. $.each(tables, function(key, table) {
  519. 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>'
  520. })
  521. createSelector(".sortableLadder", "border: 1px gray solid;margin: 5px;padding: 5px;background-color:rgb(25, 25, 25);")
  522. createSelector(".tableSortNavigation", "display: inline-block;float: right;margin-top: -2px;")
  523. createSelector(".tableSortNavigation span", "padding: 3px 10px; cursor: pointer")
  524. createSelector(".tableSortNavigation span:hover", "color: #C0D0FF")
  525. createSelector(".sortTableHighlight", "background-color: rgb(60, 60, 60)")
  526. createSelector(".tableSortHideShow img", "height: 10px")
  527. createSelector(".tableSortHidden", "opacity: 0.2;")
  528. $("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>')
  529. $(".tableSortUp").on("click", function() {
  530. $(".sortTableHighlight").removeClass("sortTableHighlight")
  531. var table = $(this).closest(".sortableLadder")
  532. table.addClass("sortTableHighlight")
  533. var prev = table.prev()
  534. table = table.detach()
  535. prev.before(table)
  536. })
  537. $(".tableSortDown").on("click", function() {
  538. $(".sortTableHighlight").removeClass("sortTableHighlight")
  539. var table = $(this).closest(".sortableLadder")
  540. table.addClass("sortTableHighlight")
  541. var next = table.next()
  542. table = table.detach()
  543. next.after(table)
  544. })
  545. $(".tableSortHideShow").on("click", function() {
  546. $(".sortTableHighlight").removeClass("sortTableHighlight")
  547. var table = $(this).closest(".sortableLadder")
  548. table.addClass("sortTableHighlight")
  549. table.toggleClass("tableSortHidden")
  550. })
  551. checkUserscriptMenuButtons();
  552.  
  553. }
  554.  
  555. function showUserscriptMenu() {
  556. $(".userscript-show").fadeIn();
  557. $(".overlay").fadeIn();
  558. $("#TopRightDropDown").fadeOut();
  559. $("embed#main").attr('wmode', 'transparent');
  560. $("embed#main").css('opacity', '0');
  561. $("embed#main").attr('align', 'left');
  562. }
  563.  
  564. function getSortTables() {
  565. var defaultTables =
  566. [
  567. {id: "#BookmarkTable", name: "Bookmarks", hidden: false, order: 0},
  568. {id: "#ClotTable", name: "CLOTs", hidden: false, order: 1},
  569. {id: "#MyTournamentsTable", name: "Tournaments", hidden: false, order: 2},
  570. {id: "#RealTimeLadderTable", name: "Real-Time Ladder", hidden: false, order: 3},
  571. {id: "#MapOfTheWeekTable", name: "Map of the Week", hidden: false, order: 4},
  572. {id: "#ForumTable", name: "Forum Posts", hidden: false, order: 5},
  573. {id: "#ClanForumTable", name: "Clan Forum Posts", hidden: false, order: 6},
  574. {id: "#BlogTable", name: "Recent Blog Posts", hidden: false, order: 7},
  575. {id: "#LeaderboardTable", name: "Coin Leaderboard", hidden: false, order: 8}
  576. ]
  577. var tables;
  578. var tableData = localStorage.getItem("tableSort")
  579. try {
  580. tables = (tableData != undefined && isJson(tableData)) ? JSON.parse(tableData) : defaultTables
  581. }
  582. catch(e) {
  583. return $(defaultTables).sort(compareTable)
  584. }
  585. return $(tables).sort(compareTable);
  586. }
  587.  
  588. window.saveTableSort = function() {
  589. var tables = []
  590. $.each($("#sortTablePopup > div.sortableLadder"), function(key, table) {
  591. var order = key
  592. var id = $(table).attr('data-tableId')
  593. var hidden = $(table).hasClass("tableSortHidden")
  594. var name = $(table).attr('data-name')
  595. tables.push({id: id, name: name, hidden: hidden, order: order})
  596. })
  597. localStorage.setItem("tableSort", JSON.stringify(tables))
  598. $("#sortTablePopup").fadeOut();
  599. $(".overlay").fadeOut();
  600. window.location.reload()
  601. }
  602.  
  603. function showSortTables() {
  604. $(".popup").fadeOut();
  605. $("#sortTablePopup").fadeIn();
  606. $(".overlay").fadeIn();
  607. }
  608.  
  609. function compareTable(a,b) {
  610. if (a.order < b.order)
  611. return -1;
  612. if (a.order > b.order)
  613. return 1;
  614. return 0;
  615. }
  616.  
  617. function showInfo(text, x, y) {
  618. window.setTimeout(function () {
  619. if (!$(".custom-menu").is(':visible')) {
  620. $(".custom-menu .content").html(text);
  621. $(".custom-menu").finish().toggle(100).
  622.  
  623. // In the right position (the mouse)
  624. css({
  625. top: x + "px",
  626. left: y + "px"
  627. });
  628. }
  629.  
  630. }, 10);
  631. }
  632.  
  633. window.showSettingHelp = function (id, obj) {
  634. var help = '';
  635. $.each(userscriptSettings, function (key, setting) {
  636. if (setting.id == id) {
  637. help = setting.help;
  638. }
  639. });
  640. var x = $(obj).offset().top;
  641. var y = $(obj).offset().left;
  642. showInfo(help, x, y);
  643.  
  644.  
  645. }
  646.  
  647. function checkUserscriptMenuButtons() {
  648. $.each(userscriptSettings, function (key, setting) {
  649. $("#" + setting.id).prop("checked", setting.selected);
  650. });
  651. }
  652.  
  653. function StickyTitles(stickies) {
  654. var thisObj = this;
  655. thisObj.load = function () {
  656. stickies.each(function () {
  657. var thisSticky = $(this).wrap('<div class="followWrap" />');
  658. thisSticky.parent().height(thisSticky.outerHeight());
  659. var pos = parseInt(thisSticky.offset().top, 10) - parseInt($(".showSide").offset().top, 10);
  660. $.data(thisSticky[0], 'pos', pos);
  661. });
  662. $(".showSide").off("scroll.stickies").on("scroll.stickies", function () {
  663. thisObj.scroll();
  664. });
  665. };
  666.  
  667. thisObj.scroll = function () {
  668. stickies.each(function (i) {
  669. var thisSticky = $(this),
  670. nextSticky = stickies.eq(i + 1),
  671. prevSticky = stickies.eq(i - 1),
  672. pos = $.data(thisSticky[0], 'pos');
  673. var showSide = $(".showSide");
  674. if (pos <= showSide.scrollTop()) {
  675. thisSticky.addClass("fixed");
  676. if (nextSticky.length > 0 && thisSticky.offset().top >= $.data(nextSticky[0], 'pos') - thisSticky.outerHeight()) {
  677. thisSticky.addClass("absolute").css("top", jQuery.data(nextSticky[0], 'pos') - thisSticky.outerHeight());
  678. }
  679. } else {
  680. thisSticky.removeClass("fixed");
  681. if (prevSticky.length > 0 && showSide.scrollTop() <= $.data(thisSticky[0], 'pos') - prevSticky.outerHeight()) {
  682. prevSticky.removeClass("absolute").removeAttr("style");
  683. }
  684. }
  685. });
  686. }
  687. }
  688.  
  689. jQuery.fn.outerHTML = function (s) {
  690. return s ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html();
  691. };
  692.  
  693.  
  694. /**
  695. * Stores User-Settings to local Storage
  696. */
  697. function storeSettingsVariables() {
  698.  
  699. $.each(userscriptSettings, function (key, setting) {
  700. localStorage.setItem(setting.id, $("#" + setting.id).prop("checked"));
  701. });
  702.  
  703. }
  704.  
  705. /**
  706. * Refreshes Width & Height of Columns
  707. */
  708. function refreshSingleColumnSize() {
  709. var showSide = $(".showSide");
  710. var showGames = $(".showGames");
  711. showSide.scrollTop(0);
  712. /**
  713. * Sticky Titles
  714. */
  715. $(".followMeBar").each(function () {
  716. $(this).removeClass("fixed");
  717. if ($(this).parent().hasClass("followWrap")) {
  718. $(this).unwrap();
  719. }
  720. var thisSticky = $(this).wrap('<div class="followWrap" />');
  721. thisSticky.parent().height(thisSticky.outerHeight());
  722.  
  723. var pos = parseInt(thisSticky.offset().top) - parseInt(showSide.offset().top);
  724. $.data(thisSticky[0], 'pos', pos);
  725. });
  726. var width = $("#ForumTable").width();
  727. createSelector(".followMeBar", "width:" + width + "px;");
  728.  
  729. showGames.find("table").css({
  730. height: window.innerHeight - 150
  731. });
  732.  
  733. //var height = showGames.find("table thead tr").height() + 30;
  734. var height = 48;
  735. createSelector(".showGames table tbody tr:first-of-type td", "padding-top:" + height + "px");
  736.  
  737.  
  738. showSide.css({
  739. height: window.innerHeight - 150
  740. });
  741. showGames.find("table tbody tr:first-of-type td").css("padding-top", height);
  742.  
  743. $(".showGames thead tr td div").unwrap();
  744. checkBookmarkTable()
  745. }
  746.  
  747. /**
  748. * Create a CSS selector
  749. * @param name The name of the object, which the rules are applied to
  750. * @param rules The CSS rules
  751. */
  752. function createSelector(name, rules) {
  753. var style = document.createElement('style');
  754. style.type = 'text/css';
  755. document.getElementsByTagName('head')[0].appendChild(style);
  756. if (!(style.sheet || {}).insertRule) {
  757. (style.styleSheet || style.sheet).addRule(name, rules);
  758. } else {
  759. style.sheet.insertRule(name + "{" + rules + "}", 0);
  760. }
  761. }
  762.  
  763. /**
  764. * Reloads all Games
  765. */
  766. function refreshAllGames(force) {
  767. if ($(".popup").is(":visible") && !force) {
  768. return;
  769. }
  770. if (isEnabled('scrollGames')) {
  771. openGamesTable.scrollTop(0);
  772. myGamesTable.scrollTop(0);
  773. promotedGamesTable.scrollTop(0);
  774. }
  775.  
  776. $('table').css('overflow-y', 'hidden')
  777. refreshMyGames();
  778. refreshOpenGames();
  779. refreshPromotedGames();
  780. loadClots()
  781. }
  782.  
  783.  
  784. function refreshMyGames() {
  785. myGamesTable.find("tbody").fadeTo('fast', 0.15);
  786. var filter = $("#MyGamesFilter").val() || 4;
  787. wljs.Jsutil.Post("?", "FilterChange=" + 4, function (a) {
  788. myGames = wljs.Jsutil.GamesFromDump(a);
  789. d = $("#MyGamesTable").children("tbody");
  790. d.children().remove();
  791.  
  792. if (myGames.length == 0) {
  793. d.append('<tr><td colspan="2" style="color: #C1C1C1">' + warlight.shared.viewmodels.main.MultiPlayerDashboardVM.NoGamesHtml(0) + "</td></tr>");
  794. } else {
  795. for (var f = 0; f < myGames.length;) {
  796. var g = myGames[f];
  797. ++f;
  798. g = (new warlight.shared.viewmodels.main.MyGamesGameVM).Init(1, g, warlight.shared.viewmodels.SignIn.get_CurrentPlayer());
  799. d.append(warlight.shared.viewmodels.main.MultiPlayerDashboardVM.RenderGameHtml(g, null))
  800. }
  801. }
  802. myGamesTable.find("tbody").fadeTo('fast', 1, function () {
  803. myGamesTable.css('overflow-y', 'scroll');
  804. });
  805. $(window).trigger('resize');
  806. });
  807. }
  808.  
  809. function refreshOpenGames() {
  810. deletedMD = deletedRT = 0;
  811. openGamesTable.find("tbody").fadeTo('fast', 0.15);
  812. var page = $('<div />').load('https://www.warlight.net/MultiPlayer/ ', function () {
  813. var data = page.find('#AllOpenGamesData').html();
  814. $('#AllOpenGamesData').html(data);
  815.  
  816. if (openGamesFilters["disableAll"] != true) {
  817. var games = filterGames(wljs.Jsutil.GamesFromDump(data));
  818. } else {
  819. var games = wljs.Jsutil.GamesFromDump(data);
  820. }
  821. $.each(games, function (key, game) {
  822. if ($(game).playerJoined()) {
  823. games[key] = $(game).markJoined();
  824. }
  825. });
  826.  
  827. wljs.multiplayer.OpenGames();
  828. wljs.AllOpenGames = wljs.multiplayer.Ctrl.AllOpenGames = games;
  829. var RealTimeLadderTable = page.find("#RealTimeLadderTable tbody tr:first-of-type").outerHTML();
  830. $("#RealTimeLadderTable tbody tr:first-of-type")
  831. if(RealTimeLadderTable.length == 0) {
  832. $("#RealTimeLadderTable tbody tr:first-of-type").replaceWith("<tr><td>Nobody is playing in the real-time ladder. <a href='/LadderSeason?ID=3'>Join them!</a></td></tr>")
  833. } else {
  834. $("#RealTimeLadderTable tbody tr:first-of-type").replaceWith(RealTimeLadderTable)
  835. }
  836. $("#ForumTable").replaceWith(page.find("#ForumTable").outerHTML())
  837. $("#ClanForumTable").replaceWith(page.find("#ClanForumTable").outerHTML())
  838. setupRightColumn()
  839. updateOpenGamesCounter();
  840.  
  841. wljs.AllOpenGamesData = wljs.multiplayer.Ctrl.AllOpenGamesData = data;
  842. var player = warlight.shared.viewmodels.SignIn.get_CurrentPlayer();
  843. if ((new js.JQuery(this.BothRadio)).is(":checked")) {
  844. player.OpenGamePreference = 1;
  845. } else if ((new js.JQuery(this.MultiDayRadio)).is(":checked")) {
  846. player.OpenGamePreference = 2;
  847. } else if ((new js.JQuery(this.RealTimeRadio)).is(":checked")) {
  848. player.OpenGamePreference = 3;
  849. }
  850. wljs.Jsutil.Post("/MultiPlayer/", "ChangePace=" + player.OpenGamePreference, function (a) {});
  851.  
  852.  
  853. var a = $("#OpenGamesTable").children("tbody");
  854. a.children().remove();
  855. var gamesToShow = warlight.shared.viewmodels.main.MultiPlayerDashboardVM.GamesToShow(wljs.AllOpenGames, player.OpenGamePreference, 0 == this.ShowingAllOpenGames)
  856. for (var b = 0; b < gamesToShow.length;) {
  857. var game = gamesToShow[b];
  858. b++;
  859. game.get_IsLottery() && warlight.shared.viewmodels.main.MultiPlayerDashboardVM.get_HideLotteryGames() ||
  860. (game = (new warlight.shared.viewmodels.main.MyGamesGameVM).Init(2, game), a.append(warlight.shared.viewmodels.main.MultiPlayerDashboardVM.RenderGameHtml(game, null)))
  861. }
  862. openGamesTable.find("tbody").fadeTo('fast', 1, function () {
  863. openGamesTable.css('overflow-y', 'scroll');
  864. });
  865. addOpenGamesSuffix();
  866. domRefresh();
  867.  
  868. });
  869. }
  870.  
  871. function refreshPromotedGames() {
  872. promotedGamesTable.find("tbody").fadeTo('fast', 0.15);
  873. var page = $('<div />').load('https://www.warlight.net/MultiPlayer/ ', function () {
  874. var data = page.find('#MorePromotedGamesData').html();
  875. $('#MorePromotedGamesData').html(data);
  876. wljs.PromotedGames = wljs.Jsutil.GamesFromDump(data);
  877.  
  878. var a = $("#PromotedGamesTable").children("tbody");
  879. a.children().remove();
  880. for (var b = 0; b < wljs.PromotedGames.length;) {
  881. var game = wljs.PromotedGames[b];
  882. b++;
  883. (game = (new warlight.shared.viewmodels.main.MyGamesGameVM).Init(2, game), a.append(warlight.shared.viewmodels.main.MultiPlayerDashboardVM.RenderGameHtml(game, null)))
  884. }
  885. domRefresh();
  886. promotedGamesTable.find("tbody").fadeTo('fast', 1, function () {
  887. promotedGamesTable.css('overflow-y', 'scroll');
  888. });
  889.  
  890. });
  891. }
  892.  
  893.  
  894. /**
  895. * Setups the refresh functionality
  896. */
  897. function setupRefreshFunction() {
  898. lastRefresh = new Date();
  899. var oldRefreshBtn = $("#RefreshBtn");
  900. var oldRefreshBtn2 = $("#RefreshBtn2");
  901. if (oldRefreshBtn.length) {
  902. var newRefreshBtn = $("#refreshAll");
  903. oldRefreshBtn.replaceWith(oldRefreshBtn.clone().removeAttr("id").attr("id", "refreshAll").attr("value", "Refresh (R)"));
  904. newRefreshBtn.appendTo("body");
  905. $("#refreshAll").on("click", function () {
  906. if (new Date() - lastRefresh > 3000) {
  907. lastRefresh = new Date();
  908. refreshAllGames();
  909. }
  910. });
  911. } else if (oldRefreshBtn2.length) {
  912. var newRefreshBtn = $("#refreshAll");
  913. oldRefreshBtn2.replaceWith(oldRefreshBtn2.clone().removeAttr("id").attr("id", "refreshAll").attr("value", "Refresh (R)"));
  914. newRefreshBtn.appendTo("body");
  915. $("#refreshAll").on("click", function () {
  916. if (new Date() - lastRefresh > 3000) {
  917. lastRefresh = new Date();
  918. refreshAllGames();
  919. }
  920. });
  921. }
  922.  
  923. $(".MainColumn").prepend($('#refreshAll'))
  924.  
  925. if (isEnabled('autoRefreshOnFocus')) {
  926. $(window).on('focus', function () {
  927. if (new Date() - lastRefresh > 30000) {
  928. lastRefresh = new Date();
  929. refreshAllGames();
  930. }
  931. });
  932. }
  933.  
  934. $("body").keyup(function (event) {
  935. // "R" is pressed
  936. if (event.which == 82) {
  937. if (new Date() - lastRefresh > 3000) {
  938. lastRefresh = new Date();
  939. refreshAllGames();
  940. }
  941. }
  942. });
  943. }
  944.  
  945.  
  946. function getDate(text) {
  947. var date;
  948.  
  949. if (text.match(/[0-9]+ second/)) {
  950. date = new Date() - 1000;
  951.  
  952. } else if (text.match(/[0-9]+ seconds/)) {
  953. date = new Date() - text.match(/[0-9]+/) * 1000;
  954.  
  955. } else if (text.match(/[0-9]+ minute/)) {
  956. date = new Date() - text.match(/[0-9]+/) * 1000 * 60;
  957.  
  958. } else if (text.match(/[0-9]+ minutes/)) {
  959. date = new Date() - text.match(/[0-9]+/) * 1000 * 60;
  960.  
  961. } else if (text.match(/[0-9]+ hour/)) {
  962. date = new Date() - text.match(/[0-9]+/) * 1000 * 60 * 59;
  963.  
  964. } else if (text.match(/[0-9]+ hours/)) {
  965. date = new Date() - text.match(/[0-9]+/) * 1000 * 60 * 60;
  966.  
  967. } else if (text.match(/[0-9]+ day/)) {
  968. date = new Date() - text.match(/[0-9]+/) * 1000 * 60 * 60 * 36;
  969.  
  970. } else if (text.match(/[0-9]+ days/)) {
  971. date = new Date() - text.match(/[0-9]+/) * 1000 * 60 * 60 * 24;
  972.  
  973. } else if (text.match(/[0-9]+[\/][0-9]+[\/][0-9]+/)) {
  974. var split = text.split('/');
  975. date = new Date(split[2], split[0] - 1, split[1]);
  976. date.setHours(0, 0, 0, 0);
  977. }
  978. return date;
  979. }
  980.  
  981.  
  982. var searches = 0;
  983.  
  984. function filterMailTo() {
  985. if (searches == 0) {
  986. $($("#MainSiteContent div:nth-of-type(1)")[0]).children().remove()
  987. searches++;
  988. }
  989. var find = $("#search_input").val().toLowerCase()
  990. if (find.length > 1) {
  991. removeUncheckedMail()
  992. $.each(data_mail, function (index, val) {
  993. if ($(val).text().toLowerCase().indexOf(find) > -1) {
  994. var id = $(val).attr("id").replace("Lbl_", "")
  995. if ($("#Lbl_" + id).length == 0) {
  996. $($("#MainSiteContent div:nth-of-type(1)")[0]).append('<input type="checkbox" id="CB_' + id + '" onclick="PlayerClicked(' + id + ')">').append(val).append("<br>")
  997. }
  998.  
  999. }
  1000. })
  1001. } else {
  1002. removeUncheckedMail()
  1003. }
  1004.  
  1005. }
  1006.  
  1007. var activeThreadId;
  1008. function hideBlacklistedThreads() {
  1009. var ids = JSON.parse(localStorage.getItem("blackListedThreads"));
  1010. $.each($("#ForumTable tr"), function (key, row) {
  1011. var href = $(row).html().match(/href="\/([^"]*)"/m);
  1012.  
  1013. if (href) {
  1014. href = "/" + href[1]
  1015. if ($.inArray(href, ids) != -1) {
  1016. $(row).remove()
  1017. }
  1018. }
  1019.  
  1020. })
  1021. $("#ForumTable").bind("contextmenu", function (event) {
  1022. $(".highlightedBookmark").removeClass("highlightedBookmark")
  1023. $(event.target).closest("tr").addClass("highlightedBookmark")
  1024. // Avoid the real one
  1025. event.preventDefault();
  1026. href = $(event.target).closest("tr").html().match(/href="\/([^"]*)"/m);
  1027. if (href) {
  1028. activeThreadId = "/" + href[1]
  1029. } else {
  1030. return
  1031. }
  1032.  
  1033. // Show contextmenu
  1034. $(".thread-context").finish().toggle(100).
  1035.  
  1036. // In the right position (the mouse)
  1037. css({
  1038. top: event.pageY + "px",
  1039. left: event.pageX + "px"
  1040. });
  1041. });
  1042. }
  1043.  
  1044. window.hideThread = function() {
  1045. var postId = activeThreadId;
  1046. var blackListedThreads = getBlacklistedThreads();
  1047. blackListedThreads.push(postId);
  1048. setBlacklistedThreads(blackListedThreads);
  1049. hideBlacklistedThreads();
  1050. }
  1051.  
  1052. function removeUncheckedMail() {
  1053. $.each($($("#MainSiteContent div:nth-of-type(1)")[0]).find("label"), function (index, val) {
  1054. var id = $(val).attr("id").replace("Lbl_", "")
  1055. if (!$('#CB_' + id).is(":checked")) {
  1056. $(val).next().remove()
  1057. $(val).prev().remove()
  1058. $(val).remove()
  1059. }
  1060. })
  1061. }
  1062. var data_mail = []
  1063. if (location.href.match(/.*warlight[.]net\/Discussion\/SendMail$/)) {
  1064. $($("#MainSiteContent div:nth-of-type(1)")[0]).before('<input id="search_input" placeholder="Filter" style="margin-bottom:10px">')
  1065. $("#search_input").on("input", function () {
  1066. filterMailTo()
  1067.  
  1068. })
  1069.  
  1070. $.each($($("#MainSiteContent div:nth-of-type(1)")[0]).find("label"), function (index, val) {
  1071. data_mail.push($(val))
  1072. });
  1073.  
  1074. }
  1075.  
  1076. if (!isEnabled('useDefaultBootLabel')) {
  1077. createSelector(".BootTimeLabel", "color:white !important;font-weight:normal!important;font-style:italic;font-size:13px!important;z-index:50;");
  1078. } else {
  1079. createSelector(".BootTimeLabel", "z-index:50;");
  1080. }
  1081.  
  1082. function setGlobalStyles() {
  1083. createSelector('.help-icon', 'display:inline-block;position:absolute; margin-left:10px;margin-top: 2px;cursor:pointer; height: 15px; width: 15px;')
  1084. var winHeight = $(window).height();
  1085. createSelector(".userscript-menu", "display: block;color: #555;text-decoration: none;line-height: 18px;padding: 3px 15px;margin: 0;white-space: nowrap;");
  1086. createSelector(".userscript-menu:hover", "cursor:pointer;background-color: #08C;color: #FFF;cursor: pointer;");
  1087. 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");
  1088. createSelector(".close-userscript", "margin-top: 40px;width: 100%;text-align: center;font-size: 15px;cursor: pointer;background: gray;line-height: 30px;border-radius: 8px;clear: both");
  1089. createSelector(".close-popup-img", "float:right;margin:5px;cursor:pointer;margin-right: 20px");
  1090. createSelector(".popup label", "width: 80%;display: inline-block;font-size: 15px;margin: 5px;");
  1091. createSelector(".popup .title", "color: gray;font-size: 15px;margin-top: 10px;display: inline-block;width: 95%;border-bottom: 1px gray solid;padding-bottom: 3px;");
  1092. createSelector(".popup input[type='checkbox']", "width: 20px;height: 20px;margin-left:30px;margin: 5px;-moz-appearance:none;");
  1093. 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;");
  1094. 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;");
  1095. createSelector(".userscript-show", "display:none");
  1096. createSelector("#MorePromotedGamesHorizontalRow", "display:none");
  1097. createSelector(".newSetting", "color: gold;font-weight: bold;");
  1098. createSelector(".userscript-menu img", "height: 18px;display: inline-block;position: relative;margin-bottom: -5px;margin-right: 7px;");
  1099. 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");
  1100. createSelector(".custom-menu .content", "width: 300px;white-space: pre-wrap;");
  1101. 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');
  1102.  
  1103. createSelector(".popup840", "width: 840px;margin-left: -452px");
  1104. createSelector(".popup600", "width: 600px;margin-left: -332px");
  1105.  
  1106. createSelector(".popup840 .head", "width: 900px");
  1107. createSelector(".popup600 .head", "width: 660px");
  1108. 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;");
  1109. createSelector(".context-menu li", "padding: 8px 12px;cursor: pointer;list-style-type: none;");
  1110. createSelector(".context-menu li:hover", "background-color: #DEF;");
  1111.  
  1112.  
  1113. $("body").on("click", function (e) {
  1114. if ($(".custom-menu").is(':visible')) {
  1115. $(".custom-menu").hide(100);
  1116. }
  1117. });
  1118. }
  1119.  
  1120. var deletedRT = 0;
  1121. var deletedMD = 0;
  1122.  
  1123. function filterGames(games) {
  1124. var filteredGames = [];
  1125. var deletedGames = [];
  1126.  
  1127. $.each(games, function (key, game) {
  1128. if (!$(game).getsFiltered()) {
  1129. filteredGames.push(game);
  1130. } else {
  1131. if (game.RealTimeGame) {
  1132. deletedRT++;
  1133. } else {
  1134. deletedMD++;
  1135. }
  1136. }
  1137. });
  1138.  
  1139. return filteredGames;
  1140. }
  1141.  
  1142. (function ($) {
  1143. $.fn.getsFiltered = function () {
  1144. var game = this[0];
  1145.  
  1146. if (openGamesFilters["hideMaxPlayers"] <= 100 && $(game).numOfPlayers() > openGamesFilters["hideMaxPlayers"]) return true;
  1147. if (openGamesFilters["hideMinPlayers"] <= 100 && $(game).numOfPlayers() < openGamesFilters["hideMinPlayers"]) return true;
  1148. if (openGamesFilters["hideLuck"] < 100 && game.SettingsOpt.LuckModifier * 100 > openGamesFilters["hideLuck"]) return true;
  1149. if (openGamesFilters["hideFFA"] && $(game).numOfTeams() == 0 && $(game).numOfPlayers() > 2) return true;
  1150. if (openGamesFilters["hideTeam"] && $(game).numOfTeams() > 0) return true;
  1151. if (openGamesFilters["hide1v1"] && $(game).numOfPlayers() == 2) return true;
  1152. if (openGamesFilters["hideCustomScenario"] && game.SettingsOpt.DistributionMode === -3) return true;
  1153. if (openGamesFilters["hideNonCustomScenario"] && game.SettingsOpt.DistributionMode !== -3) return true;
  1154. if (openGamesFilters["hidePractice"] && !game.SettingsOpt.RankedGame) return true;
  1155. if (openGamesFilters["hideNoSplit"] && game.SettingsOpt.NoSplit) return true;
  1156. if (openGamesFilters["hideLocalDeployments"] && game.SettingsOpt.LocalDeployments) return true;
  1157. if (openGamesFilters["hideNonPractice"] && game.SettingsOpt.RankedGame) return true;
  1158. if (openGamesFilters["hideManualDistribution"] && !game.SettingsOpt.AutoDistribution) return true;
  1159. if (openGamesFilters["hideAutoDistribution"] && game.SettingsOpt.AutoDistribution) return true;
  1160. if (openGamesFilters["hideKeyword"] && openGamesFilters["hideKeyword"].length > 0 && $(game).containsKeyword()) return true;
  1161. if (openGamesFilters["hideRealTimeBootTime"] > 0 && game.RealTimeGame && game.DirectBoot < openGamesFilters["hideRealTimeBootTime"]) return true;
  1162. if (openGamesFilters["hideMultiDayBootTimeInMs"] > 0 && !game.RealTimeGame && game.DirectBoot < openGamesFilters["hideMultiDayBootTimeInMs"]) return true;
  1163.  
  1164. return false;
  1165. };
  1166.  
  1167. $.fn.numOfPlayers = function () {
  1168. var game = this[0];
  1169. return game.Players.length + game.OpenSeats.length;
  1170.  
  1171. };
  1172.  
  1173. $.fn.playerJoined = function () {
  1174. var game = this[0];
  1175. var playerJoined = false;
  1176. var id = warlight.shared.viewmodels.SignIn.get_CurrentPlayer().ID;
  1177. $.each(game.Players, function (key, player) {
  1178. if (player.PlayerID == id) {
  1179. playerJoined = true;
  1180. }
  1181. });
  1182. return playerJoined;
  1183. };
  1184.  
  1185. $.fn.markJoined = function () {
  1186. var game = this[0];
  1187. game.Name += '##joined##';
  1188. return game;
  1189. };
  1190.  
  1191. $.fn.numOfTeams = function () {
  1192. var game = this[0];
  1193. var teams = 0;
  1194. if (game.AtStartDivideIntoTeamsOfIfOpenGame > 0) return $(game).numOfPlayers() / game.AtStartDivideIntoTeamsOfIfOpenGame;
  1195. if (Math.max.apply(Math, game.OpenSeats) == -1) return 0;
  1196. var maxTeam = Math.max.apply(Math, game.OpenSeats);
  1197. $.each(game.Players, function (key, player) {
  1198. if (player.Team > maxTeam) {
  1199. maxTeam = player.Team;
  1200. };
  1201. });
  1202. return maxTeam + 1;
  1203. }
  1204.  
  1205. $.fn.containsKeyword = function () {
  1206. var game = this[0];
  1207. var keywords = openGamesFilters["hideKeyword"].split(",");
  1208. var title = game._nameLowered || game.Name.toLowerCase();
  1209. var filtered = false;
  1210. $.each(keywords, function (key, keyword) {
  1211. if (title.indexOf(keyword.trim().toLowerCase()) >= 0) {
  1212. filtered = true;
  1213. }
  1214. })
  1215. return filtered;
  1216.  
  1217. };
  1218.  
  1219. }(jQuery));
  1220.  
  1221.  
  1222. function storeFilterVariables() {
  1223. openGamesFilters = {};
  1224.  
  1225. $.each(filters, function (key, filter) {
  1226. if (filter.type == "checkbox") {
  1227. openGamesFilters[filter.id] = $("#" + filter.id).prop("checked");
  1228. }
  1229. });
  1230. openGamesFilters["hideKeyword"] = $("#hideKeyword").val()
  1231. openGamesFilters["hideRealTimeBootTime"] = $("#hideRealTimeBootTime").val()
  1232. openGamesFilters["hideMultiDayBootTimeDays"] = $("#hideMultiDayBootTimeDays").val()
  1233. openGamesFilters["hideMultiDayBootTimeHours"] = $("#hideMultiDayBootTimeHours").val()
  1234.  
  1235. var luck = $("#hideLuck").val();
  1236. openGamesFilters["hideLuck"] = ($.isNumeric(luck) && luck <= 100 && luck >= 0) ? luck : 100;
  1237.  
  1238. var minPlayers = $("#hideMinPlayers").val();
  1239. openGamesFilters["hideMinPlayers"] = ($.isNumeric(minPlayers) && minPlayers <= 100 && minPlayers >= 2) ? minPlayers : 2;
  1240.  
  1241. var maxPlayers = $("#hideMaxPlayers").val();
  1242. openGamesFilters["hideMaxPlayers"] = ($.isNumeric(maxPlayers) && maxPlayers <= 100 && maxPlayers >= 2) ? maxPlayers : 100;
  1243.  
  1244. if (parseFloat(openGamesFilters["hideMinPlayers"]) > parseFloat(openGamesFilters["hideMaxPlayers"])) {
  1245. openGamesFilters["hideMaxPlayers"] = openGamesFilters["hideMinPlayers"]
  1246. }
  1247.  
  1248. var rtBoot = $("#hideRealTimeBootTime").val();
  1249. openGamesFilters["hideRealTimeBootTime"] = $.isNumeric(rtBoot) ? rtBoot * 60 * 1000 : 0;
  1250.  
  1251. var mdBoot = calculateMDBoot($("#hideMultiDayBootTimeHours").val(), $("#hideMultiDayBootTimeDays").val());
  1252.  
  1253. openGamesFilters["hideMultiDayBootTimeDays"] = mdBoot.days;
  1254. openGamesFilters["hideMultiDayBootTimeHours"] = mdBoot.hours;
  1255.  
  1256. openGamesFilters["hideMultiDayBootTimeInMs"] = (parseInt(mdBoot.days) * 24 + parseInt(mdBoot.hours)) * 60 * 60 * 1000;
  1257.  
  1258. localStorage.setItem("openGamesFilters", JSON.stringify(openGamesFilters));
  1259. updateFilterSettings()
  1260. }
  1261.  
  1262. function calculateMDBoot(hours, days) {
  1263. hours = $.isNumeric(hours) ? hours : 0;
  1264. days = $.isNumeric(days) ? days : 0;
  1265.  
  1266. if (hours >= 24) {
  1267. days = parseFloat(days) + parseInt(hours / 24);
  1268. hours -= parseInt(hours / 24) * 24
  1269. }
  1270.  
  1271. return {
  1272. hours: hours,
  1273. days: days
  1274. }
  1275.  
  1276. }
  1277.  
  1278. function updateFilterSettings() {
  1279.  
  1280. $.each(filters, function (key, filter) {
  1281. if (filter.type == "checkbox") {
  1282. $("#" + filter.id).prop("checked", openGamesFilters[filter.id]);
  1283. }
  1284. });
  1285. $("#hideLuck").val(openGamesFilters["hideLuck"] || 100);
  1286. $("#hideMinPlayers").val(openGamesFilters["hideMinPlayers"] || 0);
  1287. $("#hideMaxPlayers").val(openGamesFilters["hideMaxPlayers"] || 100);
  1288. $("#hideKeyword").val(openGamesFilters["hideKeyword"] || "");
  1289. $("#hideRealTimeBootTime").val(openGamesFilters["hideRealTimeBootTime"] / 1000 / 60 || 0);
  1290. $("#hideMultiDayBootTimeDays").val(openGamesFilters["hideMultiDayBootTimeDays"] || 0);
  1291. $("#hideMultiDayBootTimeHours").val(openGamesFilters["hideMultiDayBootTimeHours"] || 0);
  1292. }
  1293.  
  1294. function isEnabled(setting) {
  1295. return $(userscriptSettings).settingIsEnabled(setting);
  1296. }
  1297.  
  1298. function pageIsMultiplayer() {
  1299. return location.href.match(/.*warlight[.]net\/MultiPlayer.*/);
  1300. }
  1301.  
  1302. function pageIsDashboard() {
  1303. return location.href.match(/.*warlight[.]net\/MultiPlayer\/#?$/);
  1304. }
  1305.  
  1306. function pageIsRealTimeLadder() {
  1307. return location.href.match(/.*warlight[.]net\/LadderSeason?ID=3.*$/);
  1308. }
  1309.  
  1310. function pageIsProfile() {
  1311. return location.href.match(/.*warlight[.]net\/[P|p]rofile\?p=[0-9]+$/);
  1312. }
  1313.  
  1314. function pageIsClanThread() {
  1315. return location.href.match(/.*warlight[.]net\/Discussion/);
  1316. }
  1317.  
  1318. function pageIsForumThread() {
  1319. return location.href.match(/.*warlight[.]net\/Forum\/[0-9]+.*/);
  1320. }
  1321.  
  1322. function pageIsForum() {
  1323. return location.href.match(/.*warlight[.]net\/Forum\/.*/);
  1324. }
  1325.  
  1326. function pageIsLadderOverview() {
  1327. return location.href.match(/.*warlight[.]net\/Ladders/);
  1328. }
  1329.  
  1330. function pageIsClanForumThread() {
  1331. return location.href.match(/.*warlight[.]net\/Discussion\/\?ID=[0-9]+.*/);
  1332. }
  1333.  
  1334. function pageIsTournament() {
  1335. return location.href.match(/.*warlight[.]net\/MultiPlayer\/Tournament\?ID=[0-9]+/);
  1336. }
  1337.  
  1338. function pageIsGame() {
  1339. return location.href.match(/.*warlight[.]net\/MultiPlayer\?GameID=[0-9]+/);
  1340. }
  1341.  
  1342. function showOpenGamesLink() {
  1343. $("#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>');
  1344.  
  1345. if (location.href.match(/.*warlight[.]net\/MultiPlayer\/OpenGames.*/)) {
  1346. $("#openGamesTab").addClass("SubTabCellSelected");
  1347. $("#openGamesTab").prev().children().css("visibility", "visible");
  1348. $("#openGamesTab").next().children().css("visibility", "visible");
  1349. }
  1350. }
  1351.  
  1352. function setupOpenGamesFilter() {
  1353. $("#OpenGamesTable thead tr td").prepend('<a id="editFilters" style="color:#DDDDDD;font-size: 14px;float: right;">▼</a>');
  1354.  
  1355.  
  1356. var filtersHTML = "<hr>";
  1357. $.each(filters, function (key, filter) {
  1358. if (filter.type == "checkbox") {
  1359. filtersHTML += '<div class="filterOption"><label for="' + filter.id + '">' + filter.text + '</label><input type="checkbox" id="' + filter.id + '"></div>';
  1360. } else if (filter.type == "custom") {
  1361. filtersHTML += '<div class="filterOption">' + filter.text + '</div>';
  1362. }
  1363. });
  1364.  
  1365. $("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>');
  1366.  
  1367. createSelector('hr', 'height: 1px;border: none;background-color: gray;opacity:0.5;');
  1368. createSelector('.number', 'width: 31px');
  1369. createSelector('.filterOption', 'width: 400px;float: left;margin: 5px;');
  1370. 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;');
  1371. createSelector('.info:hover', 'max-height:500px');
  1372. createSelector('#hideKeyword', 'text-align: left;');
  1373. createSelector('.filter-small, .filter-small label', 'font-size: 12px!important;color: #aaa;');
  1374.  
  1375. $("#hideLuck").after("%");
  1376.  
  1377. createSelector('.ui-button-text-only .ui-button-text', 'padding: .4em 0.6em;');
  1378. createSelector('#editFilters:hover', 'cursor:pointer');
  1379.  
  1380. $(".filters-show").on("change", function () {
  1381. storeFilterVariables();
  1382. });
  1383.  
  1384. $("#editFilters").on("click", function () {
  1385. window.showFilterOptions();
  1386. });
  1387.  
  1388. $(".close-userscript").on("click", function () {
  1389. $(".filters-show").fadeOut();
  1390. $(".overlay").fadeOut();
  1391. refreshAllGames(true);
  1392. });
  1393.  
  1394. $(".close-popup-img").on("click", function () {
  1395. $(".overlay").fadeOut();
  1396. $(".popup").fadeOut();
  1397. });
  1398.  
  1399. updateFilterSettings();
  1400. }
  1401.  
  1402. function hightlightNewClanForumPosts() {
  1403.  
  1404. var regex1 = /.* commented [\n \t]+/;
  1405. var regex2 = / ago/;
  1406. var regex3 = /.*\/Forum\//;
  1407. var regex4 = /-.*/;
  1408.  
  1409. var data = localStorage.getItem('clanForumThreadsTime');
  1410. if (data != null) {
  1411. data = JSON.parse(data);
  1412. } else if (data == null) {
  1413. data = [];
  1414. $.each($('#ClanForumTable tbody tr'), function (index, row) {
  1415. if ($(row).find('td a')[0].href.match(/.*Forum\/[0-9]+/)) {
  1416. var id = $(row).find('td a')[0].href.replace(regex3, "").replace(regex4, "");
  1417. data.push({
  1418. id: id,
  1419. date: new Date()
  1420. });
  1421. }
  1422. });
  1423.  
  1424. localStorage.setItem('clanForumThreadsTime', JSON.stringify(data));
  1425. }
  1426.  
  1427. $.each($('#ClanForumTable tbody tr'), function (index, row) {
  1428. if ($(row).find('td a')[0].href.match(/.*Forum\/[0-9]+/)) {
  1429. var lastComment = $(row).find('td span').text().trim().replace(regex1, "").replace(regex2, "");
  1430. var id = $(row).find('td a')[0].href.replace(regex3, "").replace(regex4, "");
  1431. var found = false;
  1432.  
  1433. $.each(data, function (key, val) {
  1434. if (val.id == id) {
  1435. found = true;
  1436. if (getDate(lastComment) > new Date(val.date)) {
  1437. $(row).css('background', '#4C4C33');
  1438. }
  1439. }
  1440. });
  1441. if (!found) {
  1442. $(row).css('background', '#4C4C33');
  1443. }
  1444. }
  1445. });
  1446. }
  1447.  
  1448. function setupBasicDashboardStyles() {
  1449. createSelector(".GameRow a", "font-size:16px !important;");
  1450. createSelector('#PromotedGamesTable td:last-of-type a img', 'display:none');
  1451. createSelector("#MyGamesTable td > a > img", 'display:none');
  1452. 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;");
  1453. createSelector("#MyGamesTable td span a img, #MyGamesTable td span a img", "display:inherit;");
  1454. createSelector(".GameRow:hover", "background-color:rgb(50, 50, 50);cursor:pointer;");
  1455. createSelector(".GameRow a:hover", "text-decoration:none;");
  1456. createSelector(".TournamentRow a:hover", "text-decoration:none;");
  1457. createSelector(".TournamentRow:hover", "background-color:rgb(50, 50, 50);cursor:pointer;");
  1458. createSelector(".ui-buttonset label", "font-size:11px;");
  1459. createSelector("#OpenGamesTable label:hover", " border: 1px solid #59b4d4;background: #0078a3 50% 50% repeat-x;font-weight: bold;color: #ffffff;");
  1460. createSelector("#OpenGamesTable td:last-child,#MyGamesTable td:last-child, #PromotedGamesTable td:last-child", "position: relative;");
  1461. 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;");
  1462. 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;");
  1463. createSelector(".loading img", "position: absolute;top: 50%;left: 50%;margin-left: -16px;margin-top: -16px;");
  1464. createSelector("img", "position: relative;z-index:50;");
  1465. createSelector("input", "z-index: 98;position: relative;");
  1466. createSelector(".showGames thead tr", "background: rgb(51, 0, 0) none repeat scroll 0% 0%;z-index: 98;position: absolute;padding: 5px;border-bottom: 1px solid rgb(68, 68, 68);border-top-left-radius: 8px;width: calc(100% - 30px);letter-spacing: 1px;");
  1467. createSelector(".showGames table tbody", "display:table;width:100%;");
  1468. createSelector(".showGames table thead", "position:inherit;");
  1469.  
  1470. $.each($(".TournamentRow td"), function () {
  1471. $(this).find("font:first-of-type").appendTo($(this).find("a")).css("font-size", "10px");
  1472. });
  1473. }
  1474.  
  1475. function setupFixedWindowStyles() {
  1476. 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");
  1477. var top = parseInt($(".showSide").offset().top) + parseInt(43);
  1478. createSelector(".followMeBar.fixed", "position: fixed;top: " + top + "px;z-index: 0;z-index:98;");
  1479. createSelector(".followMeBar.fixed.absolute", "position: absolute;");
  1480.  
  1481. createSelector(".showSide", "overflow-y:scroll;float: left;margin-top: 43px;padding-right: 6px;");
  1482. createSelector(".showSide thead", "display:none");
  1483. createSelector(".showSide table", "border-top-right-radius:0;border-top-left-radius:0");
  1484.  
  1485. createSelector("#switchGameRadio label", "margin-left: 6px !important");
  1486. createSelector(".showGames table", "display:block !important");
  1487. 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);");
  1488. createSelector("#MyGamesTable, #PromotedGamesTable, #OpenGamesTable", "display:none");
  1489. createSelector("#MainSiteContent > table > tbody > tr > td", "width:100%");
  1490. createSelector(".MainColumn", "width: calc(60% - 98px)!important;max-width: 800px;min-width:535px");
  1491. createSelector(".SideColumn", "float:left !important");
  1492. createSelector("h2 + span", "margin-right: 50px;");
  1493. createSelector("body", "overflow:hidden");
  1494. createSelector(".SideColumn", "width: 100% !important;");
  1495. createSelector("#MyGamesFilter", "width:200px");
  1496. createSelector(".showGames table", "display:block; overflow-y:scroll; overflow-x:hidden; border:1px gray solid; border-radius:8px");
  1497. createSelector(".adsbygoogle", "margin-top: 25px;");
  1498. createSelector(".showSide", "overflow-y:scroll;float: left;margin-top: 43px;padding-right: 6px;width:33.55%; min-width:500px;margin-left: 20px;border-top-left-radius:8px;border-top-right-radius:8px");
  1499. createSelector("#refreshAll", "width: 140px;float: right;margin-top: 10px;");
  1500. createSelector("#fakeOpenGameMenu label", "margin-right:2px");
  1501. createSelector("#RestoreLotteryGamesBtn", "display:none");
  1502.  
  1503. createSelector('#ForumTable tbody tr td, #ClanForumTable tbody tr td', 'overflow:hidden;position:relative');
  1504. 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;');
  1505. createSelector('#ForumTable tbody tr td span, #ClanForumTable tbody tr td span', 'display: inline-block;z-index: 1;float: left;position: relative;');
  1506. createSelector('#ForumTable tbody tr:hover, #ClanForumTable tbody tr:hover', 'background-color:rgb(50, 50, 50)');
  1507.  
  1508. createSelector('#ForumTable tbody tr td a[href="/Forum/Forum"]', 'position: relative;');
  1509. createSelector('#ClanForumTable tbody tr td a[href="/Clans/Forum"]', 'position: relative;');
  1510.  
  1511.  
  1512. }
  1513.  
  1514. function setupFixedTitlesInSideColumn() {
  1515. var blogTable = $("#BlogTable");
  1516. var realTimeLadderTable = $("#RealTimeLadderTable");
  1517. var forumTable = $("#ForumTable");
  1518. var clanForumTable = $("#ClanForumTable");
  1519. var mapOfTheWeekTable = $("#MapOfTheWeekTable");
  1520. var leaderboardTable = $("#LeaderboardTable");
  1521. var myTournamentsTable = $("#MyTournamentsTable");
  1522. var bookmarkTable = $("#BookmarkTable");
  1523.  
  1524. blogTable.before("<div class='followMeBar'>" + blogTable.find("thead > tr > td").html() + "</div>");
  1525. realTimeLadderTable.before("<div class='followMeBar'>" + realTimeLadderTable.find("thead > tr > td").html() + "</div>");
  1526. forumTable.before("<div class='followMeBar'>" + forumTable.find("thead > tr > td").html() + "</div>");
  1527. clanForumTable.before("<div class='followMeBar'>" + clanForumTable.find("thead > tr > td").html() + "</div>");
  1528. mapOfTheWeekTable.before("<div class='followMeBar'>" + mapOfTheWeekTable.find("thead > tr > td").html() + "</div>");
  1529. if (!isEnabled("hideCoinsGlobally")) {
  1530. leaderboardTable.before("<div class='followMeBar'>" + leaderboardTable.find("thead > tr > td").html() + "</div>");
  1531. }
  1532. myTournamentsTable.before("<div class='followMeBar'>" + myTournamentsTable.find("thead > tr > td").html() + "</div>");
  1533. bookmarkTable.before("<div class='followMeBar'>" + bookmarkTable.find("thead > tr > td").html() + "</div>");
  1534. var clotTable = $("#ClotTable");
  1535. clotTable.before("<div class='followMeBar'>" + clotTable.find("thead > tr > td").html() + "</div>");
  1536.  
  1537. new StickyTitles(jQuery(".followMeBar")).load();
  1538. }
  1539.  
  1540. function setupFixedWindowWithScrollableGames() {
  1541. var gameButtons = '<div style="margin: 10px;" id="switchGameRadio" class="ui-buttonset">';
  1542. gameButtons += '<input type="radio" id="ShowMyGames" name="switchGames" checked="checked" class="ui-helper-hidden-accessible">';
  1543. 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>';
  1544. if (isEnabled('hidePromotedGames') || isEnabled('hideCoinsGlobally')) {
  1545. gameButtons += '<input type="radio" id="ShowOpenGames" name="switchGames" class="ui-helper-hidden-accessible">';
  1546. 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>';
  1547. } else {
  1548. gameButtons += '<input type="radio" id="ShowOpenGames" name="switchGames" class="ui-helper-hidden-accessible">';
  1549. 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>';
  1550. gameButtons += '<input type="radio" id="ShowCoinGames" name="switchGames" class="ui-helper-hidden-accessible">';
  1551. 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>';
  1552. }
  1553.  
  1554. gameButtons += '</div>';
  1555.  
  1556.  
  1557. var mainColumn = $(".MainColumn ");
  1558. mainColumn.prepend('<div class="showGamesContainer">' + gameButtons + '<div class="showGames"></div></div>');
  1559. myGamesTable.appendTo(".showGames");
  1560.  
  1561. mainColumn.after('<div class="showSide"></div>');
  1562. $(".SideColumn").appendTo(".showSide");
  1563.  
  1564. setupFixedWindowStyles();
  1565.  
  1566. refreshSingleColumnSize();
  1567.  
  1568. $("#switchGameRadio").find("label").on("click", function () {
  1569. var newShowGames = $(this).attr("for");
  1570. if (newShowGames != showGamesActive) {
  1571. $.each($("#switchGameRadio").find("label"), function () {
  1572. $(this).removeClass("ui-state-active");
  1573. });
  1574. $(this).addClass("ui-state-active");
  1575.  
  1576. if (newShowGames == "ShowMyGames") {
  1577. showGamesActive = newShowGames;
  1578. promotedGamesTable.appendTo("body");
  1579. openGamesTable.appendTo("body");
  1580. myGamesTable.appendTo(".showGames");
  1581. } else if (newShowGames == "ShowCoinGames") {
  1582. showGamesActive = newShowGames;
  1583. myGamesTable.appendTo("body");
  1584. openGamesTable.appendTo("body");
  1585. promotedGamesTable.appendTo(".showGames");
  1586. } else if (newShowGames == "ShowOpenGames") {
  1587. showGamesActive = newShowGames;
  1588. myGamesTable.appendTo("body");
  1589. promotedGamesTable.appendTo("body");
  1590. openGamesTable.appendTo(".showGames");
  1591. }
  1592.  
  1593. refreshSingleColumnSize()
  1594. }
  1595. });
  1596. }
  1597.  
  1598. function hideRightColumn() {
  1599. if (isEnabled('scrollGames')) {
  1600. $(".showSide").css("display", "none");
  1601. createSelector(".MainColumn", "margin: auto;");
  1602. createSelector(".MainColumn", "max-width: 800px;");
  1603. createSelector(".MainColumn", "width: 60%!important;");
  1604. createSelector(".MainColumn", "float: none !important;");
  1605. createSelector(".MainColumn", "min-width: 600px !important;");
  1606. } else {
  1607. $(".SideColumn").css("display", "none");
  1608. $(".MainColumn").css("width", "100%");
  1609. $(".MainColumn").css("max-width", "800px");
  1610. }
  1611. }
  1612.  
  1613. function registerGameTabClick() {
  1614. if (lastClick - new Date() > 2000) {
  1615. openGamesTable.scrollTop(0);
  1616. lastClick = new Date();
  1617. }
  1618. window.setTimeout(function () {
  1619. domRefresh();
  1620. addOpenGamesSuffix();
  1621. }, 1);
  1622. }
  1623.  
  1624. function registerClanThread() {
  1625. var id = location.href.replace(/.*warlight[.]net\/Discussion\/[?]ID=/, "");
  1626. var data = localStorage.getItem('clanForumThreadsTime');
  1627.  
  1628. if (data != null) {
  1629. data = JSON.parse(data)
  1630. } else {
  1631. data = [];
  1632. }
  1633. var found = false;
  1634.  
  1635. $.each(data, function (key, val) {
  1636. if (val.id == id) {
  1637. data[key] = {
  1638. id: id,
  1639. date: new Date()
  1640. };
  1641. found = true;
  1642. }
  1643. });
  1644. if (!found) {
  1645. data.push({
  1646. id: id,
  1647. date: new Date()
  1648. });
  1649. }
  1650.  
  1651. localStorage.setItem('clanForumThreadsTime', JSON.stringify(data))
  1652. }
  1653.  
  1654. function updateOpenGamesCounter() {
  1655. var numMD = countGames(wljs.AllOpenGames, 1);
  1656. var numRT = countGames(wljs.AllOpenGames, 2);
  1657. var numBoth = parseInt(numMD) + parseInt(numRT)
  1658.  
  1659. //Both
  1660. $("#OpenGamesTable [for='BothRadio'] span").text('Both (' + numBoth + ')')
  1661. //Real
  1662. $("#OpenGamesTable [for='RealTimeRadio'] span").text('Real-Time (' + numRT + ')')
  1663. //Multi-Day
  1664. $("#OpenGamesTable [for='MultiDayRadio'] span").text('Multi-Day (' + numMD + ')')
  1665. }
  1666.  
  1667. // Type 1 : Multiday
  1668. // Type 2 : Realtime
  1669. function countGames(games, type) {
  1670. games = system.linq.Enumerable.Where(games, function (a) {
  1671. if (type == 1) return !a.RealTimeGame;
  1672. if (type == 2) return a.RealTimeGame;
  1673. });
  1674. return system.linq.Enumerable.ToArray(games).length
  1675. }
  1676.  
  1677. function addOpenGamesSuffix() {
  1678. var deletedBoth = parseInt(deletedMD) + parseInt(deletedRT);
  1679. $("#OpenGamesTable tbody tr:not(.GameRow)").remove();
  1680. var active = $("#OpenGamesTable .ui-buttonset .ui-state-active").text();
  1681.  
  1682. if (active.indexOf('Both') > -1 && deletedBoth > 0) {
  1683. //Both
  1684. $("#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>");
  1685. } else if (active.indexOf('Real') > -1 && deletedRT > 0) {
  1686. //Real
  1687. $("#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>");
  1688. } else if (active.indexOf('Multi') > -1 && deletedMD > 0) {
  1689. //Multi-Day
  1690. $("#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>");
  1691. }
  1692.  
  1693. }
  1694.  
  1695. function getNumHiddenLabelText(num) {
  1696. return num == 1 ? "1 Game is hidden" : (num + " Games are hidden");
  1697. }
  1698.  
  1699.  
  1700. function loadPrivateNotes() {
  1701. console.log("loading private notes")
  1702. $("#FeedbackMsg").after('<div class="profileBox" id="privateNotes"><h3>Private Notes</h3><p style="width: 285px;overflow:hidden" class="content">Loading Privates Notes..</p></div>');
  1703. var url = $("img[alt='Private Notes']").parent()[0].href;
  1704. var page = $('<div />').load(url, function () {
  1705. var notes = page.find('#PostForDisplay_0').html().trim();
  1706. if (notes) {
  1707. $('#privateNotes .content').html(notes);
  1708. } else {
  1709. $('#privateNotes .content').html('You don\'t have any Private Notes.');
  1710. }
  1711.  
  1712. });
  1713. }
  1714.  
  1715. window.showFilterOptions = function () {
  1716. $(".filters-show").fadeIn();
  1717. $(".overlay").fadeIn();
  1718. }
  1719.  
  1720. function domRefresh() {
  1721. // $("body").css("diplay", "none");
  1722. // $("body").css("diplay", "block");
  1723. $("body").hide(0).show(0);
  1724. $(window).trigger('resize')
  1725. }
  1726.  
  1727. window.showFilterHelp = function (text, obj) {
  1728. window.setTimeout(function () {
  1729. if (!$(".custom-menu").is(':visible')) {
  1730. $(".custom-menu .content").html(text);
  1731. $(".custom-menu").finish().toggle(100).
  1732.  
  1733. // In the right position (the mouse)
  1734. css({
  1735. top: $(obj).offset().top + "px",
  1736. left: $(obj).offset().left + "px"
  1737. });
  1738. }
  1739.  
  1740. }, 10);
  1741. }
  1742.  
  1743. function setupBookmarkMenu() {
  1744. 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'>";
  1745.  
  1746. $("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>");
  1747.  
  1748. $("bookmarkMenu").append('<div id="bookmarkMenu"></div>');
  1749.  
  1750. $(".close-popup-img").on("click", function () {
  1751. $(".popup").fadeOut();
  1752. $(".overlay").fadeOut();
  1753. });
  1754. createSelector(".highlightedBookmark", "background-color:rgb(50, 50, 50);cursor:pointer;");
  1755. $("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>")
  1756. $("body").append("<ul class='context-menu thread-context'><li onclick='hideThread()'>Hide</li></ul>")
  1757. $("body").append("<ul class='context-menu playersearch-context'><li onclick='findMostCommonGames()'>Most Common Games (Friends)</li></ul>")
  1758.  
  1759. }
  1760.  
  1761. function setupBookmarkTable() {
  1762. $(".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>');
  1763.  
  1764. if (bookmarks.length > 0) {
  1765. refreshBookmarks();
  1766.  
  1767. } else {
  1768. var tables = $(".SideColumn .dataTable").filter(function () {
  1769. return $(this).css('opacity') == '1';
  1770. })
  1771. table = $(tables).get($(tables).length - 1)
  1772. $(table).after('<div style="text-align: left;margin-top: 15px;"><a onclick="showAddBookmark()" style="cursor:pointer">Add a Bookmark...</a></div>')
  1773. }
  1774. }
  1775.  
  1776. function refreshBookmarks() {
  1777. setBookmarks()
  1778. $("#BookmarkTable tbody tr").remove();
  1779. bookmarks.sort((a, b) => {return a.id - b.id})
  1780. var data = "<tbody>";
  1781. $.each(bookmarks, function (key, bookmark) {
  1782. data += '<tr data-bookmarkId="' + bookmark.id + '"><td><a ' + (bookmark.newWindow ? 'target="blank"' : "") + ' href="' + bookmark.url + '">' + bookmark.name + '</a>';
  1783. data += '<a onclick="deleteBookmark(' + bookmark.id + ')" style="display:inline-block;float:right; opacity: 0.6;cursor: pointer;margin-right:5px">';
  1784. data += '<img src="' + IMAGES.TRASH + '" width="15" height="15" ></a></td></tr>';
  1785. })
  1786.  
  1787. $("#BookmarkTable").prepend(data + '</tbody>');
  1788.  
  1789. }
  1790.  
  1791. var bookmarkId;
  1792. window.showAddBookmark = function () {
  1793. $(".overlay").fadeIn();
  1794. $("#bookmarkMenu").show();
  1795. bookmarkId = undefined
  1796. }
  1797.  
  1798. window.editBookmark = function () {
  1799. $.each(bookmarks, function (key, bookmark) {
  1800. if (bookmarkId == bookmark.id) {
  1801. $("#bookmarkURL").val(bookmark.url);
  1802. $("#bookmarkName").val(bookmark.name);
  1803. $("#bookmarkNewWindow").prop("checked", bookmark.newWindow)
  1804. }
  1805. })
  1806.  
  1807. $(".overlay").fadeIn();
  1808. $("#bookmarkMenu").show();
  1809. }
  1810.  
  1811. window.moveBookmarkUp = function() {
  1812. var oldIdx
  1813. var newIdx = -1
  1814. $.each(bookmarks, function (key, bookmark) {
  1815. if (bookmarkId == bookmark.id) {
  1816. oldIdx = key
  1817. }
  1818. })
  1819. var tempId = -1
  1820. $.each(bookmarks, function (key, bookmark) {
  1821. if (bookmark.id < bookmarkId && bookmark.id > tempId) {
  1822. newIdx = key
  1823. tempId = bookmark.id
  1824. }
  1825. })
  1826. if(newIdx != -1) {
  1827. var oldId = bookmarks[oldIdx].id
  1828. var newId = bookmarks[newIdx].id
  1829. bookmarks[oldIdx].id = -1
  1830. bookmarks[newIdx].id = oldId
  1831. bookmarks[oldIdx].id = newId
  1832.  
  1833. localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
  1834.  
  1835. $("#bookmarkURL").val('');
  1836. $("#bookmarkName").val('');
  1837. $("#bookmarkNewWindow").prop('checked', false);
  1838. $(".overlay").fadeOut();
  1839.  
  1840. showBookmarkTable();
  1841.  
  1842. refreshBookmarks();
  1843. }
  1844. }
  1845.  
  1846. window.moveBookmarkDown = function() {
  1847. var oldIdx
  1848. var newIdx = -1
  1849. $.each(bookmarks, function (key, bookmark) {
  1850. if (bookmarkId == bookmark.id) {
  1851. oldIdx = key
  1852. }
  1853. })
  1854. var tempId = 10000000
  1855. $.each(bookmarks, function (key, bookmark) {
  1856. if (bookmark.id > bookmarkId && bookmark.id < tempId) {
  1857. newIdx = key
  1858. tempId = bookmark.id
  1859. }
  1860. })
  1861. if(newIdx != -1) {
  1862. var oldId = bookmarks[oldIdx].id
  1863. var newId = bookmarks[newIdx].id
  1864. bookmarks[oldIdx].id = -1
  1865. bookmarks[newIdx].id = oldId
  1866. bookmarks[oldIdx].id = newId
  1867.  
  1868. localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
  1869.  
  1870. $("#bookmarkURL").val('');
  1871. $("#bookmarkName").val('');
  1872. $("#bookmarkNewWindow").prop('checked', false);
  1873. $(".overlay").fadeOut();
  1874.  
  1875. showBookmarkTable();
  1876.  
  1877. refreshBookmarks();
  1878. }
  1879. }
  1880.  
  1881.  
  1882. window.deleteBookmark = function (id) {
  1883. var idx;
  1884. $.each(bookmarks, function (key, bookmark) {
  1885. if (id == bookmark.id) {
  1886. idx = key;
  1887. }
  1888. })
  1889. $("[data-bookmarkId='" + id + "']").remove();
  1890. bookmarks.splice(idx, 1);
  1891. localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
  1892.  
  1893. }
  1894.  
  1895. window.saveBookmark = function () {
  1896. $("#bookmarkMenu").hide();
  1897. var url = $("#bookmarkURL").val().trim();
  1898. url = (url.lastIndexOf('http', 0) != 0) && (url.lastIndexOf('javascript', 0) != 0) ? "http://" + url : url;
  1899. var name = $("#bookmarkName").val().trim();
  1900. var newWindow = $("#bookmarkNewWindow").prop("checked");
  1901. if(bookmarkId == undefined) {
  1902. bookmarks.push({
  1903. name: name,
  1904. url: url,
  1905. newWindow: newWindow,
  1906. id: getBookmarkId()
  1907. });
  1908. } else {
  1909. var idx;
  1910. $.each(bookmarks, function (key, bookmark) {
  1911. if (bookmarkId == bookmark.id) {
  1912. idx = key
  1913. }
  1914. })
  1915. bookmarks[idx] = {
  1916. name: name,
  1917. url: url,
  1918. newWindow: newWindow,
  1919. id: bookmarkId
  1920. }
  1921. }
  1922. localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
  1923.  
  1924. $("#bookmarkURL").val('');
  1925. $("#bookmarkName").val('');
  1926. $("#bookmarkNewWindow").prop('checked', false);
  1927. $(".overlay").fadeOut();
  1928.  
  1929. showBookmarkTable();
  1930.  
  1931. refreshBookmarks();
  1932. }
  1933.  
  1934. function checkBookmarkTable() {
  1935. if (bookmarks.length == 0) {
  1936. hideBookmarkTable();
  1937. }
  1938.  
  1939. }
  1940.  
  1941. function hideBookmarkTable() {
  1942. $("#BookmarkTable").hide();
  1943. if ($("#BookmarkTable").prev().hasClass("followWrap")) {
  1944. $("#BookmarkTable").prev().hide();
  1945. }
  1946. if ($("#BookmarkTable").next().is('br')) {
  1947. $("#BookmarkTable").next().hide();
  1948. }
  1949. }
  1950.  
  1951. function showBookmarkTable() {
  1952. $("#BookmarkTable").show();
  1953. if ($("#BookmarkTable").prev().hasClass("followWrap")) {
  1954. $("#BookmarkTable").prev().show();
  1955. }
  1956. if ($("#BookmarkTable").next().is('br')) {
  1957. $("#BookmarkTable").next().show();
  1958. }
  1959. }
  1960.  
  1961. window.bookmarkForumThread = function () {
  1962. var title = $("title").text().replace(' - Play Risk Online Free - WarLight', '');
  1963. var url = window.location.href;
  1964.  
  1965. $("#bookmarkURL").val(url);
  1966. $("#bookmarkName").val(title);
  1967. showAddBookmark();
  1968.  
  1969. }
  1970. window.bookmarkTournament = function () {
  1971. var title = $("#TournamentName").text().replace("Tournament: ", "").trim();
  1972. var url = window.location.href;
  1973.  
  1974. $("#bookmarkURL").val(url);
  1975. $("#bookmarkName").val(title);
  1976. showAddBookmark();
  1977.  
  1978. }
  1979.  
  1980. function addDefaultBookmark() {
  1981. bookmarks = [];
  1982. bookmarks.push({
  1983. name: "Tidy up Your Dashboard #2",
  1984. url: "https://www.warlight.net/Forum/106092-tidy-up-dashboard-2",
  1985. newWindow: false,
  1986. id: getBookmarkId()
  1987. });
  1988. localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
  1989. }
  1990.  
  1991. function getBookmarkId() {
  1992. var id = 0;
  1993.  
  1994. $.each(bookmarks, function (key, bookmark) {
  1995. id = bookmark.id > id ? bookmark.id : id;
  1996. })
  1997.  
  1998. return id + 1;
  1999. }
  2000.  
  2001. var findMeIndex = -1;
  2002. window.findNextInTournament = function() {
  2003. var boxes = getPlayerBoxes();
  2004. var max = boxes.length - 1;
  2005. findMeIndex = findMeIndex == max ? 0 : findMeIndex + 1;
  2006. panzoomMatrix = undefined;
  2007. findInTournament();
  2008. }
  2009.  
  2010. function setupTournamentFindMe() {
  2011. $("body").keyup(function (event) {
  2012. // "Left" is pressed
  2013. var boxes = getPlayerBoxes();
  2014. var max = boxes.length - 1;
  2015. if(event.which == 37) {
  2016. findMeIndex = findMeIndex == 0 ? max : findMeIndex - 1;
  2017. panzoomMatrix = undefined;
  2018. findInTournament();
  2019. }
  2020. // "Right" is pressed
  2021. else if(event.which == 39) {
  2022. findMeIndex = findMeIndex == max ? 0 : findMeIndex + 1;
  2023. panzoomMatrix = undefined;
  2024. findInTournament();
  2025. }
  2026. // "Home" is pressed
  2027. else if(event.which == 36) {
  2028. findMeIndex = 0;
  2029. panzoomMatrix = undefined;
  2030. findInTournament();
  2031. }
  2032. // "End" is pressed
  2033. else if(event.which == 35) {
  2034. findMeIndex = boxes.length - 1;
  2035. panzoomMatrix = undefined;
  2036. findInTournament();
  2037. }
  2038. });
  2039. window.players = []
  2040. $("[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>');
  2041. 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')
  2042. createSelector('#findMe', 'border: 1px solid #666666;border-bottom-width: 0')
  2043.  
  2044. 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;}',
  2045. head = document.head || document.getElementsByTagName('head')[0],
  2046. style = document.createElement('style');
  2047.  
  2048. style.type = 'text/css';
  2049. if (style.styleSheet) {
  2050. style.styleSheet.cssText = css;
  2051. } else {
  2052. style.appendChild(document.createTextNode(css));
  2053. }
  2054.  
  2055. head.appendChild(style);
  2056.  
  2057.  
  2058. $("#findMe").append('<div id="selectContainer"><div id="playerSelectInputContainer"><input placeholder="Search a Player" type="text" id="playerSelectInput"></input></div><div id="playerContainer"></div></div>');
  2059. self = {
  2060. id: warlight.shared.viewmodels.SignIn.get_CurrentPlayer().ID,
  2061. name: warlight.shared.viewmodels.SignIn.get_CurrentPlayer().Name,
  2062. 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),
  2063. team: $("[data-playerid='" + warlight.shared.viewmodels.SignIn.get_CurrentPlayer().ID + "'] td:nth-of-type(2)").text()
  2064. };
  2065. window.currentPlayer = self;
  2066. $.each($("#PlayingPlayers tr"), function (key, playerRow) {
  2067. var id = $(playerRow).attr("data-playerid");
  2068. var fullID = $(playerRow).find("a").get($(playerRow).find("a").length - 1).href.replace(/.*warlight.net\/Profile\?p=/, "");
  2069. var name = $(playerRow).find("td a").text();
  2070. var img = $(playerRow).find("td img").attr("src");
  2071. var team = $("[data-playerid='" + id + "'] td:nth-of-type(2)").text();
  2072. if (img && img.indexOf("MemberIcon") > -1) {
  2073. img = "";
  2074. }
  2075. window.players.push({
  2076. id: id,
  2077. fullID: fullID,
  2078. name: name,
  2079. img: img,
  2080. team: team
  2081. });
  2082. });
  2083.  
  2084.  
  2085. $("#playerSelectInput").on('input', function (data) {
  2086. $(".playerElement").remove();
  2087. var search = $(this).val().toLowerCase();
  2088. $("#playerContainer").append("<div class='playerElement' onclick='setCurrentplayer(self)'>" + self.name + " (Me)</div>")
  2089. $.each(window.players, function (key, player) {
  2090. if (player.name.toLowerCase().indexOf(search) > -1 && self.name != player.name) {
  2091. var img = player.img ? "<img src='" + player.img + "'>" : "";
  2092. $("#playerContainer").append("<div onclick='setCurrentplayer(players[" + key + "])' class='playerElement'>" + img + "<span>" + htmlEscape(player.name) + "</span>" + "</div>")
  2093. }
  2094. });
  2095.  
  2096. $("#activePlayer").html(window.currentPlayer.name == self.name ? "Me" : window.currentPlayer.name);
  2097. $("#playerContainer").scrollTop(0)
  2098.  
  2099. });
  2100. $("#playerSelectInput").trigger("input");
  2101.  
  2102. $("#showPlayerSelect").on("click", function () {
  2103. $("#selectContainer").toggle(100);
  2104. $("#playerContainer").scrollTop(0);
  2105. $("#playerSelectInput").trigger("input");
  2106. $("#playerSelectInput").focus();
  2107. });
  2108. createSelector("#playerSelectInputContainer", "height: 28px; ");
  2109. createSelector(".border-red", "border: 3px red solid !important; ");
  2110. createSelector(".playerElement span, .playerElement img", "display:inline-block; margin-right: 10px");
  2111. createSelector("#showPlayerSelect", "color: #DDDDDD;font-size: 14px;margin: 5px 5px 0 -3px;cursor: pointer; display: inline-block;margin-right: 10px;");
  2112. createSelector("#playerSelectInput", "display: block;margin: 5px 3%;width: 93%;");
  2113. createSelector("#activePlayer", "cursor:pointer");
  2114. createSelector(".playerElement", "border-bottom: 1px gray solid;padding: 7px;color: white; clear:both; height: 14px; font-weight: normal;");
  2115. createSelector(".playerElement:hover", "background: rgb(102, 102, 102);");
  2116. createSelector("#playerContainer", "border: 2px gray solid; overflow-y: auto; overflow-x: hidden;max-height: 275px; min-width: 175px; ");
  2117. 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");
  2118.  
  2119.  
  2120.  
  2121. }
  2122.  
  2123.  
  2124. window.setCurrentplayer = function (player) {
  2125. window.currentPlayer = {
  2126. id: player.id,
  2127. name: player.name,
  2128. fullID: player.fullID,
  2129. team: player.team
  2130. };
  2131. $("#selectContainer").toggle(100);
  2132. $("#activePlayer").html(htmlEscape(player.name == self.name ? "Me" : player.name));
  2133. $("#playerSelectInput").val("");
  2134. panzoomMatrix = undefined;
  2135. findMeIndex = 0;
  2136. window.findInTournament();
  2137. }
  2138.  
  2139. var panzoomMatrix;
  2140. window.findInTournament = function () {
  2141. var id;
  2142. $("#selectContainer").hide(100);
  2143. if ($("[href='#PlayersTab']").parent().hasClass("ui-state-active")) {
  2144. id = window.currentPlayer.id;
  2145. if ($("#PlayingPlayers [data-playerid='" + id + "']").length > 0) {
  2146. var player = $("#PlayingPlayers [data-playerid='" + id + "']");
  2147. var box = $("#CenterTabs").parent()
  2148. var offset = player.offset().top - box.offset().top - box.height() / 2
  2149.  
  2150. box.stop().animate({
  2151. scrollTop: offset
  2152. }, '500', 'swing');
  2153.  
  2154. window.setTimeout(function () {
  2155. $("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").addClass("pulsate");
  2156. window.setTimeout(function () {
  2157. $(".pulsate").removeClass("pulsate");
  2158. }, 1000);
  2159. }, 250);
  2160. } else {
  2161. showInfo("You didn't join this tournament.", $("#findMe").offset().top + 25, $("#findMe").offset().left + 25);
  2162. }
  2163.  
  2164. } else if ($("[href='#BracketTab']").parent().hasClass("ui-state-active") && $("[src='https://d2wcw7vp66n8b3.cloudfront.net/Images/TournamentIconBig_RR.png']").length == 0) {
  2165. id = window.currentPlayer.fullID;
  2166. if (getPlayerBoxes().length > 0) {
  2167.  
  2168. if (!panzoomMatrix) {
  2169. var currentMatrix = $("#Visualize").panzoom("getMatrix");
  2170. $("#Visualize").panzoom("reset", {
  2171. animate: false
  2172. });
  2173.  
  2174. VisualizePanzoom.panzoom("zoom", {
  2175. increment: 0.75,
  2176. animate: false
  2177. })
  2178. var boxes = getPlayerBoxes();
  2179. $(".TeamBoxHighlighted").removeClass("TeamBoxHighlighted");
  2180. boxes.addClass("TeamBoxHighlighted");
  2181. var offsetTop = $(boxes.get(findMeIndex)).offset().top - $("#VisualizeContainer").offset().top - $("#VisualizeContainer").height() / 4;
  2182. var offsetLeft = $(boxes.get(findMeIndex)).offset().left - $("#VisualizeContainer").offset().left - $("#VisualizeContainer").width() / 2;
  2183.  
  2184. $(".border-red").removeClass("border-red");
  2185. $(boxes.get(findMeIndex)).addClass("border-red");
  2186. $("#Visualize").panzoom("pan", 0 - offsetLeft, 100 - offsetTop, {
  2187. relative: true,
  2188. animate: false
  2189. });
  2190.  
  2191. panzoomMatrix = $("#Visualize").panzoom("getMatrix");
  2192. $("#Visualize").panzoom("setMatrix", currentMatrix, {
  2193. animate: false
  2194. });
  2195. }
  2196.  
  2197. window.setTimeout(function () {
  2198. $("#Visualize").panzoom("setMatrix", panzoomMatrix, {
  2199. animate: true
  2200. })
  2201. window.setTimeout(function () {
  2202. //getPlayerBoxes().addClass("pulsate-border");
  2203. window.setTimeout(function() {
  2204. $(".pulsate-border").removeClass("pulsate-border");
  2205. }, 2000)
  2206. }, 400);
  2207. }, 10)
  2208.  
  2209. } else {
  2210. if ($("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").length == 0) {
  2211. showInfo("You didn't join this tournament.", $("#findMe").offset().top + 25, $("#findMe").offset().left + 25);
  2212.  
  2213. } else {
  2214. showInfo("This tournament didn't start yet.", $("#findMe").offset().top + 25, $("#findMe").offset().left + 25);
  2215.  
  2216. }
  2217. }
  2218. }
  2219. }
  2220.  
  2221. function getPlayerBoxes() {
  2222. var boxes = $(".GameBox [href='/Profile?p=" + window.currentPlayer.fullID + "']").closest(".TeamBox");
  2223. if(boxes.length == 0) {
  2224. boxes = $("[title='" + window.currentPlayer.team + "']").closest(".TeamBox");
  2225. }
  2226. return boxes;
  2227. }
  2228.  
  2229. function htmlEscape(str) {
  2230. return String(str)
  2231. .replace(/&/g, '&amp;')
  2232. .replace(/"/g, '&quot;')
  2233. .replace(/'/g, '&#39;')
  2234. .replace(/</g, '&lt;')
  2235. .replace(/>/g, '&gt;');
  2236. }
  2237.  
  2238. function setBookmarks() {
  2239. var bm = localStorage.getItem("bookmarks");
  2240.  
  2241. if (bm) {
  2242. bookmarks = $.parseJSON(bm);
  2243. } else {
  2244. bookmarks = [];
  2245. }
  2246. }
  2247.  
  2248.  
  2249. $("#BookmarkTable").bind("contextmenu", function (event) {
  2250. $(".highlightedBookmark").removeClass("highlightedBookmark")
  2251. $(event.target).closest("tr").addClass("highlightedBookmark")
  2252. // Avoid the real one
  2253. event.preventDefault();
  2254. bookmarkId = $(event.target).closest("tr").attr("data-bookmarkid")
  2255. // Show contextmenu
  2256. $(".bookmark-context").finish().toggle(100).
  2257. // In the right position (the mouse)
  2258. css({
  2259. top: event.pageY + "px",
  2260. left: event.pageX + "px"
  2261. });
  2262. });
  2263.  
  2264.  
  2265. // If the document is clicked somewhere
  2266. $(document).bind("mousedown", function (e) {
  2267. // If the clicked element is not the menu
  2268. if (!$(e.target).parents(".context-menu").length > 0) {
  2269. // Hide it
  2270. $(".context-menu").hide(100);
  2271. $(".highlightedBookmark").removeClass("highlightedBookmark")
  2272. }
  2273. });
  2274.  
  2275.  
  2276. // If the menu element is clicked
  2277. $(".context-menu li").click(function(){
  2278. // This is the triggered action name
  2279. switch($(this).attr("data-action")) {
  2280. // A case for each action. Your actions here
  2281. case "first": alert("first"); break;
  2282. case "second": alert("second"); break;
  2283. case "third": alert("third"); break;
  2284. }
  2285. // Hide it AFTER the action was triggered
  2286. $(".context-menu").hide(100);
  2287. });
  2288.  
  2289.  
  2290. function setupRealTimeLadderTable() {
  2291. if($("#RealTimeLadderTable").length == 0) {
  2292. $(".SideColumn").append('<table class="dataTable" cellspacing="0" width="100%" id="RealTimeLadderTable"><thead><tr><td>Real-Time Ladder</td></tr></thead><tbody><tr><td>Nobody is playing in the real-time ladder.<a href="/LadderSeason?ID=3">Ladder Page</a></td></tr> </tbody></table>')
  2293. }
  2294. if( $(".extendedRTLadderRow").length == 0) {
  2295. createSelector(".extendedRTLadderRow .rtBox", "width: calc(100%/2);");
  2296. createSelector(".extendedRTLadderRow span", "");
  2297. createSelector(".rtLeft", "float:left");
  2298. createSelector(".rtRight", "float:Right");
  2299. createSelector(".rtRight a", " padding: 10px 30px;position: absolute;margin-left: -75px;");
  2300. createSelector(".newGamesRT", "display:block");
  2301. createSelector(".rtLabelBig", "font-size: 18px; margin: 5px");
  2302. }
  2303. $(".extendedRTLadderRow").remove()
  2304. $("#RealTimeLadderTable tbody").append('<tr class="extendedRTLadderRow"><td colspan="2"><div class="rtLeft rtBox"><span class="newGamesRT">New Games in<br></span><div class="rtLabelBig">' + getRealTimeLadderTimerHTML() + '<a href="https://www.warlight.net/LadderJoin?Ladder=RealTime" class="rtLabelBig">Join!</a></div></td></tr>')
  2305. $("[href='/LadderSeason?ID=3'").text("Ladder Page")
  2306. setRTLadderTime()
  2307. }
  2308.  
  2309. function setupRealTimeLadderPageTimer() {
  2310. $("#LadderJoinBtn").after("<div>New Games in " + getRealTimeLadderTimerHTML() +"</div>")
  2311. $("#LeaveLadderBtn").after("<div>New Games in " + getRealTimeLadderTimerHTML() +"</div>")
  2312. setRTLadderTime()
  2313. }
  2314.  
  2315. function getRealTimeLadderTimerHTML() {
  2316. return '<span class="rtMin">00</span>:<span class="rtSec">00</span></div></div><div class="rtRight rtBox">'
  2317. }
  2318.  
  2319.  
  2320. function setRTLadderTime() {
  2321. var date = new Date()
  2322. date.setMinutes(Math.ceil((new Date().getMinutes() + date.getSeconds() / 60) / 5) * 5)
  2323. date.setSeconds(0)
  2324. var diff = (date - new Date()) / 1000
  2325. var min = Math.floor(diff / 60) % 60
  2326. diff -= min * 60
  2327. var sec = diff % 60
  2328. $(".rtMin").text(padLeft(min))
  2329. $(".rtSec").text(padLeft(sec))
  2330. }
  2331.  
  2332. function padLeft(str) {
  2333. str = Math.round(str)
  2334. len = 2
  2335. symbol = '0'
  2336. while(String(str).length < len) {
  2337. str = symbol + str;
  2338. }
  2339. return str
  2340. }
  2341.  
  2342.  
  2343.  
  2344. function setupClotTable() {
  2345. if($("#ClotTable").length == 0) {
  2346. $(".SideColumn").append('<table class="dataTable" cellspacing="0" width="100%" id="ClotTable" style="text-align: left"><thead><tr><td style="text-align: center">CLOTs</td></tr></thead><tbody></tbody></table>')
  2347. }
  2348. parseClotTable()
  2349. loadClots()
  2350. createSelector(".clotLabel", "display: inline-block; width: 70px")
  2351. createSelector(".clotPlayers", "display: inline-block; margin-left: 5px; color:gray; ")
  2352. }
  2353.  
  2354. function setupLadderClotOverview() {
  2355. $("h1").text($("h1").text() + " & CLOTs")
  2356. var clotInfo = getClots()
  2357. if(!clotInfo) {
  2358. return
  2359. }
  2360. console.log(clotInfo)
  2361. var clots = clotInfo
  2362. console.log(clots)
  2363. var ladders = clots['ladders']
  2364. var md = ""
  2365. var rt = ""
  2366. var counter = 0
  2367. $.each(ladders, function (key, val) {
  2368. if (val.type == "realtime") {
  2369. rt += "<li><big><a target='_blank' href=" + val.url + ">" + val.name + "</a> using Real-Time boot times</big></li><br><br>"
  2370. counter++
  2371. } else if (val.type == "multiday") {
  2372. md += "<li><big><a target='_blank' href = " + val.url + ">" + val.name + "</a> using Multi-Day boot times</big></li><br><br>"
  2373. counter++
  2374. }
  2375. })
  2376. $("#MainSiteContent > div").append("Warlight currently has " + toWords(counter) + " <a href='https://www.warlight.net/wiki/CLOT'>CLOTs</a><br><br>")
  2377. $("#MainSiteContent > div").append("<ul id='clotInfo'></ul>")
  2378. $("#clotInfo").append(rt)
  2379. $("#clotInfo").append(md)
  2380. }
  2381.  
  2382. function parseClotTable() {
  2383. try {
  2384. var clotInfo = getClots()
  2385. if(!clotInfo) {
  2386. return
  2387. }
  2388. var ladders = clots['ladders']
  2389. var md = ""
  2390. var rt = ""
  2391. $.each(ladders, function (key, val) {
  2392. if (val.type == "realtime") {
  2393. rt += "<tr><td><a target='_blank' href=" + val.url + ">" + val.name + " (RT)</a> <span class='clotPlayers'>" + val.players + " Players joined</span></td></tr>"
  2394. } else if (val.type == "multiday") {
  2395. md += "<tr><td><a target='_blank' href = " + val.url + ">" + val.name + " (MD)</a><span class='clotPlayers'>" + val.players + " Players joined</span></td></tr>"
  2396. }
  2397. })
  2398. $("#ClotTable tbody tr").remove()
  2399. $("#ClotTable tbody").append(md)
  2400. $("#ClotTable tbody").append(rt)
  2401. $(window).trigger('resize');
  2402. } catch (e) {
  2403. console.log("Error reading CLOTs")
  2404. console.log(e.message)
  2405. hideTable("#ClotTable")
  2406. }
  2407. }
  2408. function getClots() {
  2409. try {
  2410. return clots = $.parseJSON(localStorage.getItem('clots'))
  2411. } catch (e) {
  2412. console.log("Error reading CLOTs")
  2413. console.log(e.message)
  2414. hideTable("#ClotTable")
  2415. }
  2416. return undefined
  2417. }
  2418.  
  2419. function loadClots() {
  2420. $.ajax({
  2421. type: 'GET',
  2422. //url: 'https://php-psenough.rhcloud.com/hub/list.php',
  2423. //url: 'https://w115l144.hoststar.ch/test.php',
  2424. url: 'https://php-psenough.rhcloud.com/hub/list_jsonp.php',
  2425. dataType: 'jsonp',
  2426. crossDomain: true,
  2427. }).done(function(response){
  2428. try {
  2429. var json = response.data
  2430. localStorage.setItem('clots', JSON.stringify(json));
  2431. parseClotTable()
  2432. var datetime = json.datetime
  2433. console.log("clot update " + datetime)
  2434. } catch (e) {
  2435. console.log("Error parsing CLOTs")
  2436. console.log(e)
  2437. }
  2438. }).fail(function(e){
  2439. console.log("Error loading CLOTs")
  2440. console.log(e);
  2441. });
  2442. }
  2443.  
  2444.  
  2445. function isJson(str) {
  2446. try {
  2447. JSON.parse(str);
  2448. } catch (e) {
  2449. return false;
  2450. }
  2451. return true;
  2452. }
  2453.  
  2454.  
  2455. function setupRightColumn(isInit) {
  2456. if(isInit) {
  2457. createSelector(".SideColumn > table", "margin-bottom: 17px;")
  2458. }
  2459. //Bookmarks
  2460. if(isInit) {
  2461. setupBookmarkTable()
  2462. } else {
  2463. refreshBookmarks()
  2464. }
  2465. //Tournament
  2466. // #MyTournamentsTable
  2467. //Clots
  2468. setupClotTable()
  2469. //RT Ladder
  2470. setupRealTimeLadderTable()
  2471. //Map of the Week
  2472. //Forum Posts
  2473. hideBlacklistedThreads()
  2474. //Blog Posts
  2475. //Coin Leaderboard
  2476. sortRightColumnTables()
  2477. if(isInit && isEnabled('scrollGames')) {
  2478. setupFixedTitlesInSideColumn()
  2479. }
  2480. }
  2481.  
  2482. function sortRightColumnTables() {
  2483. var sideColumn = $(".SideColumn")
  2484. $.each(getSortTables(), function(key, table) {
  2485. if(table.hidden == true) {
  2486. hideTable(table.id)
  2487. } else {
  2488. var table = $(table.id)
  2489. if(table.prev().hasClass("followWrap")) {
  2490. var wrap = table.prev().remove()
  2491. sideColumn.append(wrap)
  2492. }
  2493. table = table.detach()
  2494. sideColumn.append(table)
  2495. }
  2496. })
  2497. $(".SideColumn > br").remove()
  2498. }
  2499.  
  2500. function toWords(num) {
  2501. if(num == 1) {
  2502. return "one"
  2503. } else if(num == 2) {
  2504. return "two"
  2505. } else if(num == 3) {
  2506. return "three"
  2507. } else if(num == 4) {
  2508. return "four"
  2509. } else if(num == 5) {
  2510. return "five"
  2511. } else if(num == 6) {
  2512. return "six"
  2513. } else if(num == 7) {
  2514. return "seven"
  2515. } else if(num == 8) {
  2516. return "eight"
  2517. } else if(num == 9) {
  2518. return "nine"
  2519. } else if(num == 10) {
  2520. return "ten"
  2521. } else if(num == 0) {
  2522. return "zero"
  2523. }
  2524. }
  2525.  
  2526. function hideTable(seletor) {
  2527. if( $(seletor).prev().hasClass("followWrap")) {
  2528. $(seletor).prev().remove()
  2529. }
  2530. $(seletor).remove()
  2531. }
  2532.  
  2533. window.findMostCommonGames = function() {
  2534. $("#foundPlayers").empty()
  2535. warlight.shared.viewmodels.WaitDialogVM.Start("Searching Players...")
  2536. warlight.shared.messages.Message.GetFriendsAsync(null, warlight.shared.viewmodels.SignIn.Auth, null, function (b, c, players) {
  2537. if (null != c) throw c;
  2538. var myId = warlight.shared.viewmodels.SignIn.get_CurrentPlayer().ID;
  2539. warlight.shared.SharedUtility.RemoveWhere(players, function (p) {
  2540. return p.PlayerID == myId
  2541. });
  2542. var topPlayers = [];
  2543. var limit = -1;
  2544. for (var i = 0; i < players.length; i++) {
  2545. var player = players[i];
  2546. if(player.TimesPlayedWithYou > limit || topPlayers.length < 10) {
  2547. topPlayers.push(player)
  2548. topPlayers.sort(function (p1, p2) {
  2549. return p2.TimesPlayedWithYou - p1.TimesPlayedWithYou
  2550. });
  2551. topPlayers = topPlayers.slice(0, 10);
  2552. limit = topPlayers.slice(-1)[0].TimesPlayedWithYou
  2553. }
  2554. }
  2555. warlight.shared.viewmodels.WaitDialogVM.Stop()
  2556. parseFoundFriendPlayers(topPlayers)
  2557. })
  2558. }
  2559.  
  2560. function setupPlayerSearch() {
  2561. $("body").append("<div class='popup popup600 playersearch-show' style='display: none'><div class='head'>Search Player <img class='close-popup-img' src='" + IMAGES.CROSS + "' height='25' width='25'></div><input placeholder='Player Name' id='playerSearchQuery'><button id='searchPlayerBtn'>Search</button><div class='playerSearchTypeSelect'><label for='playerSearchFriend'>Friends</label><input type='radio' id='playerSearchFriend' name='playerSearchType' value='playerSearchFriend' checked><label for='playerSearchGlobal'>All Players</label><input type='radio' id='playerSearchGlobal' name='playerSearchType' value='playerSearchGlobal'></div><button id='findPlayerExtra'>More ▼</button><div id='foundPlayers'></div></div>");
  2562. $("#SubTabRow").append('<td nowrap="nowrap" id="searchPlayerLink" data-subtabcell="Search Player" class="SubTabCell"><a>Search Player</a></td>');
  2563. $("#searchPlayerLink").on("click", function() {
  2564. $(".playersearch-show").fadeIn();
  2565. $(".overlay").fadeIn();
  2566. $("#playerSearchQuery").val("")
  2567. $("#playerSearchQuery").focus()
  2568. })
  2569. $("#searchPlayerBtn").on("click", function() {
  2570. searchPlayer()
  2571. })
  2572. $("#findPlayerExtra").on("click", function(event) {
  2573. $(".playersearch-context").finish().toggle(100).
  2574. css({
  2575. top: event.pageY + "px",
  2576. left: event.pageX + "px"
  2577. });
  2578. })
  2579. $('#playerSearchQuery').keyup(function(e){
  2580. if(e.keyCode == 13) {
  2581. searchPlayer()
  2582. }
  2583. });
  2584. createSelector(".SubTabCell", "cursor: pointer")
  2585. createSelector(".playersearch-show button", "padding: 5px;float: left; margin: 10px")
  2586. createSelector("#playerSearchQuery", "width: 200px; padding: 5px; margin: 10px;float: left")
  2587. createSelector(".foundPlayer", "display: block; height: 25px; padding: 2px; clear:both")
  2588. createSelector(".foundPlayer a", "line-height: 25px; float: left")
  2589. createSelector(".foundPlayer img", "height: 15px; display: block; float: left; margin: 5px")
  2590. createSelector("#foundPlayers span", "color: gray; padding: 0 5px; line-height: 25px")
  2591. createSelector("#foundPlayers > span", "display: block; clear: both; margin: 0px; padding: 10px 0")
  2592. createSelector(".playerSearchName", "float: left")
  2593. createSelector(".playerSearchTypeSelect", "float: left; width: 30%")
  2594. createSelector(".playerSearchTypeSelect label", "color: gray; font-size: 13px; margin: 2px")
  2595. }
  2596.  
  2597. function searchPlayer() {
  2598. $("#foundPlayers").empty()
  2599. var query = $("#playerSearchQuery").val().toLowerCase()
  2600. if($('#playerSearchFriend').is(':checked')) {
  2601. warlight.shared.viewmodels.WaitDialogVM.Start("Searching Players...")
  2602. warlight.shared.messages.Message.GetFriendsAsync(null, warlight.shared.viewmodels.SignIn.Auth, null, function (b, c, players) {
  2603. if (null != c) throw c;
  2604. var myId = warlight.shared.viewmodels.SignIn.get_CurrentPlayer().ID;
  2605. warlight.shared.SharedUtility.RemoveWhere(players, function (p) {
  2606. return p.Name.toLowerCase().indexOf(query) < 0 || p.PlayerID == myId
  2607. });
  2608. warlight.shared.viewmodels.WaitDialogVM.Stop()
  2609. parseFoundFriendPlayers(players)
  2610. })
  2611. } else {
  2612. if(query.length < 3) {
  2613. warlight.shared.viewmodels.AlertVM.DoPopup("Please enter at least 3 characters to search for");
  2614. return
  2615. }
  2616. warlight.shared.viewmodels.main.manageplayers.ManagePlayersVM.SearchPlayers(query, function (players) {
  2617. players = players.Results
  2618. if(players.length >= 25) {
  2619. $("#foundPlayers").append("<span>This query found more than 25 results. Only the first 25 results are shown below.</span>")
  2620. }
  2621. parseFoundGlobalPlayers(players)
  2622. $("#playerSearchQuery").focus()
  2623. $("#playerSearchQuery").select()
  2624. })
  2625. }
  2626. }
  2627.  
  2628. function parseFoundFriendPlayers(players) {
  2629. if(!players || players.length == 0) {
  2630. $("#foundPlayers").append("<span>No Players found.</span>");
  2631. return;
  2632. }
  2633. players.sort(function (p1, p2) {
  2634. return (p2.TimesPlayedWithYou - p1.TimesPlayedWithYou != 0) ? p2.TimesPlayedWithYou - p1.TimesPlayedWithYou : p1.Level > p2.Level
  2635. });
  2636. for (var i = 0; i < players.length; i++) {
  2637. var player = players[i];
  2638. var id = String(player.ProfileToken).substr(0, 2) + String(player.PlayerID) + String(player.ProfileToken).substr(2, 2);
  2639. var nameLink = '<a href="/Profile?p=' + id + '">' + player.Name + '</a>'
  2640. var clan = player.ClanOpt != null ? '<a href="https://www.warlight.net/Clans/?ID=' + player.ClanOpt.ClanID + '"><img class="playerSearchClan" src="https://d32kaghj56y4ei.cloudfront.net/Data/Clans/' + player.ClanOpt.ClanID + '/Icon/' + player.ClanOpt.IconIncre + '.png"></a>' : "";
  2641. var member = player.IsMember ? '<img class="playerSearchMember" src="https://d2wcw7vp66n8b3.cloudfront.net/Images/MemberIcon.png">' : "";
  2642. var description = '<div class="playerSearchName">' + nameLink + member + "<span>(Level " + player.Level + ", " + player.TimesPlayedWithYou + " common games)</span></div>";
  2643. $("#foundPlayers").append('<div class="foundPlayer">' + clan + description + '</div>')
  2644. }
  2645. }
  2646.  
  2647. function parseFoundGlobalPlayers(players) {
  2648. if(!players || players.length == 0) {
  2649. $("#foundPlayers").append("<span>No Players found.</span>");
  2650. return;
  2651. }
  2652. players.sort(function(p1, p2){
  2653. return (p2.Level - p1.Level != 0) ? p2.Level - p1.Level : p1.Name > p2.Name
  2654. });
  2655.  
  2656. for (var i = 0; i < players.length; i++) {
  2657. var player = players[i];
  2658. var id = String(player.ProfileToken).substr(0, 2) + String(player.PlayerID) + String(player.ProfileToken).substr(2, 2);
  2659. var nameLink = '<a href="/Profile?p=' + id + '">' + player.Name + '</a>'
  2660. var clan = player.ClanOpt != null ? '<a href="https://www.warlight.net/Clans/?ID=' + player.ClanOpt.ClanID + '"><img class="playerSearchClan" src="https://d32kaghj56y4ei.cloudfront.net/Data/Clans/' + player.ClanOpt.ClanID + '/Icon/' + player.ClanOpt.IconIncre + '.png"></a>' : "";
  2661. var member = player.IsMember ? '<img class="playerSearchMember" src="https://d2wcw7vp66n8b3.cloudfront.net/Images/MemberIcon.png">' : "";
  2662. var name = '<div class="playerSearchName">' + nameLink + "<span>(" + player.Level + ")</span></div>";
  2663. $("#foundPlayers").append('<div class="foundPlayer">' + clan + name + member + '</div>')
  2664. }
  2665. }
  2666.  
  2667. /**************************************
  2668.  
  2669. RANDOMIZED BONUSES
  2670.  
  2671. **************************************/
  2672.  
  2673. function setupRandomizedBonus() {
  2674. /*console.log("loaded random bonus")
  2675.  
  2676. var selectField = document.createElement("select")
  2677. selectField.id = "templateSelect"
  2678. var templates = [{id: 12345, text: "Strategic Earth"}, {id: 54345, text: "Strategic Earth 2"}]
  2679.  
  2680. for(var i = 0; i < templates.length; i++) {
  2681. var option = new Option();
  2682. option.value = templates[i].id;
  2683. option.text = templates[i].text;
  2684. selectField.options.add(option);
  2685. }
  2686.  
  2687. $("#gameId").before(selectField)
  2688.  
  2689. $("#templateSelect").on("change", function() {
  2690. $("#gameId").val(this.value)
  2691. })*/
  2692. }
  2693.  
  2694. // Compute Player Ids
  2695.  
  2696. var yourId;
  2697. var opponentId;
  2698. var gameName;
  2699. if(pageIsProfile() && isMember()) {
  2700. var idRegex = /p=(\d+)/;
  2701. var yourProfileLink = document.evaluate('/html/body/div[1]/span/div/a[2]',
  2702. document, null, XPathResult.ANY_TYPE, null).iterateNext();
  2703. yourId = yourProfileLink.href.match(idRegex)[1];
  2704. opponentId = getParameterByName("p");
  2705. if (yourId == opponentId) {
  2706. opponentId = "OpenSeat";
  2707. }
  2708.  
  2709. // Add text box and button
  2710. addRandomizedControls();
  2711. }
  2712.  
  2713. function addRandomizedControls() {
  2714. /// <summary>
  2715. /// Add a text box(for sample game Id) and a button to create randomized
  2716. /// game.
  2717. /// </summary>
  2718. /// <param name="levelElement" type="Element">
  2719. /// The parent element if text box and button.
  2720. /// </param>
  2721.  
  2722. $("#FeedbackMsg").after("<div class='randomGameContainer profileBox'><h3>Randomized Bonuses Game</h3></div>")
  2723. var br = document.createElement('br');
  2724. $(".randomGameContainer").append('<label for="gameName">Game Name:</label><input id="gameName" type="text" placeholder="Game Name" value="Game - Randomized Bonuses"><br>')
  2725. $(".randomGameContainer").append('<label for="gameId">Game ID:</label><input id="gameId" type="text" placeholder="Game ID" value="">')
  2726. $(".randomGameContainer").append('<button id="createGame">Create Game</button>')
  2727. $("#createGame").on("click", function() {
  2728. $("#createGame").attr('disabled', true);
  2729. $("#createGame").text('...processing...');
  2730.  
  2731. setTimeout(function(){
  2732. $("#createGame").attr('disabled', false);
  2733. $("#createGame").text('Create Game');
  2734. }, 1000);
  2735. extractGameSettings();
  2736. })
  2737. $(".randomGameContainer").append('<button id="bookmarkRandomBonus"><img src="' + IMAGES.BOOKMARK + '"></button>')
  2738. $("#bookmarkRandomBonus").on("click", function() {
  2739. var templateId = getSampleGameId()
  2740. if(isNaN(templateId)) {
  2741. warlight.shared.viewmodels.AlertVM.DoPopup("Please enter a valid Game ID");
  2742. return;
  2743. }
  2744. $("#bookmarkURL").val("javascript:randomBonusGame('" + $("#gameName").val().replace("'", "`").replace('"', "`") + "', '" + templateId + "', '" + yourId + "', '" + opponentId + "')");
  2745. $("#bookmarkName").val($("#gameName").val());
  2746. showAddBookmark();
  2747. })
  2748.  
  2749.  
  2750. var saveButton = document.createElement("input");
  2751. saveButton.setAttribute("type", "button");
  2752. saveButton.setAttribute("value", "<img src='" + IMAGES.SAVE + "'>");
  2753. saveButton.onclick = function () {
  2754. var oldValue = saveButton.value;
  2755. saveButton.setAttribute('disabled', true);
  2756. saveButton.value = '...saving...';
  2757.  
  2758. setTimeout(function(){
  2759. saveButton.value = oldValue;
  2760. saveButton.removeAttribute('disabled');
  2761. }, 500);
  2762. //extractGameSettings();
  2763. };
  2764. var bookmarkButton = document.createElement("input");
  2765. bookmarkButton.setAttribute("type", "button");
  2766. bookmarkButton.setAttribute("value", "Bookmark");
  2767. bookmarkButton.onclick = function () {
  2768. var oldValue = bookmarkButton.value;
  2769. bookmarkButton.setAttribute('disabled', true);
  2770. bookmarkButton.value = '...saving...';
  2771.  
  2772. setTimeout(function(){
  2773. bookmarkButton.value = oldValue;
  2774. bookmarkButton.removeAttribute('disabled');
  2775. }, 500);
  2776. //extractGameSettings();
  2777. };
  2778. createSelector(".randomGameContainer button", "min-width: 10%; margin: 3px 6px 3px 0")
  2779. createSelector(".randomGameContainer button img", "height: 12px")
  2780. createSelector(".randomGameContainer input[type='text']", "margin: 3px")
  2781. createSelector(".randomGameContainer label", "width: 100px; display: inline-block; color: #858585")
  2782. }
  2783.  
  2784. function getSampleGameId() {
  2785. /// <summary>
  2786. /// Gets the sample game Id and checks if it is a number.
  2787. /// </summary>
  2788. /// <returns type="number">Game Id.</returns>
  2789. var gameIdElement = document.getElementById("gameId");
  2790. if (gameIdElement !== undefined) {
  2791. return parseInt(gameIdElement.value, 10);
  2792. }
  2793. }
  2794.  
  2795. function extractGameSettings(gameId) {
  2796. /// <summary>
  2797. /// Extract game settings from the sample game using GameFeed API.
  2798. /// </summary>
  2799.  
  2800. var sampleGameId = gameId || getSampleGameId();
  2801. console.log(sampleGameId)
  2802. if (isNaN(sampleGameId)) {
  2803. alert("Invalid GameId");
  2804. } else {
  2805. doAsyncRequest("POST",
  2806. 'https://www.warlight.net/API/GameFeed?GameID=' +
  2807. sampleGameId.toString() + '&GetHistory=true', {},
  2808. "GameFeed");
  2809. }
  2810. }
  2811.  
  2812. function setupRandomizedGame(response) {
  2813. /// <summary>
  2814. /// From the GameFeed API response, randomize bonuses and create a game
  2815. /// using the template.
  2816. /// </summary>
  2817. /// <param name="response" type="string">
  2818. /// The GameFeed API response for the provided sample game.
  2819. /// </param>
  2820.  
  2821. var obj = JSON.parse(response);
  2822. if (obj != undefined) {
  2823. var templateId = obj.templateID;
  2824. var bonuses = [];
  2825. if(obj && obj.map) {
  2826. for (var i = 0; i < obj.map.bonuses.length; i++) {
  2827. var bonusObj = obj.map.bonuses[i];
  2828. if (bonusObj.value != 0) {
  2829. var bonus = [];
  2830. var originalBonusValue = parseInt(bonusObj.value, 10);
  2831.  
  2832. // set the bonus value to (original-1, original+1)
  2833. bonus.push(bonusObj.name);
  2834. bonus.push(originalBonusValue - 1);
  2835. bonus.push(originalBonusValue + 1);
  2836. bonuses.push(bonus);
  2837. }
  2838. }
  2839. } else {
  2840. 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")
  2841. warlight.shared.viewmodels.WaitDialogVM.Stop();
  2842. return
  2843. }
  2844. }
  2845. console.log(yourId, " ", opponentId)
  2846. createGame(templateId, bonuses, yourId, opponentId);
  2847. }
  2848.  
  2849. window.randomBonusGame = function(name, templateId, yID, oID) {
  2850. if(isMember()) {
  2851. warlight.shared.viewmodels.WaitDialogVM.Start("Creating Game...")
  2852. yourId = yID;
  2853. opponentId = oID;
  2854. gameName = name;
  2855. extractGameSettings(templateId)
  2856. } else {
  2857. warlight.shared.viewmodels.AlertVM.DoPopup("You need to be a Warlight Member to use this Feature");
  2858. }
  2859. }
  2860. function createGame(templateId, bonuses, yourId, opponentId) {
  2861. /// <summary>
  2862. /// Create a game on Warlight between the two players on given settings.
  2863. /// </summary>
  2864. /// <param name="templateId" type="number">
  2865. /// The game template Id.
  2866. /// </param>
  2867. /// <param name="bonuses" type="array">
  2868. /// All bonuses on the map and the range of values they can take.
  2869. /// </param>
  2870.  
  2871. var template = templateId;
  2872. var postDataObject = {
  2873. "gameName": gameName || $("#gameName").val() || "Randomized bonuses game",
  2874. "personalMessage": "Check bonuses carefully as they may have been altered",
  2875. "templateID": template,
  2876. "players": [{
  2877. "token": yourId,
  2878. "team": "None"
  2879. }, {
  2880. "token": opponentId,
  2881. "team": "None"
  2882. }],
  2883. "overriddenBonuses": []
  2884. };
  2885. if (bonuses !== null) {
  2886. for (var i = 0; i < bonuses.length; i++) {
  2887. var bonusName = bonuses[i][0];
  2888. var min = bonuses[i][1];
  2889. var max = bonuses[i][2];
  2890. postDataObject.overriddenBonuses.push({
  2891. "bonusName": bonusName,
  2892. value: getRandomInt(min, max) // Randomize the bonus
  2893. });
  2894. }
  2895. }
  2896. var response = doAsyncRequest("POST",
  2897. 'https://www.warlight.net/API/CreateGame', JSON.stringify(
  2898. postDataObject), "CreateGame");
  2899. }
  2900.  
  2901. function getRandomInt(min, max) {
  2902. /// <summary>
  2903. /// Pick a random number in the interval (min, max)
  2904. /// </summary>
  2905. /// <param name="min" type="number">
  2906. /// lower bound of number
  2907. /// </param>
  2908. /// <param name="max" type="number">
  2909. /// upper bound of number
  2910. /// </param>
  2911. /// <returns type="number">
  2912. /// Random number in the interval
  2913. /// </returns>
  2914.  
  2915. return Math.floor(Math.random() * (max - min + 1)) + min;
  2916. }
  2917.  
  2918. function doAsyncRequest(method, url, data, api) {
  2919. /// <summary>
  2920. /// Perform an asynchronous request to create a game on Warlight.
  2921. /// </summary>
  2922. /// <param name="method" type="string">
  2923. /// GET/POST
  2924. /// </param>
  2925. /// <param name="url" type="string">
  2926. /// The request url.
  2927. /// </param>
  2928. /// <param name="data" type="dictionary">
  2929. /// Request parameters
  2930. /// </param>
  2931. /// <param name="api" type="string">
  2932. /// Warlight api type
  2933. /// </param>
  2934. console.log(data)
  2935. var xhr = new XMLHttpRequest();
  2936. xhr.onreadystatechange = function() {
  2937. //if (xhr.readyState === 4){
  2938. if (xhr.readyState != 4) return;
  2939. if (api === "GameFeed") {
  2940. setupRandomizedGame(xhr.responseText);
  2941. } else if (api === "CreateGame") {
  2942. var obj = JSON.parse(xhr.responseText);
  2943. if (obj.gameID !== undefined) {
  2944. if(pageIsDashboard()) {
  2945. refreshMyGames()
  2946. warlight.shared.viewmodels.WaitDialogVM.Stop();
  2947. } else {
  2948. window.location.href = "https://www.warlight.net/MultiPlayer?GameID=" + obj.gameID
  2949. }
  2950. } else if (obj.error !== undefined) {
  2951. alert("Cannot create game. Warlight says: " +
  2952. obj.error);
  2953. warlight.shared.viewmodels.WaitDialogVM.Stop();
  2954. }
  2955. }
  2956. };
  2957.  
  2958. xhr.open(method, url, true);
  2959. xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  2960. xhr.send(data);
  2961. }
  2962.  
  2963. function setIsMember() {
  2964. if (typeof warlight != 'undefined') {
  2965. window.setTimeout(function() {
  2966. localStorage.setItem("isMember", warlight.shared.viewmodels.SignIn.get_CurrentPlayer().IsMember)
  2967. }, 1000)
  2968. }
  2969. }
  2970.  
  2971. function isMember() {
  2972. var isMember = localStorage.getItem("isMember")
  2973. if(isMember != undefined) {
  2974. return isMember
  2975. } else {
  2976. $("#FeedbackMsg").after("<div class='profileBox'>Please visit the <a href='https://www.warlight.net/MultiPlayer/'>Dashboard</a> once to reconfigure the Userscript.</div>")
  2977. return false;
  2978. }
  2979. }
  2980.  
  2981. function getParameterByName(name, url) {
  2982. url = url || location.search
  2983. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  2984. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  2985. results = regex.exec(url);
  2986. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  2987. }
  2988.  
  2989. /**************************************
  2990.  
  2991. SNOWFALL JQUERY PLUGIN
  2992.  
  2993. **************************************/
  2994.  
  2995. if (!Date.now)
  2996. Date.now = function() { return new Date().getTime(); };
  2997.  
  2998. (function() {
  2999. 'use strict';
  3000.  
  3001. var vendors = ['webkit', 'moz'];
  3002. for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {
  3003. var vp = vendors[i];
  3004. window.requestAnimationFrame = window[vp+'RequestAnimationFrame'];
  3005. window.cancelAnimationFrame = (window[vp+'CancelAnimationFrame']
  3006. || window[vp+'CancelRequestAnimationFrame']);
  3007. }
  3008. if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) // iOS6 is buggy
  3009. || !window.requestAnimationFrame || !window.cancelAnimationFrame) {
  3010. var lastTime = 0;
  3011. window.requestAnimationFrame = function(callback) {
  3012. var now = Date.now();
  3013. var nextTime = Math.max(lastTime + 16, now);
  3014. return setTimeout(function() { callback(lastTime = nextTime); },
  3015. nextTime - now);
  3016. };
  3017. window.cancelAnimationFrame = clearTimeout;
  3018. }
  3019. }());
  3020.  
  3021. $(document).ready(function() {
  3022. (function(){
  3023. $.snowfall = function(element, options){
  3024. var flakes = [],
  3025. defaults = {
  3026. flakeCount : 50,
  3027. flakeColor : '#ffffff',
  3028. flakePosition: 'absolute',
  3029. flakeIndex: 999999,
  3030. minSize : 1,
  3031. maxSize : 2,
  3032. minSpeed : 1,
  3033. maxSpeed : 5,
  3034. round : false,
  3035. shadow : false,
  3036. collection : false,
  3037. collectionHeight : 40,
  3038. deviceorientation : false
  3039. },
  3040. options = $.extend(defaults, options),
  3041. random = function random(min, max){
  3042. return Math.round(min + Math.random()*(max-min));
  3043. };
  3044.  
  3045. $(element).data("snowfall", this);
  3046.  
  3047. // Snow flake object
  3048. function Flake(_x, _y, _size, _speed){
  3049. // Flake properties
  3050. this.x = _x;
  3051. this.y = _y;
  3052. this.size = _size;
  3053. this.speed = _speed;
  3054. this.step = 0;
  3055. this.stepSize = random(1,10) / 100;
  3056.  
  3057. if(options.collection){
  3058. this.target = canvasCollection[random(0,canvasCollection.length-1)];
  3059. }
  3060.  
  3061. var flakeMarkup = null;
  3062.  
  3063. if(options.image){
  3064. flakeMarkup = document.createElement("img");
  3065. flakeMarkup.src = options.image;
  3066. }else{
  3067. flakeMarkup = document.createElement("div");
  3068. $(flakeMarkup).css({'background' : options.flakeColor});
  3069. }
  3070.  
  3071. $(flakeMarkup).attr({
  3072. 'class': 'snowfall-flakes',
  3073. }).css({
  3074. 'width' : this.size,
  3075. 'height' : this.size,
  3076. 'position' : options.flakePosition,
  3077. 'top' : this.y,
  3078. 'left' : this.x,
  3079. 'fontSize' : 0,
  3080. 'zIndex' : options.flakeIndex
  3081. });
  3082.  
  3083. if($(element).get(0).tagName === $(document).get(0).tagName){
  3084. $('body').append($(flakeMarkup));
  3085. element = $('body');
  3086. }else{
  3087. $(element).append($(flakeMarkup));
  3088. }
  3089.  
  3090. this.element = flakeMarkup;
  3091.  
  3092. // Update function, used to update the snow flakes, and checks current snowflake against bounds
  3093. this.update = function(){
  3094. this.y += this.speed;
  3095.  
  3096. if(this.y > (elHeight) - (this.size + 6)){
  3097. this.reset();
  3098. }
  3099.  
  3100. this.element.style.top = this.y + 'px';
  3101. this.element.style.left = this.x + 'px';
  3102.  
  3103. this.step += this.stepSize;
  3104.  
  3105. if (doRatio === false) {
  3106. this.x += Math.cos(this.step);
  3107. } else {
  3108. this.x += (doRatio + Math.cos(this.step));
  3109. }
  3110.  
  3111. // Pileup check
  3112. if(options.collection){
  3113. 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){
  3114. var ctx = this.target.element.getContext("2d"),
  3115. curX = this.x - this.target.x,
  3116. curY = this.y - this.target.y,
  3117. colData = this.target.colData;
  3118.  
  3119. if(colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] !== undefined || curY+this.speed+this.size > this.target.height){
  3120. if(curY+this.speed+this.size > this.target.height){
  3121. while(curY+this.speed+this.size > this.target.height && this.speed > 0){
  3122. this.speed *= .5;
  3123. }
  3124.  
  3125. ctx.fillStyle = "#fff";
  3126.  
  3127. if(colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] == undefined){
  3128. colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] = 1;
  3129. ctx.fillRect(curX, (curY)+this.speed+this.size, this.size, this.size);
  3130. }else{
  3131. colData[parseInt(curX)][parseInt(curY+this.speed)] = 1;
  3132. ctx.fillRect(curX, curY+this.speed, this.size, this.size);
  3133. }
  3134. this.reset();
  3135. }else{
  3136. // flow to the sides
  3137. this.speed = 1;
  3138. this.stepSize = 0;
  3139.  
  3140. if(parseInt(curX)+1 < this.target.width && colData[parseInt(curX)+1][parseInt(curY)+1] == undefined ){
  3141. // go left
  3142. this.x++;
  3143. }else if(parseInt(curX)-1 > 0 && colData[parseInt(curX)-1][parseInt(curY)+1] == undefined ){
  3144. // go right
  3145. this.x--;
  3146. }else{
  3147. //stop
  3148. ctx.fillStyle = "#fff";
  3149. ctx.fillRect(curX, curY, this.size, this.size);
  3150. colData[parseInt(curX)][parseInt(curY)] = 1;
  3151. this.reset();
  3152. }
  3153. }
  3154. }
  3155. }
  3156. }
  3157.  
  3158. if(this.x + this.size > (elWidth) - widthOffset || this.x < widthOffset){
  3159. this.reset();
  3160. }
  3161. }
  3162.  
  3163. // Resets the snowflake once it reaches one of the bounds set
  3164. this.reset = function(){
  3165. this.y = 0;
  3166. this.x = random(widthOffset, elWidth - widthOffset);
  3167. this.stepSize = random(1,10) / 100;
  3168. this.size = random((options.minSize * 100), (options.maxSize * 100)) / 100;
  3169. this.element.style.width = this.size + 'px';
  3170. this.element.style.height = this.size + 'px';
  3171. this.speed = random(options.minSpeed, options.maxSpeed);
  3172. }
  3173. }
  3174.  
  3175. // local vars
  3176. var i = 0,
  3177. elHeight = $(element).height(),
  3178. elWidth = $(element).width(),
  3179. widthOffset = 0,
  3180. snowTimeout = 0;
  3181.  
  3182. // Collection Piece ******************************
  3183. if(options.collection !== false){
  3184. var testElem = document.createElement('canvas');
  3185. if(!!(testElem.getContext && testElem.getContext('2d'))){
  3186. var canvasCollection = [],
  3187. elements = $(options.collection),
  3188. collectionHeight = options.collectionHeight;
  3189.  
  3190. for(var i =0; i < elements.length; i++){
  3191. var bounds = elements[i].getBoundingClientRect(),
  3192. $canvas = $('<canvas/>',
  3193. {
  3194. 'class' : 'snowfall-canvas'
  3195. }),
  3196. collisionData = [];
  3197.  
  3198. if(bounds.top-collectionHeight > 0){
  3199. $('body').append($canvas);
  3200.  
  3201. $canvas.css({
  3202. 'position' : options.flakePosition,
  3203. 'left' : bounds.left + 'px',
  3204. 'top' : bounds.top-collectionHeight + 'px'
  3205. })
  3206. .prop({
  3207. width: bounds.width,
  3208. height: collectionHeight
  3209. });
  3210.  
  3211. for(var w = 0; w < bounds.width; w++){
  3212. collisionData[w] = [];
  3213. }
  3214.  
  3215. canvasCollection.push({
  3216. element : $canvas.get(0),
  3217. x : bounds.left,
  3218. y : bounds.top-collectionHeight,
  3219. width : bounds.width,
  3220. height: collectionHeight,
  3221. colData : collisionData
  3222. });
  3223. }
  3224. }
  3225. }else{
  3226. // Canvas element isnt supported
  3227. options.collection = false;
  3228. }
  3229. }
  3230. // ************************************************
  3231.  
  3232. // This will reduce the horizontal scroll bar from displaying, when the effect is applied to the whole page
  3233. if($(element).get(0).tagName === $(document).get(0).tagName){
  3234. widthOffset = 25;
  3235. }
  3236.  
  3237. // Bind the Window resize event so we can get the innerHeight again
  3238. $(window).bind("resize", function(){
  3239. elHeight = $(element)[0].clientHeight;
  3240. elWidth = $(element)[0].offsetWidth;
  3241. });
  3242.  
  3243.  
  3244. // initialize the flakes
  3245. for(i = 0; i < options.flakeCount; i+=1){
  3246. flakes.push(new Flake(random(widthOffset,elWidth - widthOffset), random(0, elHeight), random((options.minSize * 100), (options.maxSize * 100)) / 100, random(options.minSpeed, options.maxSpeed)));
  3247. }
  3248.  
  3249. // This adds the style to make the snowflakes round via border radius property
  3250. if(options.round){
  3251. $('.snowfall-flakes').css({'-moz-border-radius' : options.maxSize, '-webkit-border-radius' : options.maxSize, 'border-radius' : options.maxSize});
  3252. }
  3253.  
  3254. // This adds shadows just below the snowflake so they pop a bit on lighter colored web pages
  3255. if(options.shadow){
  3256. $('.snowfall-flakes').css({'-moz-box-shadow' : '1px 1px 1px #555', '-webkit-box-shadow' : '1px 1px 1px #555', 'box-shadow' : '1px 1px 1px #555'});
  3257. }
  3258.  
  3259. // On newer Macbooks Snowflakes will fall based on deviceorientation
  3260. var doRatio = false;
  3261. if (options.deviceorientation) {
  3262. $(window).bind('deviceorientation', function(event) {
  3263. doRatio = event.originalEvent.gamma * 0.1;
  3264. });
  3265. }
  3266.  
  3267. // this controls flow of the updating snow
  3268. function snow(){
  3269. for( i = 0; i < flakes.length; i += 1){
  3270. flakes[i].update();
  3271. }
  3272.  
  3273. snowTimeout = requestAnimationFrame(function(){snow()});
  3274. }
  3275.  
  3276. snow();
  3277.  
  3278. // clears the snowflakes
  3279. this.clear = function(){
  3280. $('.snowfall-canvas').remove();
  3281. $(element).children('.snowfall-flakes').remove();
  3282. cancelAnimationFrame(snowTimeout);
  3283. }
  3284. };
  3285.  
  3286. // Initialize the options and the plugin
  3287. $.fn.snowfall = function(options){
  3288. if(typeof(options) == "object" || options == undefined){
  3289. return this.each(function(i){
  3290. (new $.snowfall(this, options));
  3291. });
  3292. }else if (typeof(options) == "string") {
  3293. return this.each(function(i){
  3294. var snow = $(this).data('snowfall');
  3295. if(snow){
  3296. snow.clear();
  3297. }
  3298. });
  3299. }
  3300. };
  3301. })(jQuery);
  3302. if(!isEnabled('disableSnow')) {
  3303. var flakes;
  3304. if(isEnabled('snowLight')) {
  3305. flakes = pageIsGame() ? 40 : 125
  3306. } else {
  3307. flakes = pageIsGame() ? 75 : 225
  3308. }
  3309. $(document).snowfall({flakeCount : flakes});
  3310. }
  3311. });
  3312.  
  3313. function addVersionLabel() {
  3314. $("body").append('<div class="versionLabel">' + GM_info.script.version +'</div>')
  3315. createSelector(".versionLabel", "position:fixed; right:0; bottom: 0; padding: 5px; color: #555; font-size: 10px; cursor:pointer")
  3316. $(".versionLabel").on("click", showUserscriptMenu)
  3317. }
  3318.  
  3319. function setupImages() {
  3320. IMAGES = {
  3321. EYE: 'https://i.imgur.com/kekYrsO.png',
  3322. CROSS: 'https://i.imgur.com/RItbpDS.png',
  3323. QUESTION: 'https://i.imgur.com/TUyoZOP.png',
  3324. PLUS: 'https://i.imgur.com/lT6SvSY.png',
  3325. TRASH: 'https://i.imgur.com/KrTbICA.png',
  3326. SAVE: 'http://i.imgur.com/Ze4h3NQ.png',
  3327. BOOKMARK: 'http://i.imgur.com/c6IxAql.png'
  3328.  
  3329. }
  3330. }

QingJ © 2025

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