Tidy up your Dashboard

Customizable Userscript which tidies up your Dashboard!

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

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

QingJ © 2025

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