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

QingJ © 2025

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