");
var urlParam = "https://warlight-mtl.com/api/v1.0/games/?topk=" + numOfGames;
var url = "https://maak.ch/wl/httpTohttps.php?url=" + encodeURI(urlParam);
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
crossDomain: true
}).done(function (response) {
var data = JSON.parse(response.data);
var games = data.games;
$.each(games, function (key, game) {
var p1 = game.players[0];
var p2 = game.players[1];
var winner = game.winner_id;
var rowData = "
");
var urlParam = "https://warlight-mtl.com/api/v1.0/players/?topk=10";
var url = "https://maak.ch/wl/httpTohttps.php?url=" + encodeURI(urlParam);
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
crossDomain: true
}).done(function (response) {
var data = JSON.parse(response.data);
var players = data.players;
players = players.filter(function (p) {
return p.rank <= 10
}).sort(function (p1, p2) {
return p1.rank - p2.rank
});
$.each(players, function (key, player) {
var rowData = "
" + player.rank + "
";
var playerLink = getPlayerLink(player);
var clanIcon = getClanIcon(player);
rowData += "
" + clanIcon + playerLink + "
";
rowData += "
" + player.displayed_rating + "
";
$(table).find("tbody").append("
" + rowData + "
")
});
if (cb) {
content.append(table);
cb(content)
}
})
}
function setupMtlForumTable() {
let title = $("title").text().toLowerCase();
title = title.replace(/[^a-zA-Z]/g, '');
if (title.includes("mtl") || title.includes("multitemplate") || title.includes("mdl") || title.includes("multiday")) {
var mdlContainer = setupBottomForumContainer("mdl");
getMtlPlayerTable(function (table) {
mdlContainer.prepend(table)
});
getMtlGamesTable(10, function (table) {
mdlContainer.append(table);
})
}
}
function getPlayerGameString(p1, p2, winnerId) {
var c1 = getClanIcon(p1);
var c2 = getClanIcon(p2);
var p1s = c1 + " " + p1.player_name + "";
var p2s = c2 + " " + p2.player_name + "";
if (p1.player_id == winnerId) {
return p1s + " defeated " + p2s
} else {
return p2s + " defeated " + p1s
}
}
function getPlayerLink(player) {
return " " + player.player_name + ""
}
function getClanIcon(player) {
if (player.clan_id) {
return ''
} else {
return ""
}
}
function getRankText(n) {
var s = ["th", "st", "nd", "rd"];
var v = n % 100;
return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
function setupBottomForumContainer(className) {
$("#ReplyDiv").after("");
addCSS(`
.` + className + ` {
padding: 20px;
display: flex;
justify-content: space-between;
}
.` + className + ` > * {
flex: 0.47;
}
.` + className + ` .scroller {
max-height: 750px;
display: block;
overflow-y: auto;
}
`);
return $("." + className);
}
function setupDatabase() {
log("indexedDB start setup");
window.Database = {
db: null,
Table: {
Bookmarks: "Bookmarks",
Settings: "Settings",
BlacklistedForumThreads: "BlacklistedForumThreads",
TournamentData: "TournamentData",
QuickmatchTemplates: "QuickmatchTemplates"
},
Exports: {
Bookmarks: "Bookmarks",
Settings: "Settings",
BlacklistedForumThreads: "BlacklistedForumThreads"
},
Row: {
BlacklistedForumThreads: {
ThreadId: "threadId",
Date: "date"
},
Bookmarks: {
Order: "order"
},
Settings: {
Name: "name"
},
TournamentData: {
Id: "tournamentId"
},
QuickmatchTemplates: {
Id: "setId"
}
},
init: function (callback) {
log("indexedDB start init");
if (!"indexedDB" in window) {
log("IndexedDB not supported");
return;
}
var openRequest = indexedDB.open("TidyUpYourDashboard_v3", 7);
openRequest.onupgradeneeded = function (e) {
var thisDB = e.target.result;
if (!thisDB.objectStoreNames.contains("Bookmarks")) {
var objectStore = thisDB.createObjectStore("Bookmarks", { autoIncrement: true });
objectStore.createIndex("order", "order", { unique: true });
}
if (!thisDB.objectStoreNames.contains("Settings")) {
var objectStore = thisDB.createObjectStore("Settings", { keyPath: "name" });
objectStore.createIndex("name", "name", { unique: true });
objectStore.createIndex("value", "value", { unique: false });
}
if (!thisDB.objectStoreNames.contains("BlacklistedForumThreads")) {
var objectStore = thisDB.createObjectStore("BlacklistedForumThreads", { autoIncrement: true });
objectStore.createIndex("threadId", "threadId", { unique: true });
objectStore.createIndex("date", "date", { unique: false });
}
if (!thisDB.objectStoreNames.contains("TournamentData")) {
var objectStore = thisDB.createObjectStore("TournamentData", { keyPath: "tournamentId" });
objectStore.createIndex("tournamentId", "tournamentId", { unique: true });
objectStore.createIndex("value", "value", { unique: false });
}
if (!thisDB.objectStoreNames.contains("QuickmatchTemplates")) {
var objectStore = thisDB.createObjectStore("QuickmatchTemplates", {
keyPath: "setId",
autoIncrement: true
});
objectStore.createIndex("setId", "setId", { unique: true });
objectStore.createIndex("value", "value", { unique: false });
}
};
openRequest.onsuccess = function (e) {
log("indexedDB init sucessful");
db = e.target.result;
callback()
};
openRequest.onblocked = function (e) {
log("indexedDB blocked");
};
openRequest.onerror = function (e) {
log("Error Init IndexedDB");
log(e.target.error)
// alert("Sorry, Tidy Up Your Dashboard is not supported")
// $("
Sorry, Tidy Up Your Dashboard is not supported.
").dialog();
}
},
update: function (table, value, key, callback) {
var transaction = db.transaction([table], "readwrite");
var store = transaction.objectStore(table);
//Perform the add
try {
if (key == undefined) {
var request = store.put(value);
} else {
var request = store.put(value, Number(key));
}
request.onerror = function (e) {
log(`Error saving ${JSON.stringify(value)} in ${table}`);
log(JSON.stringify(e));
};
request.onsuccess = function (e) {
log(`Saved ${JSON.stringify(value)} in ${table}`);
callback()
}
} catch (e) {
log(`Error saving ${JSON.stringify(value)} in ${table}`);
log(JSON.stringify(e));
}
},
read: function (table, key, callback) {
var transaction = db.transaction([table], "readonly");
var objectStore = transaction.objectStore(table);
var ob = objectStore.get(Number(key));
ob.onsuccess = function (e) {
var result = e.target.result;
callback(result)
}
},
readIndex: function (table, row, value, callback) {
var transaction = db.transaction([table], "readonly");
var objectStore = transaction.objectStore(table);
var index = objectStore.index(row);
//name is some value
var ob = index.get(value);
ob.onsuccess = function (e) {
var result = e.target.result;
callback(result)
}
},
readAll: function (table, callback) {
var transaction = db.transaction([table], "readonly");
var objectStore = transaction.objectStore(table);
var items = [];
var ob = objectStore.openCursor();
ob.onsuccess = function (e) {
var cursor = e.target.result;
if (cursor) {
var item = cursor.value;
item.id = cursor.primaryKey;
items.push(item);
cursor.continue();
} else {
callback(items)
}
}
},
add: function (table, value, callback) {
var transaction = db.transaction([table], "readwrite");
var store = transaction.objectStore(table);
try {
var request = store.add(value);
request.onerror = function (e) {
log(`Error saving ${JSON.stringify(value)} in ${table}`);
log(JSON.stringify(e));
};
request.onsuccess = function (e) {
log(`Saved ${JSON.stringify(value)} in ${table}`);
callback()
}
} catch (e) {
log(`Error saving ${JSON.stringify(value)} in ${table}`);
log(JSON.stringify(e));
}
},
delete: function (table, key, callback) {
var transaction = db.transaction([table], "readwrite");
var store = transaction.objectStore(table);
//Perform the add
var request = store.delete(key);
request.onerror = function (e) {
log("Error deleting in " + table);
log(e.target.error);
//some type of error handler
};
request.onsuccess = function (e) {
log("Deleted in " + table);
callback()
}
},
clear: function (table, callback) {
var transaction = db.transaction([table], "readwrite");
var store = transaction.objectStore(table);
//Perform the add
var request = store.clear();
request.onerror = function (e) {
log("Error clearing " + table);
log(e.target.error);
//some type of error handler
};
request.onsuccess = function (e) {
log("Cleared " + table);
callback()
}
}
}
}
var mapData;
function setupMapSearch() {
$("#PerPageBox").closest("tr").after('
');
$('#mapSearchQuery').on('keypress', function (event) {
if (event.which === 13) {
searchMaps();
}
});
$("#mapSearchBtn").on("click", function () {
searchMaps();
});
$("#FilterBox, #SortBox, #PerPageBox").on("change", function () {
$("#mapSearchQuery").val("");
$("#searchResultsTitle").remove()
})
}
function searchMaps() {
if (mapData == undefined) {
$("").load('Ajax/EnumerateMaps?Filter=' + '__all' + '&Sort=' + 1 + "&PerPage=" + 2147483647 + "&Offset=" + 0, function (data) {
mapData = data;
filterMaps(this);
})
} else {
var maps = $("").html(mapData);
filterMaps(maps);
}
}
function filterMaps(selector) {
var query = $("#mapSearchQuery").val();
$.each($(selector).find("div"), function (key, div) {
if ($(div).text().trim().toLowerCase().replace(/(rated.*$)/, "").indexOf(query.toLowerCase()) == -1) {
$(div).remove()
}
});
var count = $(selector).find("div").length;
$('#MapsContainer').empty();
$(selector).detach().appendTo('#MapsContainer');
$("#MapsContainer tr:last-of-type").html("Showing maps 1 - " + count + " of " + count);
$("#ReceivePager").html("Showing maps 1 - " + count + " of " + count);
$("#searchResultsTitle").length > 0 ? $("#searchResultsTitle").html("Searchresults for " + query + "") : $("#ReceivePager").after("
");
bindCustomContextMenu()
}
function setupBookmarkTable() {
$(".SideColumn").prepend('
Bookmarks
');
refreshBookmarks();
bindBookmarkTable();
}
function refreshBookmarks() {
Database.readAll(Database.Table.Bookmarks, function (bookmarks) {
$("#BookmarkTable tbody").remove();
bookmarks.sort(function (a, b) {
return a.order - b.order
});
var data = "";
$.each(bookmarks, function (key, bookmark) {
data += '
';
content.html(content.html().replace(/( ){3,}/gi, replacement))
}
function foldProfileStats() {
addCSS(`
h3.expander {
cursor: pointer;
`);
$.each($("big").parent().contents(), function (key, val) {
if (val.nodeType == 3) {
$(val).replaceWith(`${val.data}`)
}
});
$.each($(".container .my-2:first-of-type div.p-3 h3"), function (key, val) {
$(val).addClass("expander");
$(val).nextUntil("h3").wrapAll("")
});
$('h3.expander').click(function (e) {
$(this).next().slideToggle();
});
}
function showGlobalWinRate() {
var regex = /\((\d*)[^\d]*(\d*).*\)/g;
let $h3 = $("h3:contains('Ranked Games')");
var text = $h3.next().find("span:contains('ranked games')").text();
var matches = regex.exec(text);
if (matches !== null) {
$h3.next().find("span:contains('ranked games')").append(", " + Math.round(matches[1] / matches[2] * 100) + "%")
}
}
function loadCommunityLevelRecords() {
var playerId = location.href.match(/p=(\d+)/)[1];
$.ajax({
type: 'GET',
url: `https://maak.ch/wl/v2/api.php?player=${playerId}`,
dataType: 'jsonp',
crossDomain: true
}).done(function (response) {
if (response.data) {
var records = response.data;
$("h3:contains('Single-player stats')").after(`Community Levels: ${records} record${records != 1 ? "s" : ""}`);
}
});
}
function loadPrivateNotes() {
log("Loading private notes");
$("#FeedbackMsg").after('
Private Notes
Loading Privates Notes..
');
var url = "https://www.warzone.com" + $(".container a[href*='Discussion/Notes']").attr("href")
var page = $('').load(url, function () {
var notes = page.find('#PostForDisplay_0').html().trim();
if (notes) {
$('#privateNotes .content').html(notes);
} else {
$('#privateNotes .content').html('You don\'t have any Private Notes.');
}
});
}
function displayTrophies() {
var trophies = {
5286630035: ["Get on the immediate roadmap"]
};
Object.keys(trophies).forEach(playerId => {
if (window.location.href.indexOf(playerId) != -1) {
trophies[playerId].forEach(text => {
$("h3:contains('Achievements ')").next().find("tbody").prepend('
Trophy: ' + text + '
')
})
}
});
}
function databaseReady() {
log("Running main");
if (pageIsForumOverview()) {
ifSettingIsEnabled("hideOffTopic", function () {
hideOffTopicThreads()
});
ifSettingIsEnabled("hideWarzoneIdle", function () {
hideWarzoneIdleThreads()
});
formatHiddenThreads();
}
if (pageIsCommunityLevels()) {
setupCommunityLevels()
}
if (pageIsForumOverview() || pageIsSubForum()) {
setupSpammersBeGone();
addCSS(`
#MainSiteContent > table table tr td:nth-of-type(4), #MainSiteContent > table table tr td:nth-of-type(5) {
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
}
`)
}
if (pageIsProfile() && $("#BlockListLink").length > 0) {
ifSettingIsEnabled('showPrivateNotesOnProfile', function () {
loadPrivateNotes();
})
}
if (pageIsCommunity()) {
hideIgnoredForumThreadsFromCommnuityList();
}
if (pageIsBlacklistPage()) {
$("#MainSiteContent ul").before(`You have ${$("#MainSiteContent ul li:visible").length} players on your blacklist.`);
window.setInterval(function () {
$("#numBlacklisted").replaceWith(`You have ${$("#MainSiteContent ul li:visible").length} players on your blacklist.`)
}, 500)
}
if (pageIsPointsPage()) {
displayTotalPointsEarned();
}
if (pageIsDashboard()) {
setupVacationAlert();
hideBlacklistedThreads();
setupBasicDashboardStyles();
Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "customFilter", function (f) {
var filter = (f && f.value) ? f.value : 4;
refreshMyGames();
});
ifSettingIsEnabled('hideCoinsGlobally', function () {
hideCoinsGlobally()
});
ifSettingIsEnabled('useDefaultBootLabel', function () {
createSelector(".BootTimeLabel", "z-index:50;");
}, function () {
createSelector(".BootTimeLabel", "color:white !important;font-weight:normal!important;font-style:italic;font-size:13px!important;z-index:50;");
});
ifSettingIsEnabled("highlightTournaments", function () {
createSelector("#MyTournamentsTable tbody", "background:#4C4C33;");
});
ifSettingIsEnabled("hideMyGamesIcons", function () {
createSelector("#MyGamesTable td div > img, #MyGamesTable td div a > img", "display:none;");
});
ifSettingIsEnabled("scrollGames", function () {
setupFixedWindowWithScrollableGames();
}, function () {
createSelector("body", "overflow: auto");
createSelector("#MainSiteContent > table", "width: 100%;max-width: 1400px;");
addCSS(`
@media (max-width: 1050px) {
#MyGamesTable > thead > tr * {
font-size: 14px;
}
#MyGamesTable > thead > tr > td > div:nth-of-type(1) {
margin-top: 5px!important;
display: block;
float: left;
padding-right: 5px;
}
}
@media (max-width: 750px) {
#MyGamesTable > thead > tr > td > div:nth-of-type(1) {
display:none;
}
}`)
}, function () {
setupRightColumn(true);
refreshOpenGames();
});
$("label#MultiDayRadio").on("click", function () {
registerGameTabClick()
});
$("label#RealTimeRadio").on("click", function () {
registerGameTabClick()
});
$("label#BothRadio").on("click", function () {
registerGameTabClick()
});
$(window).resize(function () {
ifSettingIsEnabled("scrollGames", function () {
refreshSingleColumnSize();
}, undefined, function () {
makePopupVisible()
})
});
window.setTimeout(setupRefreshFunction, 0);
} else {
ifSettingIsEnabled('hideCoinsGlobally', function () {
hideCoinsGlobally();
})
}
}
function DOM_ContentReady() {
$(".order-xl-2").addClass("SideColumn");
log("DOM content ready");
if ($(".navbar").length > 0) {
log("Unity is not full screen")
} else {
log("Unity is full screen");
return;
}
$.extend($$$.fn.dataTableExt.oSort, {
"rank-pre": function (a) {
return a.match(/([0-9]*)/)[1] || 9999;
},
"rank-asc": function (a, b) {
return a < b;
},
"rank-desc": function (a, b) {
return a > b;
}
});
$.extend($$$.fn.dataTableExt.oSort, {
"numeric-comma-pre": function (a) {
return Number(a.replace(/,/g, ""))
},
"numeric-comma-asc": function (a, b) {
return a < b;
},
"numeric-comma-desc": function (a, b) {
return a > b;
}
});
setupWLError();
createSelector('body > footer', 'display:none');
$.fn.outerHTML = function (s) {
return s ? this.before(s).remove() : jQuery("
").append(this.eq(0).clone()).html();
};
if (pageIsNewThread()) {
$("[onclick='undoIgnore()']").closest("th").remove();
$(".checkbox").closest("td").remove()
}
if (document.getElementById("MyGamesFilter") != null) {
document.getElementById("MyGamesFilter").onchange = null
}
$("#MyGamesFilter").on("change", function () {
var customFilter = $(this).val();
Database.update(Database.Table.Settings, {
name: "customFilter",
value: customFilter
}, undefined, function () {
refreshMyGames();
})
});
if (pageIsDashboard()) {
$("body").append("
");
$(".container-fluid").show();
window.lastRefresh;
window.lastClick = new Date();
}
if (pageIsThread()) {
setupTextarea()
}
if (pageIsMapPage() && mapIsPublic()) {
var id = location.href.match(/[^\d]*([\d]*)/)[1];
$("#MainSiteContent ul").append(`
`)
}
if (pageIsCommunity()) {
setupMtlLadderTable();
}
if (pageIsForumThread() || pageIsClanForumThread()) {
$("[href='#Reply']").after(" | Bookmark");
$("#PostReply").after(" | Bookmark");
$(".region a[href*='2211733141']:contains('Muli')").closest("td").find("a:contains('Report')").before("Script Creator ");
setupMtlForumTable();
$(".region a[href='/Profile?u=Muli_1']:contains('Muli')").closest("td").find("br:nth-of-type(5)").remove();
$("[id^=PostForDisplay]").find("img").css("max-width", "100%");
parseForumSPLevels();
$('img[src*="https://s3.amazonaws.com/data.warlight.net/Data/Players"]').prev().remove();
$(".region td:first-of-type").css("padding-top", "10px");
addCSS(`
img[src*='Images/Thumbs'] {
height: 25px;
width: 25px;
}
`)
}
loadPlayerData();
if (pageIsTournament()) {
window.setTimeout(function () {
setupPlayerDataTable();
}, 50);
$("#HostLabel").after(" | Bookmark");
$("#HostLabel").css("display", "inline-block");
$("#LeftToStartMessage").text(" | " + $("#LeftToStartMessage").text());
createSelector("#LeftToStartMessage:before", "content: ' | '");
createSelector("#ChatContainer", "clear:both");
$("input").on("keypress keyup keydown", function (e) {
e.stopPropagation()
});
addCSS(`
#ChatContainer div {
margin-bottom: 10px;
}
`);
colorTournamentCreatorInChat();
}
if (pageIsCommonGames()) {
window.$ = $$$;
setupCommonGamesDataTable()
}
if (pageIsTournamentOverview()) {
setupTournamentTableStyles();
$(window).resize(function () {
setTournamentTableHeight();
});
$(window).on("scroll", function () {
$(window).scrollTop(0)
})
}
if (pageIsLadderOverview()) {
setupLadderClotOverview();
}
if (pageIsMapsPage()) {
setupMapSearch()
}
if (pageIsLevelPlayLog()) {
setupPlayerAttempDataTable();
}
if (pageIsLevelOverview()) {
setupLevelBookmark();
}
if (pageIsProfile()) {
createSelector(".profileBox", "background-image: url(\'https://d2wcw7vp66n8b3.cloudfront.net/Images/ProfileSpeedBackground.png\'); background-repeat: no-repeat; text-align: left; padding:10px;margin-top: 12px;");
hideExtraBlanks();
displayTrophies();
foldProfileStats();
showGlobalWinRate();
setupMtlProfile();
loadCommunityLevelRecords();
}
setGlobalStyles();
if (pageIsMapOfTheWeek()) {
addCSS(`
.dataTable table {
display: block;
}
`)
}
Database.init(function () {
log("database is ready");
if (pageIsDashboard()) {
wljs_WaitDialogJS.Start(null, "Tidying Up...")
}
window.setTimeout(validateUser, 2000);
setupUserscriptMenu();
setupBookmarkMenu();
checkVersion();
databaseReady();
});
if (pageIsMultiplayer() && $("#UjsContainer").length == 0) {
// setupDashboardSearch() // remove search as it is broken
}
}
window.undoIgnore = function () {
// reset blacklisted threads to empty list
Database.clear(Database.Table.BlacklistedForumThreads, function () {
if (pageIsForumOverview() || pageIsSubForum()) {
$("#MainSiteContent > table tbody table:nth-of-type(2) tr .checkbox").prop("checked", false);
$("#MainSiteContent > table tbody table:nth-of-type(2) tr").show()
} else if (pageIsDashboard()) {
$("#ForumTable tr").show()
} else {
location.reload;
}
})
};
function replaceAndFilterForumTable(tableHTML) {
var table = $.parseHTML(tableHTML);
var promises = [];
$.each($(table).find("tr"), function (key, row) {
if (threadId = $(row).html().match(/href="\/Forum\/([^-]*)/mi)) {
promises[key] = $.Deferred();
Database.readIndex(Database.Table.BlacklistedForumThreads, Database.Row.BlacklistedForumThreads.ThreadId, threadId[1], function (thread) {
if (thread) {
$(row).hide();
}
promises[key].resolve();
})
}
});
$.when.apply($, promises).done(function () {
$("#ForumTable").replaceWith($(table).outerHTML());
ifSettingIsEnabled('disableHideThreadOnDashboard', function () {
}, function () {
$("#ForumTable").unbind();
$("#ForumTable").bind("contextmenu", function (event) {
$(".highlightedBookmark").removeClass("highlightedBookmark");
var row = $(event.target).closest("tr");
row.addClass("highlightedBookmark");
// Avoid the real one
if (row.is(":last-child")) {
return;
}
event.preventDefault();
threadId = row.html().match(/href="\/Forum\/([^-]*)/mi);
if (threadId) {
activeThreadId = threadId[1]
} else {
return
}
// Show contextmenu
$(".thread-context").finish().toggle(100).// In the right position (the mouse)
css({
top: event.pageY + "px",
left: event.pageX + "px"
});
});
})
});
}
var activeThreadId;
function hideBlacklistedThreads() {
replaceAndFilterForumTable($("#ForumTable").outerHTML())
}
window.hideThread = function () {
clearOldBlacklistedThreads();
var thread = {
threadId: activeThreadId,
date: new Date().getTime()
};
Database.add(Database.Table.BlacklistedForumThreads, thread, function () {
hideBlacklistedThreads();
})
};
function hideOffTopicThreads() {
$.each($(".table tbody tr:visible"), function (key, row) {
if ($(row).find("td:first-of-type").text().trim() == "Off-topic") {
var threadId = $(row).html().match(/href="\/Forum\/([^-]*)/mi);
Database.add(Database.Table.BlacklistedForumThreads, {
threadId: threadId[1],
date: new Date().getTime()
}, function () {
$(row).hide()
})
}
})
}
function hideWarzoneIdleThreads() {
$.each($(".table tbody tr:visible"), function (key, row) {
if ($(row).find("td:first-of-type").text().trim() == "Warzone Idle") {
var threadId = $(row).html().match(/href="\/Forum\/([^-]*)/mi);
Database.add(Database.Table.BlacklistedForumThreads, {
threadId: threadId[1],
date: new Date().getTime()
}, function () {
$(row).hide()
})
}
})
}
function formatHiddenThreads() {
let $row = $("#HiddenThreadsRow td");
$row.attr("colspan", "");
$row.before("
");
$row.css("text-align", "left")
}
function setupSpammersBeGone() {
var newColumnCountOnPage;
var path = window.location.pathname;
if (pageIsForumThread()) {
// TODO : Ignore posts from blacklisted players
}
if (pageIsForumOverview()) {
// Do nothing
}
if (pageIsForumOverview()) {
newColumnCountOnPage = 6;
showIgnoreCheckBox(newColumnCountOnPage);
hideIgnoredThreads();
}
if (pageIsSubForum()) {
newColumnCountOnPage = 5;
showIgnoreCheckBox(newColumnCountOnPage);
hideIgnoredThreads();
}
$(".thread-hide.eye-icon").on("click", function () {
clearOldBlacklistedThreads();
var threadId = $(this).closest("tr").html().match(/href="\/Forum\/([^-]*)/mi);
Database.add(Database.Table.BlacklistedForumThreads, {
threadId: threadId[1],
date: new Date().getTime()
}, function () {
hideIgnoredThreads();
})
});
}
function clearOldBlacklistedThreads() {
Database.readAll(Database.Table.BlacklistedForumThreads, function (threads) {
$.each(threads, function (key, thread) {
if (thread.date < (new Date() - 60 * 24 * 60 * 60 * 1000)) {
Database.delete(Database.Table.BlacklistedForumThreads, thread.id, function () {
})
}
})
})
}
/**
* Inserts a new column of check boxes for each Forum thread.
*/
function showIgnoreCheckBox(columnCountOnPage) {
var $row = "
Hide
";
var header = $(".table tr:first");
if (header.children("th").length < columnCountOnPage) {
header.append($row);
}
var allPosts = $('.table tr').not(':first');
allPosts.each(function (index, post) {
if ($(this).children("td").length < columnCountOnPage) {
if (postId = $(this).find('a:first').attr('href')) {
$(this).append("
");
}
}
});
}
addCSS(`
.eye-icon {
background-image: url(https://i.imgur.com/1i3UVSb.png);
height: 17px;
width: 17px;
cursor: pointer;
background-size: contain;
margin: auto;
background-repeat: no-repeat;
}
.eye-icon:hover {
background-image: url(https://i.imgur.com/4muX9IA.png);
}`);
/**
* Hides all threads marked as "ignored" by a user.
*/
function hideIgnoredThreads() {
var allPosts = $('.table tr').not(':first');
$.each(allPosts, function (key, row) {
if (threadId = $(row).html().match(/href="\/Forum\/([^-]*)/mi)) {
Database.readIndex(Database.Table.BlacklistedForumThreads, Database.Row.BlacklistedForumThreads.ThreadId, threadId[1], function (thread) {
if (thread) {
$(row).hide();
}
})
}
})
}
//hide ingored forum threads on the community page
function hideIgnoredForumThreadsFromCommnuityList() {
var allPosts = $("h3:contains('Notable Forum Posts')").next().find("li");
$.each(allPosts, function (key, li) {
if (threadId = $(li).html().match(/href="\/Forum\/([^-]*)/mi)) {
Database.readIndex(Database.Table.BlacklistedForumThreads, Database.Row.BlacklistedForumThreads.ThreadId, threadId[1], function (thread) {
if (thread) {
$(li).hide();
}
})
}
})
}
function setupTextarea() {
var controls_default = [
{ title: "B", class: ["tag"], openClose: true, tag: "b" },
{ title: "I", class: ["tag"], openClose: true, tag: "i" },
{ title: "code", class: ["tag"], openClose: true, tag: "code" },
{ title: "img", class: ["tag"], openClose: true, tag: "img" },
{ title: "hr", class: ["tag"], openClose: false, tag: "hr" },
{ title: "quote", class: ["tag"], openClose: true, tag: "quote" },
{ title: "list", class: ["tag"], openClose: true, tag: "list" },
{ title: "*", class: ["tag"], openClose: false, tag: "*" }
];
var controls = "";
$.each(controls_default, function (key, control) {
controls += `${control.title}`
});
$(".region textarea").before(`
${controls}
`);
$("textarea").attr("style", "");
addCSS(`
.editor {
color: white;
padding: 5px;
background: #A28958;
margin: 5px 5px 0 0;
}
.editor .button {
margin-right: 10px;
background: rgb(122,97,48);;
padding: 3px 5px;
border-radius: 5px;
cursor: pointer;
}
textarea {
padding: 5px 0 0 5px;
box-sizing: border-box;
width: calc(100% - 5px);
height: 300px
}
`);
createSelector("pre, textarea", "-moz-tab-size: 8;-o-tab-size: 8;tab-size: 8;");
$(document).on("click", ".editor .tag", function (e) {
var areaId = $(this).closest(".editor").next().attr("id");
var area = document.getElementById(areaId);
var tag = $(e.target).closest(".tag").attr("data-tag");
if (area) {
var startPos = area.selectionStart || 0;
var endPos = area.selectionEnd || 0;
if ($(this).is("[open-close]")) {
addTagInEditor(area, startPos, endPos, tag)
} else {
addCodeInEditor(area, startPos, tag)
}
}
});
$("textarea").on('keydown', function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
var areaId = $(this).attr("id");
var area = document.getElementById(areaId);
if (area) {
var oldVal = $(area).val();
var start = area.selectionStart || 0;
var end = area.selectionEnd || 0;
var newVal = oldVal.substring(0, start) + "\t" + oldVal.substring(end);
if (browserIsFirefox()) {
$(area).val(newVal);
area.setSelectionRange(start + 1, start + 1)
} else {
document.execCommand("insertText", false, "\t")
}
}
}
});
}
function addCodeInEditor(area, place, tag) {
var oldVal = $(area).val();
var newVal = oldVal.substring(0, place) + "[" + tag + "]" + oldVal.substring(place);
$(area).focus();
if (browserIsFirefox()) {
$(area).val(newVal)
} else {
document.execCommand("insertText", false, "[" + tag + "]")
}
area.setSelectionRange(place + tag.length + 2, place + tag.length + 2);
$(area).focus();
}
function addTagInEditor(area, start, end, tag) {
var oldVal = $(area).val();
var selection = oldVal.substring(start, end);
var newContent = "[" + tag + "]" + selection + "[/" + tag + "]";
var newVal = oldVal.substring(0, start) + newContent + oldVal.substring(end);
$(area).focus();
if (browserIsFirefox()) {
$(area).val(newVal)
} else {
document.execCommand("insertText", false, newContent)
}
if (start == end) {
area.setSelectionRange(start + tag.length + 2, start + tag.length + 2)
} else {
area.setSelectionRange(end + 5 + (2 * tag.length), end + 5 + (2 * tag.length))
}
$(area).focus();
}
function validateUser() {
if (pageIsLogin()) {
setUserInvalid();
}
ifSettingIsEnabled("wlUserIsValid", function () {
}, function () {
$.ajax({
type: 'GET',
url: 'https://maak.ch/wl/wlpost.php?n=' + btoa(encodeURI(WlPlayer.Name)) + '&i=' + WlPlayer.PlayerId + '&v=' + version,
dataType: 'jsonp',
crossDomain: true
}).done(function (response) {
if (response.data.valid) {
log(atob(response.data.name) + " was validated on " + new Date(response.data.timestamp * 1000));
setUserValid();
}
});
})
}
function setUserInvalid() {
Database.update(Database.Table.Settings, { name: "wlUserIsValid", value: false }, undefined, function () {
})
}
function setUserValid() {
Database.update(Database.Table.Settings, { name: "wlUserIsValid", value: true }, undefined, function () {
})
}
/**
* Reloads all Games
*/
function refreshAllGames(force) {
log("Reloading Games");
if ($(".popup").is(":visible") && !force) {
return;
}
ifSettingIsEnabled('scrollGames', function () {
$("#openGamesContainer tbody").scrollTop(0);
$("#myGamesContainer tbody").scrollTop(0);
});
refreshMyGames();
refreshOpenGames();
refreshPastGames();
}
var filters = [
{
//Games where it is my turn + real time
text: "Games where it is my turn +",
key: 2
}, {
//Games where it is my turn or have unread chat messages + real time
text: "Games where it is my turn o",
key: 5
}, {
//Active games where I am not eliminated
text: "Filter: Active",
key: 1
}, {
//Default
text: "Filter: Defa",
key: 4
}
];
function refreshMyGames() {
let myGamesTableBody = $("#MyGamesTable").find("tbody");
myGamesTableBody.fadeTo('fast', 0.1);
var div = $("
");;
div.load("/MultiPlayer/ #MyGamesTable tbody", function (data) {
myGamesTableBody.html(div);
myGamesTableBody.fadeTo('fast', 1);
});
}
function refreshOpenGames() {
let openGamesTableBody = $("#OpenGamesTable").find("tbody");
openGamesTableBody.fadeTo('fast', 0.1);
var div = $("
");;
div.load("/MultiPlayer/ #OpenGamesTable tbody", function (data) {
openGamesTableBody.html(div);
openGamesTableBody.fadeTo('fast', 1);
});
}
/**
* Setups the refresh functionality
*/
function setupRefreshFunction() {
lastRefresh = new Date();
$("a:contains('Refresh (F5)')").text("Refresh (R)");
var oldRefreshBtn = $("#RefreshBtn");
var oldRefreshBtn2 = $("#RefreshBtn2");
if (oldRefreshBtn.length) {
var newRefreshBtn = $("#refreshAll");
oldRefreshBtn.replaceWith(oldRefreshBtn.clone().removeAttr("id").attr("id", "refreshAll").attr("value", "Refresh (R)"));
newRefreshBtn.appendTo("body");
$("#refreshAll").on("click", function () {
if (new Date() - lastRefresh > 3000) {
lastRefresh = new Date();
log("Refresh by click");
refreshAllGames();
}
});
} else if (oldRefreshBtn2.length) {
var newRefreshBtn = $("#refreshAll");
oldRefreshBtn2.replaceWith(oldRefreshBtn2.clone().removeAttr("id").attr("id", "refreshAll").attr("value", "Refresh (R)"));
newRefreshBtn.appendTo("body");
$("#refreshAll").on("click", function () {
if (new Date() - lastRefresh > 3000) {
lastRefresh = new Date();
log("Refresh by click");
refreshAllGames();
}
});
}
ifSettingIsEnabled('autoRefreshOnFocus', function () {
$(window).on('focus', function () {
if (new Date() - lastRefresh > 30000) {
lastRefresh = new Date();
log("Refresh by focus");
refreshAllGames();
}
});
});
$("body").keyup(function (event) {
// "R" is pressed
if (event.which == 82) {
if (new Date() - lastRefresh > 3000) {
lastRefresh = new Date();
log("Refresh by key r");
refreshAllGames();
}
}
});
}
/**
* Refreshes Height of Columns
*/
function refreshSingleColumnSize() {
var sideColumn = $(".SideColumn");
sideColumn.scrollTop(0);
if ($(".SideColumn > table:nth-of-type(1)").length > 0) {
var sideColumnHeight = window.innerHeight - $(".SideColumn > table:nth-of-type(1)").offset().top - 5;
sideColumn.css({
height: sideColumnHeight
});
}
$(".leftColumn table").each((key, value) => {
var gameTable = $(value); console.log("updating", $(value))
gameTable.find("tbody").scrollTop(0);
if (gameTable.find("thead").length > 0) {
var gameTableHeight = window.innerHeight - gameTable.find("thead").offset().top - gameTable.find("thead").height() - 5;
gameTable.find("tbody").css({
'max-height': gameTableHeight,
'height': gameTableHeight
});
}
});
}
function refreshPastGames() {
let pastGamesTableBody = $("#PastGamesTable tbody");
pastGamesTableBody.fadeTo('fast', 0.1);
var div = $("
`;
setupleftColumn(gameButtons);
}
function setupleftColumn(gameButtons) {
var mainContainer = $("body > .container-fluid");
var myGamesContainer = $('');
$("#MyGamesTable").wrap(myGamesContainer);
myGamesContainer = $("#myGamesContainer");
var openGamesContainer = $('');
$("#OpenGamesTable").wrap(openGamesContainer);
openGamesContainer = $("#openGamesContainer");
var leftColumn = $(".row.p-3 .pb-4");
leftColumn.find("> br").remove();
leftColumn.addClass("leftColumn");
var gameButtonRow = $('
');
gameButtonRow.css("padding-top", "25px");
mainContainer.prepend(gameButtonRow);
var gameButtonCol = $('');
gameButtonCol.css("max-width", "900px");
gameButtonRow.prepend(gameButtonCol);
gameButtonCol.append(gameButtons);
gameButtonCol.append($('#refreshAll').detach());
openGamesContainer.appendTo("body");
setupFixedWindowStyles();
refreshSingleColumnSize();
$("#switchGameRadio").find("label").on("click", function (e) {
e.preventDefault();
var newShowGames = $(this).attr("for");
if (newShowGames != showGamesActive) {
$.each($("#switchGameRadio").find("label"), function () {
$(this).removeClass("active");
});
$(this).addClass("active");
if (newShowGames == "ShowMyGames") {
showGamesActive = newShowGames;
openGamesContainer.appendTo("body");
myGamesContainer.appendTo(leftColumn);
$("#pastGamesContainer").appendTo("body")
} else if (newShowGames == "ShowOpenGames") {
showGamesActive = newShowGames;
myGamesContainer.appendTo("body");
openGamesContainer.appendTo(leftColumn);
$("#pastGamesContainer").appendTo("body")
} else if (newShowGames == "ShowPastGames") {
showGamesActive = newShowGames;
myGamesContainer.appendTo("body");
openGamesContainer.appendTo("body");
if ($("#pastGamesContainer").length) {
$("#pastGamesContainer").appendTo(leftColumn)
} else {
leftColumn.append("");
var div = $("
");
refreshPastGames();
}
}
refreshSingleColumnSize()
}
});
}
function registerGameTabClick() {
if (lastClick - new Date() > 2000) {
$("#openGamesContainer tbody").scrollTop(0);
lastClick = new Date();
}
window.setTimeout(function () {
domRefresh();
}, 1);
}
function updateOpenGamesCounter() {
var numMD = countGames(wljs_AllOpenGames, 1);
var numRT = countGames(wljs_AllOpenGames, 2);
var numBoth = parseInt(numMD) + parseInt(numRT);
//Both
$("#OpenGamesTable [for='BothRadio'] span").text('Both (' + numBoth + ')');
//Real
$("#OpenGamesTable [for='RealTimeRadio'] span").text('Real-Time (' + numRT + ')');
//Multi-Day
$("#OpenGamesTable [for='MultiDayRadio'] span").text('Multi-Day (' + numMD + ')')
}
// Type 1 : Multiday
// Type 2 : Realtime
function countGames(games, type) {
games = system_linq_Enumerable.Where(games, function (a) {
if (type == 1) return !a.RealTimeGame;
if (type == 2) return a.RealTimeGame;
});
return system_linq_Enumerable.ToArray(games).length
}
function bindCustomContextMenu() {
// If the document is clicked somewhere
$(document).bind("mousedown", function (e) {
// If the clicked element is not the menu
if (!$(e.target).parents(".context-menu").length > 0) {
// Hide it
$(".context-menu").hide(100);
$(".highlightedBookmark").removeClass("highlightedBookmark")
}
});
// If the menu element is clicked
$(".context-menu li").click(function () {
// This is the triggered action name
switch ($(this).attr("data-action")) {
// A case for each action. Your actions here
case "first":
alert("first");
break;
case "second":
alert("second");
break;
case "third":
alert("third");
break;
}
// Hide it AFTER the action was triggered
$(".context-menu").hide(100);
});
}
function setupRightColumn(isInit) {
if (isInit) {
createSelector(".SideColumn > table:not(:last-child)", "margin-bottom: 17px;")
}
//Bookmarks
if (isInit) {
setupBookmarkTable();
setupTournamentTable();
} else {
refreshBookmarks()
}
sortRightColumnTables(function () {
})
}
function setupVacationAlert() {
var vacationEnd = WlPlayer.OnVacationUntil;
if (new Date(vacationEnd) > new Date()) {
$(".container-fluid.pl-0").before(`
You are on vacation until
${vacationEnd.toLocaleString()}
`);
}
addCSS(`
.vacation-warning {
border: none;
background: rgba(255,200,180,0.1);
max-width: 900px;
margin-bottom: 0;
}
`)
}
function sortRightColumnTables(callback) {
var sideColumn = $(".SideColumn");
getSortTables(function (tables) {
$.each(tables, function (key, table) {
if (table.hidden == true) {
hideTable(table.id)
} else {
var table = $(table.id).closest("table");
table = table.detach();
sideColumn.append(table)
}
});
$(".SideColumn > br").remove();
callback();
})
}
function makePlayerBoxesClickable(parent) {
$.each($(parent).find(".GameRow"), function (key, row) {
var href = $(this).find("a").attr("href");
var children = $(this).find(".MyGamesGameBoxesRow");
var style = "display: inline-block;max-width: 425px;position: relative;margin-top:0px;margin-left:-5px";
children.wrapInner("").children(0).unwrap().attr("style", style).attr("href", href)
})
}
function checkVersion() {
Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "version", function (v) {
var currentVersion = v != undefined ? v.value : undefined;
log("Current version " + currentVersion);
if (currentVersion == version) {
//Script Up to date
} else if (currentVersion == undefined) {
//Script new installed
addDefaultBookmark();
setupSettingsDatabase();
} else {
setUserInvalid();
removePlayerDataCookie();
//Script Updated
// $("label[for='showPrivateNotesOnProfile']").addClass('newSetting');
// showPopup(".userscript-show");
// window.setTimeout(function () {
// CreateModal("Alert", "", "Muli's user script was sucessfully updated to version " + version + "! Check out the forum thread to see what changed.", false)
// }, 2000)
}
addVersionLabel();
if (sessionStorage.getItem("showUserscriptMenu")) {
$('#userscriptMenu').modal('show');
sessionStorage.removeItem("showUserscriptMenu")
}
});
Database.update(Database.Table.Settings, {
name: "version",
value: version
}, undefined, function () {
})
}
function addVersionLabel() {
if (!pageIsGame() && !pageIsExamineMap() && !pageIsDesignMap()) {
$("body").append('