Tidy up your Dashboard

Customizable Userscript which tidies up your Dashboard!

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

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

QingJ © 2025

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