'
}
function setRTLadderTime() {
var date = new Date()
date.setMinutes(Math.ceil((new Date().getMinutes() + date.getSeconds() / 60) / 5) * 5)
date.setSeconds(0)
var diff = (date - new Date()) / 1000
var min = Math.floor(diff / 60) % 60
diff -= min * 60
var sec = diff % 60
$(".rtMin").text(padLeft(min))
$(".rtSec").text(padLeft(sec))
}
function padLeft(str) {
str = Math.round(str)
len = 2
symbol = '0'
while(String(str).length < len) {
str = symbol + str;
}
return str
}
function setupBookmarkMenu() {
bookmarkBody = "
Name Url Open in new Window ";
$("body").append("");
$("bookmarkMenu").append('');
$(".close-popup-img").on("click", function () {
$(".popup").fadeOut();
$(".overlay").fadeOut();
});
createSelector(".highlightedBookmark", "background-color:rgb(50, 50, 50);cursor:pointer;");
$("body").append("")
$("body").append("")
$("body").append("")
bindCustomContextMenu()
}
function setupBookmarkTable() {
$(".SideColumn").prepend('
Bookmarks
');
refreshBookmarks();
bindBookmarkTable();
}
function refreshBookmarks() {
Database.readAll(Database.Table.Bookmarks, function(bookmarks) {
$("#BookmarkTable tbody tr").remove();
bookmarks.sort(function(a, b) {return a.order - b.order})
var data = "
";
$.each(bookmarks, function (key, bookmark) {
data += '' + bookmark.name + ' ';
data += '';
data += ' ';
})
$("#BookmarkTable").prepend(data + ' ');
warlight_shared_viewmodels_WaitDialogVM.Stop()
$(".loader").fadeOut("fast", function() {
if($(".loader")) {
$(".loader").remove();
window.timeUserscriptReady = new Date().getTime();
log("Time userscript ready " + (timeUserscriptReady - timeUserscriptStart) / 1000)
}
})
})
}
window.bookmarkOrder;
window.bookmarkId;
window.showAddBookmark = function () {
showPopup("#bookmarkMenu")
bookmarkId = undefined
bookmarkOrder = undefined
}
window.editBookmark = function () {
Database.read(Database.Table.Bookmarks, bookmarkId, function(bookmark) {
$("#bookmarkURL").val(bookmark.url);
$("#bookmarkName").val(bookmark.name);
$("#bookmarkNewWindow").prop("checked", bookmark.newWindow);
showPopup("#bookmarkMenu");
})
}
window.moveBookmarkUp = function() {
Database.readAll(Database.Table.Bookmarks, function(bookmarks) {
var bookmark;
var newIdx = -1
$.each(bookmarks, function (key, bm) {
if (bookmarkId == bm.id) {
bookmark = bm
}
})
bookmarks.sort(function(a,b){return a.order - b.order});
var previousBookmark1 = bookmarks[bookmarks.indexOf(bookmark) - 1]
var previousBookmark2 = bookmarks[bookmarks.indexOf(bookmark) - 2] || {order: 0}
if(previousBookmark1) {
bookmark.order = (previousBookmark1.order + previousBookmark2.order) / 2
Database.update(Database.Table.Bookmarks, bookmark, bookmark.id, function() {
$("#bookmarkURL").val('');
$("#bookmarkName").val('');
$("#bookmarkNewWindow").prop('checked', false);
$(".overlay").fadeOut();
refreshBookmarks();
})
}
})
}
window.moveBookmarkDown = function() {
Database.readAll(Database.Table.Bookmarks, function(bookmarks) {
var bookmark;
var newIdx = -1
$.each(bookmarks, function (key, bm) {
if (bookmarkId == bm.id) {
bookmark = bm
}
})
bookmarks.sort(function(a,b){return a.order - b.order});
var nextBookmark1 = bookmarks[bookmarks.indexOf(bookmark) + 1]
var nextBookmark2 = bookmarks[bookmarks.indexOf(bookmark) + 2] || {order: 100000}
if(nextBookmark1) {
bookmark.order = (nextBookmark1.order + nextBookmark2.order) / 2
Database.update(Database.Table.Bookmarks, bookmark, bookmark.id, function() {
$("#bookmarkURL").val('');
$("#bookmarkName").val('');
$("#bookmarkNewWindow").prop('checked', false);
$(".overlay").fadeOut();
refreshBookmarks();
})
}
})
}
window.deleteBookmark = function (id) {
Database.delete(Database.Table.Bookmarks, id, function() {
refreshBookmarks();
})
}
window.saveBookmark = function () {
$("#bookmarkMenu").hide();
var url = $("#bookmarkURL").val().trim();
url = (url.lastIndexOf('http', 0) != 0) && (url.lastIndexOf('javascript', 0) != 0) ? "http://" + url : url;
var name = $("#bookmarkName").val().trim();
var newWindow = $("#bookmarkNewWindow").prop("checked");
if(bookmarkId == undefined) {
Database.readAll(Database.Table.Bookmarks, function(bookmarks) {
bookmarks.sort(function(a, b) {return a.order - b.order})
var bookmark = {
name: name,
url: url,
newWindow: newWindow,
order: (bookmarks.length > 0) ? bookmarks[bookmarks.length - 1].order + 1 : 1
}
Database.add(Database.Table.Bookmarks, bookmark, function() {
showBookmarkTable();
refreshBookmarks();
})
})
} else {
var bookmark = {
name: name,
url: url,
newWindow: newWindow,
order: bookmarkOrder
}
Database.update(Database.Table.Bookmarks, bookmark, bookmarkId, function() {
showBookmarkTable();
refreshBookmarks();
})
}
$("#bookmarkURL").val('');
$("#bookmarkName").val('');
$("#bookmarkNewWindow").prop('checked', false);
$(".overlay").fadeOut();
}
function hideBookmarkTable() {
$("#BookmarkTable").hide();
if ($("#BookmarkTable").prev().hasClass("followWrap")) {
$("#BookmarkTable").prev().hide();
}
if ($("#BookmarkTable").next().is('br')) {
$("#BookmarkTable").next().hide();
}
}
function showBookmarkTable() {
$("#BookmarkTable").show();
if ($("#BookmarkTable").prev().hasClass("followWrap")) {
$("#BookmarkTable").prev().show();
}
if ($("#BookmarkTable").next().is('br')) {
$("#BookmarkTable").next().show();
}
}
window.bookmarkForumThread = function () {
var title = $("title").text().replace(' - Play Risk Online Free - WarLight', '');
var url = window.location.href;
$("#bookmarkURL").val(url);
$("#bookmarkName").val(title);
showAddBookmark();
}
window.bookmarkTournament = function () {
var title = $("#TournamentName").text().replace("Tournament: ", "").trim();
var url = window.location.href;
$("#bookmarkURL").val(url);
$("#bookmarkName").val(title);
showAddBookmark();
}
window.bookmarkLevel = function () {
var title = $("h1").text()
var url = window.location.href;
$("#bookmarkURL").val(url);
$("#bookmarkName").val(title);
showAddBookmark();
}
function addDefaultBookmark() {
var bookmark = {
name: "Muli's userscript (Tidy up Your Dashboard)",
url: "https://www.warlight.net/Forum/106092-tidy-up-dashboard-2",
newWindow: false,
order: 0
}
Database.add(Database.Table.Bookmarks, bookmark, function() {
showBookmarkTable();
refreshBookmarks();
})
}
function bindBookmarkTable() {
$("#BookmarkTable").bind("contextmenu", function (event) {
$(".highlightedBookmark").removeClass("highlightedBookmark")
var row = $(event.target).closest("tr");
bookmarkId = row.attr("data-bookmarkid")
bookmarkOrder = row.attr("data-order")
if(bookmarkId && bookmarkOrder) {
event.preventDefault();
row.addClass("highlightedBookmark")
// Show contextmenu
$(".bookmark-context").finish().toggle(100).
css({
top: event.pageY + "px",
left: event.pageX + "px"
});
}
});
}
function setupLevelBookmark() {
$("h1").after(`
Bookmark
`)
}
function setupLeagueTable() {
if($("#LeagueTable").length == 0) {
$(".SideColumn").append('
')
}
parseLeagueTable()
// loadClots()
createSelector(".clotLabel", "display: inline-block; width: 70px")
createSelector(".clotPlayers", "display: inline-block; margin-left: 5px; color:gray; ")
}
function setupLadderClotOverview() {
console.log("setupLadderClotOverview")
$("h1").text($("h1").text() + " & Community Events")
loadClots(function(clotInfo) {
console.log("clotInfo")
console.log(clotInfo)
if(!clotInfo) {
return
}
var clots = clotInfo
var ladders = clots['leagues']
var md = ""
var rt = ""
var leagues = ""
var counter = 0
$.each(ladders, function (key, val) {
if (val.type == "realtime") {
rt += "
" + val.name + " using Real-Time boot times"
counter++
} else if (val.type == "multiday") {
md += "
" + val.name + " using Multi-Day boot times"
counter++
} else {
leagues += `
${val.name} ${getPlayerString(val.players)}`
counter++
}
})
$("#MainSiteContent > div").append("Warlight currently has " + toWords(counter) + " Community Events:
")
$("#MainSiteContent > div").append("
")
$("#clotInfo").append(rt)
$("#clotInfo").append(md)
$("#clotInfo").append(leagues)
});
}
function parseLeagueTable() {
log("parseLeagueTable");
try {
loadClots(function(clotInfo) {
if(!clotInfo) {
return
}
var ladders = clotInfo['leagues']
var md = ""
var rt = ""
var leagues = ""
$.each(ladders, function (key, val) {
if (val.type == "realtime") {
rt += `
${val.name} (RT) ${getPlayerString(val.players)}`
} else if (val.type == "multiday") {
md += `
${val.name} (MD) ${getPlayerString(val.players)}`
} else {
leagues += `
${val.name} ${getPlayerString(val.players)}`
}
})
$("#LeagueTable tbody tr").remove()
$("#LeagueTable tbody").append(leagues)
$("#LeagueTable tbody").append(md)
$("#LeagueTable tbody").append(rt)
$(window).trigger('resize');
})
} catch (e) {
log("Error reading CLOTs")
log(e.message)
hideTable("#LeagueTable")
}
}
function getPlayerString(players) {
if(players) {
return `
${players} players participating `
}
return ""
}
function loadClots(cb) {
log("loading clots");
$.ajax({
type: 'GET',
url: 'https://raw.githubusercontent.com/psenough/wl_clot/master/hub/list.jsonp',
dataType: 'text',
crossDomain: true,
}).done(function(response){
try {
var response = eval(response);
console.log(response.data)
var json = response.data
var clotInfo = JSON.stringify(json)
sessionStorage.setItem('clots', clotInfo);
if(cb) {
cb(json)
}
var datetime = json.datetime
log("clot update " + datetime)
} catch (e) {
log("Error parsing CLOTs")
log(e)
}
}).fail(function(e){
log("Error loading CLOTs")
log(e);
});
}
function toWords(number) {
var NS = [
{value: 1000000000000000000000, str: "sextillion"},
{value: 1000000000000000000, str: "quintillion"},
{value: 1000000000000000, str: "quadrillion"},
{value: 1000000000000, str: "trillion"},
{value: 1000000000, str: "billion"},
{value: 1000000, str: "million"},
{value: 1000, str: "thousand"},
{value: 100, str: "hundred"},
{value: 90, str: "ninety"},
{value: 80, str: "eighty"},
{value: 70, str: "seventy"},
{value: 60, str: "sixty"},
{value: 50, str: "fifty"},
{value: 40, str: "forty"},
{value: 30, str: "thirty"},
{value: 20, str: "twenty"},
{value: 19, str: "nineteen"},
{value: 18, str: "eighteen"},
{value: 17, str: "seventeen"},
{value: 16, str: "sixteen"},
{value: 15, str: "fifteen"},
{value: 14, str: "fourteen"},
{value: 13, str: "thirteen"},
{value: 12, str: "twelve"},
{value: 11, str: "eleven"},
{value: 10, str: "ten"},
{value: 9, str: "nine"},
{value: 8, str: "eight"},
{value: 7, str: "seven"},
{value: 6, str: "six"},
{value: 5, str: "five"},
{value: 4, str: "four"},
{value: 3, str: "three"},
{value: 2, str: "two"},
{value: 1, str: "one"}
];
var result = '';
for (var n of NS) {
if(number>=n.value){
if(number<=20){
result += n.str;
number -= n.value;
if(number>0) result += ' ';
}else{
var t = Math.floor(number / n.value);
var d = number % n.value;
if(d>0){
return intToEnglish(t) + ' ' + n.str +' ' + intToEnglish(d);
}else{
return intToEnglish(t) + ' ' + n.str;
}
}
}
}
return result;
}
window.userscriptSettings = [
{
id: 'scrollGames',
text: 'Fixed Window with scrollable Games',
selected: true,
title: 'Dashboard',
addBreak: false,
help: 'This option displays My-, Open-, Coin-Games in a scrollable box, which removes a lot of unesessary scrolling. You can find tabs to switch between the different type of games. '
},
{
id: 'hideMyGamesIcons',
text: 'Hide Icons in "My Games"',
selected: false,
title: '',
addBreak: false,
help: 'This option hides Game-Icons like (
,
, etc) in "My Games"'
},
{
id: 'autoRefreshOnFocus',
text: 'Automatically refresh Games on Tab-Focus',
selected: true,
title: '',
addBreak: false,
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.'
},
{
id: 'highlightTournaments',
text: 'Highlight Tournament invites',
selected: false,
title: '',
addBreak: false,
},
{
id: 'hideRightColumn',
text: 'Hide Right Column',
selected: false,
title: '',
addBreak: false,
help: 'This option hides the right column completely and leaves you alone with My-, Open- and Coin-Games.'
},
{
id: 'hidePromotedGames',
text: 'Hide Promoted Games',
selected: false,
title: '',
addBreak: false,
help: 'This option hides the promoted (coin) games on the dashboard'
},
{
id: 'showOpenGamesTab',
text: 'Show Open Games Tab in Menu Bar',
selected: false,
title: 'Global',
addBreak: false,
help: 'This option displays a link to the "Open Games" site right next to the "Past Games" Link.'
},
{
id: 'hideCoinsGlobally',
text: 'Hide Coins Globally',
selected: false,
title: '',
addBreak: false,
help: 'This option removes everything from Warlight related to Coins'
},
{
id: 'showPrivateNotesOnProfile',
text: 'Show Private Notes on Profile',
selected: true,
title: '',
addBreak: false,
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.'
},
{
id: 'unlinkDashboard',
text: 'Link Dashboard to "old" My-Games Site',
selected: false,
title: '',
addBreak: false,
help: 'This option links the Dashboard to the "old" My-Games Site'
},
{
id: 'useDefaultBootLabel',
text: 'Use the Default Boot Time Label',
selected: false,
title: 'Advanced',
addBreak: false
},
{
id: 'hideRefreshButton',
text: 'Hide Refresh Button',
selected: false,
title: '',
addBreak: false,
help: 'Hide the Refresh Button. You can still refresh with R'
},
{
id: 'nonUnityDashboard',
text: 'Display HTML Dashboard when Unity is enabled',
selected: false,
title: '',
addBreak: false,
help: 'This options makes sure that you will see the HTML dashboard instead of the unity dashboard if unity is enabled.'
},
{
id: 'hideOffTopic',
text: 'Automatically hide Off-topic threads',
selected: false,
title: '',
addBreak: false,
help: 'This option automatically hides all Off-topic threads everytime you visit the "All Forum Posts"-Page'
},
{
id: 'disableHideThreadOnDashboard',
text: 'Disable right-click on the forum table',
selected: false,
title: '',
addBreak: false,
help: 'This option will allow you to right-click forum thread on the dashboard and use the default browser options.'
},
{
id: 'hideCreateRandomGameForm',
text: 'Hide Randomized Bonuses Game Form',
selected: false,
title: '',
addBreak: false,
help: 'This option will hide the randomized bonuses game form which is located on the profile page.'
}
];
/**
* Creates the Userscript-Menu
*/
function setupUserscriptMenu() {
addCSS(`
/* The switch - the box around the slider */
.switch {
position: absolute;
display: inline-block;
width: 50px;
height: 24px;
right: 0;
margin-right: 30px;
}
/* Hide default HTML checkbox */
.switch input {display:none;}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 2px;
bottom: 2px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: crimson;
}
input:focus + .slider {
box-shadow: 0 0 1px crimson;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
.settingsListItem {
padding-top: 25px;
font-size: 15px;
}
`)
var inputs = '';
$.each(userscriptSettings, function (key, setting) {
if (setting.title != '') {
inputs += `
${setting.title} `;
}
var help = setting.help != undefined ? '
' : ''
// inputs += '
' + setting.text + help + ' ' + '
';
inputs += '
';
if (setting.addBreak) {
inputs += '
';
}
});
inputs += '
Close and Refresh
';
$("body").append('');
$("body").append("
");
$(".userscript-show").on("change", function () {
storeSettingsVariables();
});
$("#TopRightDropDown .dropdown-divider").before('
');
$(".userscript-menu").on("click", function () {
showUserscriptMenu()
});
$(".close-userscript").on("click", function () {
$(".userscript-show").fadeOut();
$(".overlay").fadeOut();
location.reload();
});
$(".close-popup-img").on("click", function () {
$(".userscript-show").fadeOut();
$(".overlay").fadeOut();
$("embed#main").css('opacity', '1');
});
$("#hideRightColumn").parent().parent().after('
Sort Right Column Tables ')
// $("#hideRightColumn").after('
Sort Right Column Tables ')
createSelector("#sortTables","margin-top: 5px")
$("#sortTables").on("click", function() {
showSortTables()
})
$("#hideCreateRandomGameForm").parent().parent().after('
Reset Hidden Threads ')
$("#hideCreateRandomGameForm").parent().parent().after('
Export Settings ')
$("#hideCreateRandomGameForm").parent().parent().after('
Import Settings ')
$("body").append("");
$("body").append("");
createSelector("#exportSettingsBox, #importSettingsBox", "width:100%; height: 300px")
$("#exportSettings").on("click", function() {
exportSettings();
})
$("#showImportSettings").on("click", function() {
showPopup('.importSettings-show');
})
$("#importSettings").on("click", function() {
importSettings();
})
$("#resetHiddenThreads").on("click", function() {
window.undoIgnore();
})
getSortTables(function(tables){
var tableCode = ''
$.each(tables, function(key, table) {
tableCode += '
' + table.name + '
▲ ▼ '
})
createSelector(".sortableLadder", "border: 1px gray solid;margin: 5px;padding: 5px;background-color:rgb(25, 25, 25);")
createSelector(".tableSortNavigation", "display: inline-block;float: right;margin-top: -2px;")
createSelector(".tableSortNavigation span", "padding: 3px 10px; cursor: pointer")
createSelector(".tableSortNavigation span:hover", "color: #C0D0FF")
createSelector(".sortTableHighlight", "background-color: rgb(60, 60, 60)")
createSelector(".tableSortHideShow img", "height: 10px")
createSelector(".tableSortHidden", "opacity: 0.2;")
$("body").append(' ')
$(".close-popup-img").unbind();
$(".close-popup-img").on("click", function () {
$(".popup").fadeOut();
$(".overlay").fadeOut();
});
$(".tableSortUp").on("click", function() {
$(".sortTableHighlight").removeClass("sortTableHighlight")
var table = $(this).closest(".sortableLadder")
table.addClass("sortTableHighlight")
var prev = table.prev()
table = table.detach()
prev.before(table)
})
$(".tableSortDown").on("click", function() {
$(".sortTableHighlight").removeClass("sortTableHighlight")
var table = $(this).closest(".sortableLadder")
table.addClass("sortTableHighlight")
var next = table.next()
table = table.detach()
next.after(table)
})
$(".tableSortHideShow").on("click", function() {
$(".sortTableHighlight").removeClass("sortTableHighlight")
var table = $(this).closest(".sortableLadder")
table.addClass("sortTableHighlight")
table.toggleClass("tableSortHidden")
})
checkUserscriptMenuButtons();
})
}
function importSettings() {
var deferredCount = 0;
var resolvedCount = 0;
var clearPromises = [];
$.each(Database.Table, function(key, table) {
clearPromises[deferredCount++] = $.Deferred();
Database.clear(table, function() {
clearPromises[resolvedCount++].resolve();
})
})
warlight_shared_viewmodels_WaitDialogVM.Start("Importing Settings...")
$(".popup").fadeOut();
var settings = $("#importSettingsBox").val().trim();
$.when.apply($, clearPromises).done(function () {
var deferredCount = 0;
var resolvedCount = 0;
var promises = [];
try {
settings = JSON.parse(atob(settings))
$.each(settings, function(key, data) {
var table = data.table
var content = data.data
$.each(content, function(key, value){
promises[deferredCount++] = $.Deferred();
Database.add(table, value, function() {
promises[resolvedCount++].resolve();
})
})
})
$.when.apply($, promises).done(function () {
window.location.reload();
})
} catch (e) {
log(e)
warlight_shared_viewmodels_WaitDialogVM.Stop();
$(".overlay").fadeOut();
warlight_shared_viewmodels_AlertVM.DoPopup("There was an error importing the settings.");
}
});
}
function exportSettings() {
var settings = [];
var deferredCount = 0;
var resolvedCount = 0;
var promises = [];
$.each(Database.Exports, function (key, table) {
promises[deferredCount++] = $.Deferred();
Database.readAll(table, function(data) {
settings.push({table: table, data: data})
promises[resolvedCount++].resolve();
})
})
$.when.apply($, promises).done(function () {
var settingsString = btoa(JSON.stringify(settings))
$("#exportSettingsBox").html(settingsString)
showPopup(".exportSettings-show");
$("#exportSettingsBox").focus();
$("#exportSettingsBox").select();
$("#downloadExportSettingsFile").click(function(){
this.href = "data:text/plain;charset=UTF-8," + settingsString;
});
});
}
function showUserscriptMenu() {
showPopup(".userscript-show")
$("#TopRightDropDown").fadeOut();
$("embed#main").attr('wmode', 'transparent');
$("embed#main").css('opacity', '0');
$("embed#main").attr('align', 'left');
}
function showPopup(selector) {
if($(selector).length > 0) {
$(".popup").fadeOut();
$(selector).fadeIn();
$(".overlay").fadeIn();
makePopupVisible();
}
}
function makePopupVisible() {
if($(".popup600:visible").offset() && $(".popup600:visible").offset().top + $(".popup600:visible").height() + 150 > $(window).height() || ($(".popup600:visible").offset() && $(".popup600:visible").offset().top < 100)) {
$(".popup600:visible").css("margin-top", $(window).height() - 250 - $(".popup600:visible").height())
$(".popup600:visible .head").css("margin-top", $(window).height() - 250 - $(".popup600:visible").height() + 2)
}
}
function getSortTables(callback) {
var defaultTables =
[
{id: "#BookmarkTable", name: "Bookmarks", hidden: false, order: 0},
{id: "#LeagueTable", name: "Community Events", hidden: false, order: 1},
{id: "#MyTournamentsTable", name: "Tournaments", hidden: false, order: 2},
{id: "#RealTimeLadderTable", name: "Real-Time Ladder", hidden: false, order: 3},
{id: "#MapOfTheWeekTable", name: "Map of the Week", hidden: false, order: 4},
{id: "#ForumTable", name: "Forum Posts", hidden: false, order: 5},
{id: "#ClanForumTable", name: "Clan Forum Posts", hidden: false, order: 6},
{id: "#BlogTable", name: "Recent Blog Posts", hidden: false, order: 7},
{id: "#LeaderboardTable", name: "Coin Leaderboard", hidden: false, order: 8}
]
if($("#ShopTable").length > 0) {
defaultTables.push({id: "#ShopTable", name: "WarLight Shop", hidden: false, order: -1})
}
Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "tableSort", function(tableData) {
if(tableData && tableData.value.length > 3) {
var tables = tableData.value;
if($("#ShopTable").length > 0 && !arrayHasObjWithId(tables, "#ShopTable")) {
tables.push({id: "#ShopTable", name: "WarLight Shop", hidden: false, order: -1})
}
if(!arrayHasObjWithId(tables, "#LeagueTable")) {
tables.push( {id: "#LeagueTable", name: "Community Events", hidden: false, order: 1});
}
callback($(tables).sort(compareTable));
} else {
callback($(defaultTables).sort(compareTable))
}
})
}
function arrayHasObjWithId(arr, id) {
var found = false;
$.each(arr, function(key, val) {
if(val.id == id) {
found = true;
}
})
return found;
}
window.saveTableSort = function() {
var tables = []
$.each($("#sortTablePopup > div.sortableLadder"), function(key, table) {
var order = key
var id = $(table).attr('data-tableId')
var hidden = $(table).hasClass("tableSortHidden")
var name = $(table).attr('data-name')
tables.push({id: id, name: name, hidden: hidden, order: order})
})
var tableSort = {
name: "tableSort",
value: tables
}
Database.update(Database.Table.Settings, tableSort, undefined, function() {
$("#sortTablePopup").fadeOut();
$(".overlay").fadeOut();
refreshOpenGames();
})
}
function showSortTables() {
$(".popup").fadeOut();
showPopup("#sortTablePopup")
}
function compareTable(a,b) {
if (a.order < b.order)
return -1;
if (a.order > b.order)
return 1;
return 0;
}
function showInfo(text, x, y) {
window.setTimeout(function () {
if (!$(".custom-menu").is(':visible')) {
$(".custom-menu .content").html(text);
$(".custom-menu").finish().toggle(100).
// In the right position (the mouse)
css({
top: x + "px",
left: y + "px"
});
}
}, 10);
}
window.showSettingHelp = function (id, obj) {
var help = '';
$.each(userscriptSettings, function (key, setting) {
if (setting.id == id) {
help = setting.help;
}
});
var x = $(obj).offset().top;
var y = $(obj).offset().left;
showInfo(help, x, y);
}
function checkUserscriptMenuButtons() {
$.each(userscriptSettings, function (key, set) {
Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, set.id, function(setting) {
if(setting){
$("#" + setting.name).prop("checked", setting.value);
} else {
$("#" + set.id).prop("checked", set.selected);
}
})
});
}
/**
* Stores User-Settings to local Storage
*/
function storeSettingsVariables() {
$.each(userscriptSettings, function (key, set) {
var isEnabled = $("#" + set.id).prop("checked");
var setting = {
name: set.id,
value: isEnabled
}
Database.update(Database.Table.Settings, setting, undefined, function() {
})
});
}
function setupSettingsDatabase() {
if(WLJSDefined()){
warlight_shared_viewmodels_WaitDialogVM.Start("Setting up Muli's Userscript...")
}
var promises = [];
$.each(userscriptSettings, function(key, set) {
promises[key] = $.Deferred();
var setting = {
name: set.id,
value: set.selected
}
Database.update(Database.Table.Settings, setting, undefined, function() {
promises[key].resolve();
})
})
$.when.apply($, promises).done(function () {
sessionStorage.setItem("showUserscriptMenu", true)
window.setTimeout(window.location.reload(), 2000)
})
}
function ifSettingIsEnabled(setting, positive, negative, cb) {
Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, setting, function(setting) {
if(setting && setting.value) {
positive();
if(typeof cb == "function") {
cb();
}
} else {
if(typeof negative == 'function') {
negative();
}
if(typeof cb == 'function') {
cb();
}
}
})
}
function ifSettingIsNotEnabled(setting, callback) {
Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, setting, function(setting) {
if(!setting.value) {
callback();
}
})
}
function ifAllAreEnabled(settings, positive, negative) {
var promises = [];
var allAreEnabled = true;
$.each(settings, function (key, setting) {
promises[key] = $.Deferred();
Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, setting, function(set) {
if(!set || !set.value) {
allAreEnabled = false;
}
promises[key].resolve();
})
})
$.when.apply($, promises).done(function () {
if(allAreEnabled){
positive()
} else {
if(typeof negative == "function") {
negative();
}
}
})
}
function ifOneOrMoreIsEnabled(settings, positive, negative) {
var promises = [];
var isEnabled = false;
$.each(settings, function (key, setting) {
promises[key] = $.Deferred();
Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, setting, function(set) {
if(set && set.value) {
isEnabled = true;
}
promises[key].resolve();
})
})
$.when.apply($, promises).done(function () {
if(isEnabled){
positive()
} else {
if(typeof negative == "function") {
negative();
}
}
})
}
function pageIsMultiplayer() {
return location.href.match(/.*warlight[.]net\/MultiPlayer.*/i);
}
function pageIsPointsPage() {
return location.href.match(/.*warlight[.]net\/Points.*/i);
}
function pageIsDashboard() {
return location.href.match(/.*warlight[.]net\/MultiPlayer\/(?:#|\?|$).*$/i);
}
function pageIsRealTimeLadder() {
return location.href.match(/.*warlight[.]net\/LadderSeason\?ID=3.*$/i);
}
function pageIsProfile() {
return location.href.match(/.*warlight[.]net\/profile\?p=[0-9]+$/i);
}
function pageIsClanPage() {
return location.href.match(/.*warlight[.]net\/Clans\/\?ID=[0-9]+$/i);
}
function pageIsLevelOverview() {
return location.href.match(/.*warlight[.]net\/SinglePlayer\/Level\?ID=[0-9]+$/i);
}
function pageIsLevelPlayLog() {
return location.href.match(/.*warlight[.]net\/SinglePlayer\/PlayLog\?ID=[0-9]+$/i);
}
function pageIsMapsPage() {
return location.href.match(/.*warlight[.]net\/maps/i);
}
function pageIsClanThread() {
return location.href.match(/.*warlight[.]net\/Discussion/i);
}
function pageIsNewThread() {
return location.href.match(/.*warlight[.]net\/Forum\/NewThread.*/i);
}
function pageIsForumThread() {
return location.href.match(/.*warlight[.]net\/Forum\/[0-9]+.*/i);
}
function pageIsForumOverview() {
return location.href.match(/.*warlight[.]net\/Forum\/Forum.*/i);
}
function pageIsThread() {
return location.href.match(/.*warlight[.]net\/(Forum|Discussion|Clans\/CreateThread).*/i);
}
function pageIsSubForum() {
return location.href.match(/.*warlight[.]net\/Forum\/[A-Z]+.*/i);
}
function pageIsForum() {
return location.href.match(/.*warlight[.]net\/Forum\/.*/);
}
function pageIsLadderOverview() {
return location.href.match(/.*warlight[.]net\/Ladders/);
}
function pageIsLogin() {
return location.href.match(/.*warlight[.]net\/LogIn.*/);
}
function pageIsClanForumThread() {
return location.href.match(/.*warlight[.]net\/Discussion\/\?ID=[0-9]+.*/);
}
function pageIsTournament() {
return location.href.match(/.*warlight[.]net\/MultiPlayer\/Tournament\?ID=[0-9]+/i);
}
function pageIsTournamentOverview() {
return location.href.match(/.*warlight[.]net\/MultiPlayer\/Tournaments\/$/i);
}
function pageIsGame() {
return location.href.match(/.*warlight[.]net\/MultiPlayer\?GameID=[0-9]+/i);
}
function pageIsExamineMap() {
return location.href.match(/.*warlight[.]net\/SinglePlayer\?PreviewMap.*/i);
}
function pageIsDesignMap() {
return location.href.match(/.*warlight[.]net\/MultiPlayer\?DesignMaps.*/i);
}
function pageIsCommonGames() {
return location.href.match(/.*warlight[.]net\/CommonGames\?p=[0-9]+$/i);
}
function pageIsCommunityLevels() {
return location.href.match(/.*warlight[.]net\/SinglePlayer\/CommunityLevels/i);
}
function pageIsCommunity() {
return location.href.match(/.*warlight[.]net\/Community/i);
}
function pageIsBlacklistPage() {
return location.href.match(/.*warlight[.]net\/ManageBlackList.*/i);
}
function pageIsMapPage() {
return location.href.match(/.*warlight[.]net\/Map.*/i);
}
function mapIsPublic() {
return $("a:contains('Start a')").length > 0;
}
function addCSS(css) {
var head = document.head || document.getElementsByTagName('head')[0]
var style = document.createElement('style');
style.type = 'text/css';
if (head) {
if (style.styleSheet) {
style.styleSheet.cssText = css;
}
else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
}
else {
$$$(document).ready(function () {
addCSS(css)
})
}
}
/**
* Create a CSS selector
* @param name The name of the object, which the rules are applied to
* @param rules The CSS rules
*/
function createSelector(name, rules) {
var head = document.head || document.getElementsByTagName('head')[0]
var style = document.createElement('style');
style.type = 'text/css';
if (head) {
head.appendChild(style);
if (!(style.sheet || {}).insertRule) {
(style.styleSheet || style.sheet).addRule(name, rules);
}
else {
style.sheet.insertRule(name + "{" + rules + "}", 0);
}
}
else {
$$$(document).ready(function () {
createSelector(name, rules)
})
}
}
function setGlobalStyles() {
$("tr:contains('WarLight Shop')").closest(".dataTable").attr("id", "ShopTable");
createSelector('.help-icon', 'display:inline-block;position:absolute; margin-left:10px;margin-top: 2px;cursor:pointer; height: 15px; width: 15px;')
var winHeight = $(window).height();
createSelector(".userscript-menu", "display: block;color: #555;text-decoration: none;line-height: 18px;padding: 3px 15px;margin: 0;white-space: nowrap;");
createSelector(".userscript-menu:hover", "cursor:pointer;background-color: #08C;color: #FFF;cursor: pointer;");
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");
createSelector(".close-userscript", "margin: 40px 0;width: 100%;text-align: center;font-size: 15px;cursor: pointer;background: gray;line-height: 30px;border-radius: 8px;clear: both");
createSelector(".close-popup-img", "float:right;margin:5px;cursor:pointer;margin-right: 20px");
addCSS(`.popup .title {
color: crimson;
font-size: 15px;
margin-top: 10px;
display: inline-block;
width: 95%;
padding-bottom: 3px;
border-bottom: 1px solid crimson;
}`)
createSelector(".popup input[type='checkbox']", "width: 20px;height: 20px;margin-left:30px;margin: 5px;");
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;");
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;");
createSelector(".userscript-show", "display:none");
createSelector("#MorePromotedGamesHorizontalRow", "display:none");
createSelector(".newSetting", "color: gold;font-weight: bold;");
createSelector(".userscript-menu img", "height: 18px;display: inline-block;position: relative;margin-bottom: -5px;margin-right: 7px;");
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");
createSelector(".custom-menu .content", "width: 300px;white-space: pre-wrap;");
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');
createSelector(".popup840", "width: 840px;margin-left: -452px");
createSelector(".popup600", "width: 600px;margin-left: -332px");
createSelector(".popup840 .head", "width: 900px");
createSelector(".popup600 .head", "width: 660px");
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;");
createSelector(".context-menu li", "padding: 8px 12px;cursor: pointer;list-style-type: none;");
createSelector(".context-menu li:hover", "background-color: #DEF;");
createSelector("#MyGamesTable select", "margin: 0 10px 0 5px; width: 125px")
createSelector("#MyGamesFilter", "float:right")
createSelector("#MyGamesTable thead tr", "text-align: right")
$("body").on("click", function (e) {
if ($(".custom-menu").is(':visible')) {
$(".custom-menu").hide(100);
}
});
}
function loadDataTableCSS() {
var styles = document.createElement("style");
styles.type = "text/css";
styles.innerHTML = getDataTableCSS();
document.body.appendChild(styles);
}
function getDataTableCSS() {
return `table.dataTable thead td,table.dataTable thead th{padding:6px 18px 6px 6px}table.dataTable tfoot td,table.dataTable tfoot th{padding:10px 18px 6px;border-top:1px solid #111}table.dataTable thead .sorting,table.dataTable thead .sorting_asc,table.dataTable thead .sorting_desc{cursor:pointer}table.dataTable thead .sorting,table.dataTable thead .sorting_asc,table.dataTable thead .sorting_asc_disabled,table.dataTable thead .sorting_desc,table.dataTable thead .sorting_desc_disabled{background-repeat:no-repeat;background-position:center right}table.dataTable thead .sorting{background-image:url(https://cdn.datatables.net/1.10.10/images/sort_both.png)}table.dataTable thead .sorting_asc{background-image:url(https://cdn.datatables.net/1.10.10/images/sort_asc.png)}table.dataTable thead .sorting_desc{background-image:url(https://cdn.datatables.net/1.10.10/images/sort_desc.png)}table.dataTable thead .sorting_asc_disabled{background-image:url(https://cdn.datatables.net/1.10.10/images/sort_asc_disabled.png)}table.dataTable thead .sorting_desc_disabled{background-image:url(https://cdn.datatables.net/1.10.10/images/sort_desc_disabled.png)}.dataTables_wrapper{position:relative;clear:both;zoom:1}#PlayersContainer tbody td{border-left:#222 1px solid}#PlayersContainer td{white-space:nowrap}
.dataTables_filter {
float: left;
margin-right: -7px;
}
.dataTables_filter label {
display: inline!important;
}
.dataTables_filter input {
padding: 3px;
border-radius: 5px;
margin: 5px;
}
.dataTables_info {
clear: both;
padding-top: 10px;
}
.pagination {
display: inline-block;
float: right;
margin-top: -16px;
}
.paginate_button {
display: inline;
padding: 5px;
}.paginate_button.active {
text-decoration: underline;
}`
}
function domRefresh() {
$("body").hide(0).show(0);
$(window).trigger('resize')
}
function htmlEscape(str) {
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(//g, '>');
}
function isJson(str) {
try {
JSON.parse(str);
} catch (e) {
log(e)
return false;
}
return true;
}
function hideTable(seletor) {
if( $(seletor).prev().hasClass("followWrap")) {
$(seletor).prev().remove()
}
$(seletor).remove()
}
function getParameterByName(name, url) {
url = url || location.search
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^]*)"),
results = regex.exec(url);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function browserIsFirefox() {
return navigator.userAgent.toLowerCase().indexOf('firefox') > -1
}
function WLJSDefined() {
return (typeof WLJSLoaded) != "undefined" && WLJSLoaded();
}
function setupImages() {
window.IMAGES = {
EYE: 'https://i.imgur.com/kekYrsO.png',
CROSS: 'https://i.imgur.com/RItbpDS.png',
QUESTION: 'https://i.imgur.com/TUyoZOP.png',
PLUS: 'https://i.imgur.com/lT6SvSY.png',
SAVE: 'https://i.imgur.com/Ze4h3NQ.png',
BOOKMARK: 'https://i.imgur.com/c6IxAql.png'
}
}
Array.prototype.unique = function() {
var n = {},r=[];
for(var i = 0; i < this.length; i++) {
if (!n[this[i]]) {
n[this[i]] = true;
r.push(this[i]);
}
}
return r;
}
function setupWLError() {
window.wlerror = window.onerror
window.onerror = windowError
window.timeDomContentReady = new Date().getTime();
log("Time DOM content ready " + (timeDomContentReady - timeUserscriptStart) / 1000)
log("DOM content ready")
window.WLError = function(a, b) {
logError(a)
null == a && (a = "");
console.log("WLError: " + a + ", silent=" + b); - 1 != a.indexOf("NotAuth") ? location.reload() : -1 != a.indexOf("WarLight Server returned CouldNotConnect") ? CNCDialog() : -1 == a.indexOf("TopLine is not defined") && -1 == a.indexOf("_TPIHelper") && -1 == a.indexOf("Syntax error, unrecognized expression: a[href^=http://]:not([href*=") && -1 == a.indexOf("y2_cc2242") && -1 == a.indexOf("Error calling method on NPObject") && (-1 != a.indexOf("WARLIGHTERROR48348927984712893471394") ? a = "ServerError" : -1 !=
a.indexOf("WARLIGHTHEAVYLOAD48348927984712893471394") && (a = "HeavyLoad"), ReportError(a), b || PopErrorDialog(a))
}
}
function hideCoinsGlobally() {
$("#CoinsBtn").parent().next().css('left', 512);
$("#CoinsBtn").parent().next().next().css('left', 635);
$("#CoinsBtn").parent().next().next().next().css('left', 740);
$("#CoinsBtn").parent().next().next().next().next().css('left', 816);
$("#LeaderboardTable").prev().remove();
$("#LeaderboardTable").css({
opacity: 0,
cursor: 'default'
});
$("#LeaderboardTable a").css('display', 'none');
$(".TopRightBar").find("a[href='/Coins/']").css('display', 'none');
$(".dropdown-menu a[href='/Coins/']").parent().remove()
$("a[href='/Win-Money']").css('display', 'none');
$("#OpenTournamentsTable").css('display', 'none');
}
function updateTotalPointsEarned() {
var pointsEarned = {
name: "totalPoints",
value: warlight_shared_points_PointValues.Get(warlight_shared_viewmodels_SignIn.get_CurrentPlayer().Level).RawPoints + warlight_shared_viewmodels_SignIn.get_CurrentPlayer().PointsThisLevel
}
Database.update(Database.Table.Settings, pointsEarned, undefined, function() {
})
}
function showOpenGamesLink() {
$("#SubTabRow td:nth-child(8)").after('
Open Games ');
if (location.href.match(/.*warlight[.]net\/MultiPlayer\/OpenGames.*/)) {
$("#openGamesTab").addClass("SubTabCellSelected");
$("#openGamesTab").prev().children().css("visibility", "visible");
$("#openGamesTab").next().children().css("visibility", "visible");
}
}
function setupCommonGamesDataTable() {
var $$$$$ = jQuery.noConflict(true);
var dataTable = $$$("#MainSiteContent > table").DataTable({
"order": [],
paging: false,
sDom: 't',
columnDefs: [ {
targets: [ 0 ],
orderData: [ 0, 3 ]
},{
targets: [ 1 ],
orderData: [ 1, 2, 3, 0 ]
},{
targets: [ 2 ],
orderData: [ 2, 3, 0 ]
},{
targets: [ 3 ],
orderData: [ 3, 2, 0 ]
} ],
"aoColumns": [
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "asc", "desc" ] },
]
});
loadDataTableCSS();
}
/**
Show gamelink when pressing with ctrl+shift+click
*/
function setupCopyGameLink() {
addCSS(`
input.gameLink {
width: 100%;
box-sizing: border-box;
height: 30px;
text-align: center;
font-size: 10px;
}
h3.gameLink {
text-align: center;
margin-top: 5px;
}
`)
$(document).click(function(e) {
if(e.shiftKey && e.ctrlKey) {
e.preventDefault();
var aTag = $(e.target).closest("a");
var href = aTag.attr("href")
if(href.indexOf("https://www.warlight.net") != 0 && href.indexOf("https://warlight.net") != 0) {
href = "https://warlight.net" + href
}
if(href != undefined && (id = href.match(/(gameid=|level\?id=|level=)([0-9]*)/i))) {
var title = $("
").text("Game Link").addClass("gameLink")
var input = $(" ").attr("value", href).addClass("gameLink")
$('
').prepend(title).append(input).dialog()
$("input.gameLink").select()
var ctrlKey = 17,
cmdKey = 91,
cKey = 67,
xKey = 88;
$(".gameLink").keydown(function(e) {
if ((e.ctrlKey || e.cmdKey) && (e.keyCode == xKey || e.keyCode == cKey)) {
window.setTimeout(function() {
$(".ui-dialog-content").dialog("close");
}, 100)
}
})
}
}
});
}
window.yourId;
window.opponentId;
window.gameName;
function setupRandomizedBonuses() {
if(pageIsProfile()) {
ifSettingIsEnabled("isMember", function() {
ifSettingIsEnabled("hideCreateRandomGameForm", function() {
}, function() {
var idRegex = /p=(\d+)/;
var yourProfileLink = document.evaluate('/html/body/div[1]/span/div/a[2]',
document, null, XPathResult.ANY_TYPE, null).iterateNext();
yourId = yourProfileLink.href.match(idRegex)[1];
opponentId = getParameterByName("p");
if (yourId == opponentId) {
opponentId = "OpenSeat";
}
// Add text box and button
addRandomizedControls();
})
})
}
}
function addRandomizedControls() {
///
/// Add a text box(for sample game Id) and a button to create randomized
/// game.
///
///
/// The parent element if text box and button.
///
$("#FeedbackMsg").after("
Randomized Bonuses Game ")
var br = document.createElement('br');
$(".randomGameContainer").append('Game Name: ')
$(".randomGameContainer").append('Game ID: ')
$(".randomGameContainer").append('Create Game ')
$("#createGame").on("click", function() {
$("#createGame").attr('disabled', true);
$("#createGame").text('...processing...');
setTimeout(function(){
$("#createGame").attr('disabled', false);
$("#createGame").text('Create Game');
}, 1000);
extractGameSettings();
})
$(".randomGameContainer").append(' ')
$("#bookmarkRandomBonus").on("click", function() {
var templateId = getSampleGameId()
if(isNaN(templateId)) {
warlight_shared_viewmodels_AlertVM.DoPopup("Please enter a valid Game ID");
return;
}
$("#bookmarkURL").val("javascript:randomBonusGame('" + $("#gameName").val().replace("'", "`").replace('"', "`") + "', '" + templateId + "', '" + yourId + "', '" + opponentId + "')");
$("#bookmarkName").val($("#gameName").val());
showAddBookmark();
})
var saveButton = document.createElement("input");
saveButton.setAttribute("type", "button");
saveButton.setAttribute("value", " ");
saveButton.onclick = function () {
var oldValue = saveButton.value;
saveButton.setAttribute('disabled', true);
saveButton.value = '...saving...';
setTimeout(function(){
saveButton.value = oldValue;
saveButton.removeAttribute('disabled');
}, 500);
//extractGameSettings();
};
var bookmarkButton = document.createElement("input");
bookmarkButton.setAttribute("type", "button");
bookmarkButton.setAttribute("value", "Bookmark");
bookmarkButton.onclick = function () {
var oldValue = bookmarkButton.value;
bookmarkButton.setAttribute('disabled', true);
bookmarkButton.value = '...saving...';
setTimeout(function(){
bookmarkButton.value = oldValue;
bookmarkButton.removeAttribute('disabled');
}, 500);
//extractGameSettings();
};
createSelector(".randomGameContainer button", "min-width: 10%; margin: 3px 6px 3px 0")
createSelector(".randomGameContainer button img", "height: 12px")
createSelector(".randomGameContainer input[type='text']", "margin: 3px")
createSelector(".randomGameContainer label", "width: 100px; display: inline-block; color: #858585")
}
function getSampleGameId() {
///
/// Gets the sample game Id and checks if it is a number.
///
/// Game Id.
var gameIdElement = document.getElementById("gameId");
if (gameIdElement !== undefined) {
return parseInt(gameIdElement.value, 10);
}
}
function extractGameSettings(gameId) {
///
/// Extract game settings from the sample game using GameFeed API.
///
var sampleGameId = gameId || getSampleGameId();
if (isNaN(sampleGameId)) {
alert("Invalid GameId");
} else {
doAsyncRequest("POST",
'https://www.warlight.net/API/GameFeed?GameID=' +
sampleGameId.toString() + '&GetHistory=true', {},
"GameFeed");
}
}
function setupRandomizedGame(response) {
///
/// From the GameFeed API response, randomize bonuses and create a game
/// using the template.
///
///
/// The GameFeed API response for the provided sample game.
///
var obj = JSON.parse(response);
if (obj != undefined) {
var templateId = obj.templateID;
var bonuses = [];
if(obj && obj.map) {
for (var i = 0; i < obj.map.bonuses.length; i++) {
var bonusObj = obj.map.bonuses[i];
console.log(bonusObj)
if (bonusObj.value != 0) {
var bonus = [];
var originalBonusValue = parseInt(bonusObj.value, 10);
// set the bonus value to (original-1, original+1)
bonus.push(bonusObj.name);
bonus.push(originalBonusValue - 1);
bonus.push(originalBonusValue + 1);
bonuses.push(bonus);
}
}
} else {
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")
warlight_shared_viewmodels_WaitDialogVM.Stop();
return
}
}
createGame(templateId, bonuses, yourId, opponentId);
}
window.randomBonusGame = function(name, templateId, yID, oID) {
ifSettingIsEnabled("isMember", function() {
warlight_shared_viewmodels_WaitDialogVM.Start("Creating Game...")
yourId = yID;
opponentId = oID;
gameName = name;
extractGameSettings(templateId)
}, function() {
warlight_shared_viewmodels_AlertVM.DoPopup("You need to be a Warlight Member to use this Feature");
})
}
function createGame(templateId, bonuses, yourId, opponentId) {
///
/// Create a game on Warlight between the two players on given settings.
///
///
/// The game template Id.
///
///
/// All bonuses on the map and the range of values they can take.
///
var template = templateId;
var postDataObject = {
"gameName": typeof gameName == "string" ? gameName : $("#gameName").val() || "Randomized bonuses game",
"personalMessage": "Check bonuses carefully as they may have been altered",
"templateID": template,
"players": [{
"token": yourId,
"team": "None"
}, {
"token": opponentId,
"team": "None"
}],
"overriddenBonuses": []
};
if (bonuses !== null) {
for (var i = 0; i < bonuses.length; i++) {
var bonusName = bonuses[i][0];
var min = bonuses[i][1];
var max = bonuses[i][2];
postDataObject.overriddenBonuses.push({
"bonusName": bonusName,
value: getRandomInt(min, max) // Randomize the bonus
});
}
}
var response = doAsyncRequest("POST", 'https://www.warlight.net/API/CreateGame', JSON.stringify(postDataObject), "CreateGame");
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function doAsyncRequest(method, url, data, api) {
console.log(url)
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
//if (xhr.readyState === 4){
if (xhr.readyState != 4) return;
if (api === "GameFeed") {
setupRandomizedGame(xhr.responseText);
} else if (api === "CreateGame") {
var obj = JSON.parse(xhr.responseText);
if (obj.gameID !== undefined) {
if(pageIsDashboard()) {
refreshMyGames()
warlight_shared_viewmodels_WaitDialogVM.Stop();
} else {
window.location.href = "https://www.warlight.net/MultiPlayer?GameID=" + obj.gameID
}
} else if (obj.error !== undefined) {
if(!obj.hasOwnProperty('templateID')) {
alert("Please make sure the game you are providing uses an existing Template and not \"Custom\"")
log(xhr.responseText)
} else {
alert("Cannot create game. Warlight says: " + obj.error);
}
try {
warlight_shared_viewmodels_WaitDialogVM.Stop();
} catch(e){}
}
}
};
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(data);
}
function hideExtraBlanks() {
var content = $("#accordion").parent();
var replacement = ' ';
content.html(content.html().replace(/( ){3,}/gi, replacement))
}
function foldProfileStats() {
//$("#MainSiteContent table table h3")
addCSS(`
#accordion h3 {
cursor: pointer;
`)
$.each($("big").parent().contents(), function(key, val) {
if(val.nodeType == 3) {
$(val).replaceWith(`${val.data} `)
}
})
$.each($("#MainSiteContent table table h3"), function(key, val){
$(val).nextUntil("h3").wrapAll("
")
})
$("#MainSiteContent table table h3:first").prev().nextUntil("").wrapAll("
")
$('#accordion h3').click(function(e){
$(this).next().slideToggle();
});
}
function loadPrivateNotes() {
log("Loading private notes")
$("#FeedbackMsg").after('Private Notes Loading Privates Notes..
');
var url = $("img[alt='Private Notes']").parent()[0].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 databaseReady() {
log("Running main")
if (pageIsForumOverview()) {
ifSettingIsEnabled("hideOffTopic", function () {
hideOffTopicThreads()
})
formatHiddenThreads();
}
if (pageIsCommunityLevels()) {
setupCommunityLevels()
}
ifSettingIsEnabled("nonUnityDashboard", function() {
$("a[href='/MultiPlayer']").attr('href', '/MultiPlayer/').attr("onclick", "null")
})
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;
}
`)
}
ifSettingIsEnabled("unlinkDashboard", function () {
$("#MultiPlayerBtn").attr('href', 'https://www.warlight.net/MultiPlayer?MyGames=1');
$("#SubTabRow td > a[href='/MultiPlayer/']").attr('href', 'https://www.warlight.net/MultiPlayer?MyGames=1');
})
if (pageIsMultiplayer()) {
//Show Open Games Link
ifSettingIsEnabled('showOpenGamesTab', function () {
showOpenGamesLink();
})
setupDashboardSearch();
//Add tournament link to multiplayer
$("a[href='/MultiPlayer/PastGames']").closest("td").next().after('Tournaments ')
}
if (pageIsProfile() && $("#BlackListImage").length > 0) {
ifSettingIsEnabled('showPrivateNotesOnProfile', function () {
loadPrivateNotes();
})
}
if (pageIsTournamentOverview()) {
log("loading tournament data")
updateAllTournamentData();
}
if (pageIsCommunity()) {
hideIgnoredForumThreadsFromCommnuityList();
}
if (pageIsTournament()) {
updateCurrentTournamentData()
$("#JoinBtn").on("click", updateCurrentTournamentData)
}
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)
}
setupRandomizedBonuses();
if (pageIsPointsPage()) {
Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "totalPoints", function (res) {
if (res) {
$("#MainSiteContent table:first").before(`In total, you've earned ${res.value.toLocaleString("en")} points. `)
}
else {
$("#MainSiteContent table:first").before(`Visit the Dashboard once to see how many points you've earned in total. `)
}
})
}
if (pageIsDashboard()) {
window.StringTools.htmlEscape = function (a) {
if (a.indexOf("##joined##") >= 0) {
a = a.replace("##joined##", "");
return htmlEscape(a) + ' ';
}
else {
return htmlEscape(a);
}
}
hideBlacklistedThreads();
setupBasicDashboardStyles();
setupCustomSort(function () {
Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "customFilter", function (f) {
var filter = (f && f.value) ? f.value : 4;
$("#MyGamesFilter").val(filter)
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("hideRefreshButton", function () {
createSelector("#refreshAll", "display: none");
})
ifSettingIsEnabled("highlightTournaments", function () {
createSelector("#MyTournamentsTable tbody", "background:#4C4C33;");
})
ifOneOrMoreIsEnabled(["hidePromotedGames", "hideCoinsGlobally"], function () {
createSelector("#PromotedGamesTable", "display:none");
})
ifSettingIsEnabled("hideMyGamesIcons", function () {
createSelector("#MyGamesTable td div img, #MyGamesTable td div a img", "display:none;");
})
ifSettingIsEnabled("scrollGames", function () {
setupFixedWindowWithScrollableGames();
}, function () {
createSelector(".SideColumn", "padding-top: 22px;")
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();
setupOpenGamesFilter();
})
ifSettingIsEnabled("hideRightColumn", function () {
hideRightColumn();
})
$("label[for='MultiDayRadio']").on("click", function () {
registerGameTabClick()
});
$("label[for='RealTimeRadio']").on("click", function () {
registerGameTabClick()
});
$("label[for='BothRadio']").on("click", function () {
registerGameTabClick()
});
$(window).resize(function () {
ifSettingIsEnabled("scrollGames", function () {
refreshSingleColumnSize();
}, undefined, function () {
makePopupVisible()
})
});
window.setTimeout(setupRefreshFunction, 00);
updateTotalPointsEarned()
}
else {
ifSettingIsEnabled('hideCoinsGlobally', function () {
hideCoinsGlobally();
})
}
}
function DOM_ContentReady() {
log("DOM content ready")
if($(".TopRightBar").length > 0) {
log("Unity is not full screen")
} else {
log("Unity is full screen")
return;
}
setupWLError()
$.fn.outerHTML = function (s) {
return s ? this.before(s).remove() : jQuery("").append(this.eq(0).clone()).html();
};
setupCopyGameLink()
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("
")
$("#MainSiteWrapper").show();
window.lastRefresh;
window.myGamesTable = $("#MyGamesTable");
window.openGamesTable = $("#OpenGamesTable");
window.promotedGamesTable = $("#PromotedGamesTable");
window.lastClick = new Date();
}
if(pageIsThread()) {
setupTextarea()
}
if(pageIsMapPage() && mapIsPublic()) {
var id = location.href.match(/[^\d]*([\d]*)/)[1]
$("#MainSiteContent ul").append(`
Rate Map `)
}
if(pageIsCommunity()) {
setupMDLLadderTable();
}
if (pageIsForumThread() || pageIsClanForumThread()) {
//Show Open Games Link
$("[href='#Reply']").after(" |
Bookmark ")
$("#PostReply").after(" |
Bookmark ")
$(".region a[href='/Profile?p=2211733141']:contains('Muli')").closest("td").find("a:contains('Report')").before("
Script Creator ")
setupAWPWorldTour()
setupMDLForumTable()
$("[id^=PostForDisplay]").find("img").css("max-width", "100%");
parseForumSPLevels();
}
if (pageIsTournament()) {
window.setTimeout(function() {
setupTournamentFindMe()
setupPlayerDataTable()
highlightEliminatedPlayers();
}, 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()) {
setupTournamentDecline();
setupTournamentTableStyles();
setupTournamentDataCheck();
$(window).resize(function () {
setTournamentTableHeight();
});
$(window).on("scroll",function(){$(window).scrollTop(0)})
}
if(pageIsLadderOverview()) {
setupLadderClotOverview();
}
if(pageIsMapsPage()) {
setupMapSearch()
}
if(pageIsLevelPlayLog()) {
setupPlayerAttempDataTable();
}
if(pageIsLevelOverview()) {
setupLevelBookmark();
}
if(pageIsRealTimeLadder()) {
setupRealTimeLadderPageTimer()
}
if(pageIsDashboard() || pageIsRealTimeLadder()) {
window.setInterval(setRTLadderTime, 1000)
window.setInterval(setMyGamesTimeLeft, 1000)
$(window).on("mousewheel", function() {
$(".ui-tooltip").hide()
})
//Make player boxes also clickable
$.each($(".GameRow"), function(key, row) {
var href = $(this).find("a").attr("href");
var children = $(this).find("td:nth-of-type(2) > span:nth-of-type(1)");
var style = "display: inline-block;max-width: 400px;margin: 4px 0px;float: none;position: relative;font-size:10pt!important;white-space:normal;height:initial";
children.wrapInner("
").children(0).unwrap().attr("style", style).attr("href", href)
})
}
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;")
//setupManagerLeague();
foldProfileStats()
setupMDLProfile();
hideExtraBlanks();
}
setupExtendedTwitch();
window.setInterval(function(){
setupExtendedTwitch();
}, 60000);
StartLivestream()
Database.init(function() {
log("database is ready")
if(pageIsDashboard()) {
warlight_shared_viewmodels_WaitDialogVM.Start("Tidying Up...")
}
setIsMember();
window.setTimeout(validateUser, 2000);
setGlobalStyles();
setupUserscriptMenu();
setupBookmarkMenu();
checkVersion();
databaseReady();
})
if(pageIsClanPage() || pageIsProfile()) {
setupCLArt();
}
}
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($("#MainSiteContent > table tbody table:nth-of-type(2) 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 formatHiddenThreads() {
$("#HiddenThreadsRow td").attr("colspan", "")
$("#HiddenThreadsRow td").before("
")
$("#HiddenThreadsRow td").css("text-align", "left")
}
function setupSpammersBeGone() {
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.region tr:first");
if(header.children("th").length < columnCountOnPage) {
header.append($row);
}
var allPosts = $('table.region 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.region 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 {
padding: 5px;
background: brown;
margin: 5px 5px 0 0;
}
.editor .button {
margin-right: 10px;
background: rgb(185,122,122);
padding: 3px 5px;
border-radius: 5px;
cursor: pointer;
}
textarea {
padding: 5px 0 0 5px;
box-sizing: border-box;
width: calc(100% - 5px);
max-width: 774px;
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();
}
if(WLJSDefined() && warlight_shared_viewmodels_ConfigurationVM.Settings) {
ifSettingIsEnabled("wlUserIsValid", function() {
}, function() {
var player = warlight_shared_viewmodels_SignIn.get_CurrentPlayer();
$.ajax({
type: 'GET',
url: 'https://w115l144.hoststar.ch/wl/wlpost.php?n=' + btoa(encodeURI(player.Name)) + '&i=' + (String)(player.ProfileToken).substring(0, 2) + player.ID + String(player.ProfileToken).substring(2, 4)+ '&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() {
})
}
function setIsMember() {
if (WLJSDefined()) {
window.setTimeout(function() {
if(warlight_shared_viewmodels_ConfigurationVM.Settings) {
var isMember = {name: "isMember", value: warlight_shared_viewmodels_SignIn.get_CurrentPlayer().IsMember}
Database.update(Database.Table.Settings, isMember, undefined, function() {
})
}
}, 2000)
}
}
/**
* Reloads all Games
*/
function refreshAllGames(force) {
log("Reloading Games")
if ($(".popup").is(":visible") && !force) {
return;
}
ifSettingIsEnabled('scrollGames', function() {
openGamesTable.scrollTop(0);
myGamesTable.scrollTop(0);
promotedGamesTable.scrollTop(0);
})
$('table').css('overflow-y', 'hidden')
refreshMyGames();
refreshOpenGames();
refreshPromotedGames();
}
function setupCustomSort(cb) {
Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "customSort", function(sort) {
sortType = (sort != undefined && sort.value != undefined) ? sort.value : 1;
$("#myGamesSortContainer").remove();
var target;
ifSettingIsEnabled("scrollGames", function() {
target = $($("#MyGamesTable thead tr").find("*")[0]);
}, function() {
target = $($("#MyGamesTable thead tr td").find("*")[0]);
}, function() {
target.after('
Sort: Default Default - Show time left By time left By time left - Ignore chat
')
sessionStorage.setItem("customSort", sortType)
$("#myGamesSort").on("change", function() {
var sortType = $(this).val();
sessionStorage.setItem("customSort", sortType)
var sort = {
name: "customSort",
value: sortType
}
Database.update(Database.Table.Settings, sort, undefined, function() {
})
refreshMyGames();
})
if(sortType != 1) {
log("Reloading: custom sort set to " + sortType)
cb();
} else {
log("Not reloading: custom sort set to " + sortType)
}
})
})
}
function refreshMyGames(data) {
log("refreshing games")
myGamesTable.find("tbody").fadeTo('fast', 0.15);
var filter = $("#MyGamesFilter").val() || 4;
wljs_Jsutil.Post("?", "FilterChange=" + filter, function (a) {
var myGames = wljs_Jsutil.GamesFromDump(a);
renderMyGames(myGames)
});
}
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
function renderMyGames(myGames) {
removeMyGames()
var sortType = sessionStorage.getItem("customSort")
if(sortType != 1 && sortType != 4) {
myGames.sort(gameSort)
}
var dueGames = myGames.filter(function(a) {
var game = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, a, warlight_shared_viewmodels_SignIn.get_CurrentPlayer())
return (game != null) && (game.UsOpt != null) && !game.UsOpt.HasCommittedOrders && (game.Game.State == 3 || game.Game.State == 5) && game.UsOpt.State == 2
})
if (myGames.length == 0) {
d.append('
' + warlight_shared_viewmodels_main_MultiPlayerDashboardVM.NoGamesHtml(0) + " ");
} else {
//Render MyGames
for (var f = 0; f < myGames.length;) {
var g = myGames[f];
++f;
g = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, g, warlight_shared_viewmodels_SignIn.get_CurrentPlayer());
d.append(warlight_shared_viewmodels_main_MultiPlayerDashboardVM.RenderGameHtml(warlight_shared_viewmodels_ConfigurationVM.Settings, g, null))
}
//Make player boxes also clickable
$.each($(".GameRow"), function(key, row) {
var href = $(this).find("a").attr("href");
var children = $(this).find("td:nth-of-type(2) > span:nth-of-type(1)");
var style = "display: inline-block;max-width: 400px;margin: 4px 0px;float: none;position: relative;font-size:10pt!important;white-space:normal;height:initial";
children.wrapInner("
").children(0).unwrap().attr("style", style).attr("href", href)
})
//Setup time left in GameRow
if(sortType != 1) {
$.each(dueGames, function(key, game) {
var id = game.GameID
var timeLeft = Math.min(game.AutoBoot._totalMilliseconds, game.VoteToBoot._totalMilliseconds, game.DirectBoot._totalMilliseconds) - game.WaitingFor._totalMilliseconds
var bootTime = new Date().getTime() + parseInt(timeLeft)
$("[gameid='" + id + "']").find("td div + span").append(`
(${getTimeLeft(timeLeft)} left) `)
})
}
//Setup time left tooltip
$.each(myGames, function(key, game) {
var id = game.GameID
var timeLeft = Math.min(game.AutoBoot._totalMilliseconds, game.VoteToBoot._totalMilliseconds, game.DirectBoot._totalMilliseconds) - game.WaitingFor._totalMilliseconds;
var bootTime = new Date().getTime() + parseInt(timeLeft)
var label = $("[gameid='" + id + "']").find(".BootTimeLabel")
if(timeLeft > 0) {
label.attr("title", getTimeLeft(timeLeft, true) + " left")
} else {
var overTime = game.WaitingFor._totalMilliseconds - Math.min(game.AutoBoot._totalMilliseconds, game.VoteToBoot._totalMilliseconds, game.DirectBoot._totalMilliseconds);
label.attr("title", "Time over since " + getTimeLeft(overTime, true))
}
label.tooltip({ show: {delay: 100}, hide: 100 });
label.attr("data-boottime", bootTime)
})
//Setup NextGameId
var nextGameIds = [];
$.each(myGames, function(key, game) {
var id = game.GameID
if(gameCanBeNextGame(game)){
nextGameIds.push(id)
}
})
$.each(myGames, function(key, game) {
var id = game.GameID
if(nextGameIds.length > 0 && nextGameIds[0]) {
var ids = [];
var url = "https://www.warlight.net/MultiPlayer?GameID=" + id + (nextGameIds.length > 1 ? ("&NextGameIDs=" + nextGameIds.slice(1, nextGameIds.length).join()) : "");
$("[gameid='" + id + "'] td > a").attr("href", url)
nextGameIds.push(nextGameIds.shift())
}
})
}
myGamesTable.find("tbody").fadeTo('fast', 1, function () {
myGamesTable.css('overflow-y', 'scroll');
});
$(window).trigger('resize');
}
function removeMyGames() {
d = $("#MyGamesTable").children("tbody");
d.children().remove();
}
function setMyGamesTimeLeft() {
$.each($("[data-boottime]"), function(key, target) {
var timeLeft = $(target).attr("data-boottime") - new Date().getTime()
if($(target).is("[data-inline]")) {
$(target).text(` (${getTimeLeft(timeLeft)} left)`)
} else {
// $(target).tooltip( "option", "content", getTimeLeft(timeLeft, true) + " left")
}
})
}
function getTimeLeft(time, detailed) {
var hours1 = 1 * 60 * 60 * 1000
var hours5 = 5 * 60 * 60 * 1000
var days5 = 5 * 25 * 60 * 60 * 1000
var secs = time / 1000
var mins = secs / 60
var hours = mins / 60
var days = hours / 24
if(time < 0) {
return "Hurry up! No time"
} else if(time < hours1) {
var m = Math.round(Math.floor(mins) % 60);
var s = Math.round(Math.floor(secs) % 60);
return m > 0 ? (m + (m == 1 ? " minute " : " minutes ")) : "" + s + (s == 1 ? " second" : " seconds")
} else if(time < hours5) {
var m = Math.round(Math.floor(mins) % 60)
var h = Math.floor(hours);
return h + (h == 1 ? " hour " : " hours ") + m + (m == 1 ? " minute" : " minutes")
} else if(time < days5 && !detailed) {
var d = Math.floor(days)
var h = Math.round(Math.floor(hours) % 24)
return (d > 0 ? d + (d == 1 ? " day " : " days ") : "") + h + (h == 1 ? " hour" : " hours")
} else if(time >= days5 && !detailed) {
return Math.round(days) + " days "
} else if(detailed) {
var d = Math.floor(days)
var h = Math.round(Math.floor(hours) % 24)
var m = Math.round(Math.floor(mins) % 60)
return (d > 0 ? d + (d == 1 ? " day " : " days ") : "") + h + (h == 1 ? " hour " : " hours ") + m + (m == 1 ? " minute" : " minutes")
} else {
return "undefined left " + time
}
}
function gameSort(a,b){
var sortType = sessionStorage.getItem("customSort")
var gameA = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, a, warlight_shared_viewmodels_SignIn.get_CurrentPlayer())
var gameB = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, b, warlight_shared_viewmodels_SignIn.get_CurrentPlayer())
var aRealTime = gameA.Game.RealTimeGame
var aPlaying = (gameA.Game.State == 3 || gameA.Game.State == 5) && gameA.UsOpt.State == 2
var aPrio0 = gameA.Game.PrivateMessagesWaiting || gameA.Game.PublicChatWaiting || gameA.Game.TeamChatWaiting
var aPrio1 = gameA.Game.State == 2 && gameA.UsOpt.State == 1 //Waiting to join
var aPrio4 = gameA.Game.State == 2 && gameA.Game.WaitingForYouToStart //Waiting for you to start
var aPrio3 = aPlaying && !gameA.UsOpt.HasCommittedOrders //Your turn 3 = turn, 5 = picking
var aBootTime = Math.min(a.AutoBoot._totalMilliseconds, a.VoteToBoot._totalMilliseconds, a.DirectBoot._totalMilliseconds) - a.WaitingFor._totalMilliseconds
var bRealTime = gameB.Game.RealTimeGame
var bPlaying = (gameB.Game.State == 3 || gameB.Game.State == 5) && gameB.UsOpt.State == 2
var bPrio0 = gameB.Game.PrivateMessagesWaiting || gameB.Game.PublicChatWaiting || gameB.Game.TeamChatWaiting
var bPrio1 = gameB.Game.State == 2 && gameB.UsOpt.State == 1
var bPrio4 = gameB.Game.State == 2 && gameB.Game.WaitingForYouToStart
var bPrio3 = bPlaying && !gameB.UsOpt.HasCommittedOrders
var bBootTime = Math.min(b.AutoBoot._totalMilliseconds, b.VoteToBoot._totalMilliseconds, b.DirectBoot._totalMilliseconds) - b.WaitingFor._totalMilliseconds
if(aRealTime && !bRealTime) return -1;
if(bRealTime && !aRealTime) return 1;
if(sortType == 3) {
if(aPrio0 && !bPrio0) return -1;
if(bPrio0 && !aPrio0) return 1;
}
if(aPrio1 && !bPrio1) return -1;
if(bPrio1 && !aPrio1) return 1;
if(aPrio3 && !bPrio3) return -1;
if(bPrio3 && !aPrio3) return 1;
if(aPlaying && !bPlaying) return -1;
if(bPlaying && !aPlaying) return 1;
if(aPrio3 && bPrio3) return aBootTime - bBootTime;
if(aPrio4 && !bPrio4) return -1;
if(bPrio4 && !aPrio4) return 1;
return a.WaitingFor - b.WaitingFor
}
function gameCanBeNextGame(g) {
var game = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, g, warlight_shared_viewmodels_SignIn.get_CurrentPlayer())
if(game != null && game.Game != null && game.UsOpt != null) {
var playing = (game.Game.State == 3 || game.Game.State == 5) && game.UsOpt.State == 2
var prio0 = game.Game.PrivateMessagesWaiting || game.Game.PublicChatWaiting || game.Game.TeamChatWaiting
var prio1 = game.Game.State == 2 && game.UsOpt.State == 1 //Waiting to join
var prio3 = playing && !game.UsOpt.HasCommittedOrders //Your turn 3 = turn, 5 = picking
var prio4 = game.Game.State == 2 && game.Game.WaitingForYouToStart //Waiting for you to start
return prio0 || prio1 || prio3 || prio4
} else {
return false;
}
}
function refreshOpenGames() {
deletedMD = deletedRT = 0;
openGamesTable.find("tbody").fadeTo('fast', 0.15);
var page = $('
').load('https://www.warlight.net/MultiPlayer/ ', function () {
var data = page.find('#AllOpenGamesData').html();
$('#AllOpenGamesData').html(data);
WL_MPDash.OpenGamesCtrl.AllOpenGamesData = data
Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "openGamesFilters", function(filters) {
var openGamesFilters;
if(filters) {
openGamesFilters = filters.value;
}
var games;
if (openGamesFilters && openGamesFilters["disableAll"] != true) {
games = filterGames(wljs_Jsutil.GamesFromDump(data), openGamesFilters);
} else {
games = wljs_Jsutil.GamesFromDump(data);
}
$.each(games, function (key, game) {
if ($$$(game).playerJoined()) {
games[key] = $$$(game).markJoined();
}
});
wljs_AllOpenGames = WL_MPDash.OpenGamesCtrl.AllOpenGames = games;
var RealTimeLadderTable = page.find("#RealTimeLadderTable tbody tr:first-of-type").outerHTML();
$("#RealTimeLadderTable tbody tr:first-of-type")
$("#RealTimeLadderTable tbody tr:first-of-type").replaceWith(RealTimeLadderTable)
replaceAndFilterForumTable(page.find("#ForumTable").outerHTML());
$("#ClanForumTable").replaceWith(page.find("#ClanForumTable").outerHTML())
setupRightColumn()
updateOpenGamesCounter();
wljs_AllOpenGamesData = wljs_multiplayer_Ctrl_AllOpenGamesData = data;
var player = warlight_shared_viewmodels_SignIn.get_CurrentPlayer();
if ((new js.JQuery(this.BothRadio)).is(":checked")) {
player.OpenGamePreference = 1;
} else if ((new js.JQuery(this.MultiDayRadio)).is(":checked")) {
player.OpenGamePreference = 2;
} else if ((new js.JQuery(this.RealTimeRadio)).is(":checked")) {
player.OpenGamePreference = 3;
}
wljs_Jsutil.Post("/MultiPlayer/", "ChangePace=" + player.OpenGamePreference, function (a) {});
var a = $("#OpenGamesTable").children("tbody");
a.children().remove();
var gamesToShow = warlight_shared_viewmodels_main_MultiPlayerDashboardVM.GamesToShow(wljs_AllOpenGames, player.OpenGamePreference, 0 == this.ShowingAllOpenGames)
for (var b = 0; b < gamesToShow.length;) {
var game = gamesToShow[b];
b++;
game.get_IsLottery() && warlight_shared_viewmodels_main_MultiPlayerDashboardVM.get_HideLotteryGames() ||
(game = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 2, game, warlight_shared_viewmodels_SignIn.get_CurrentPlayer()), a.append(warlight_shared_viewmodels_main_MultiPlayerDashboardVM.RenderGameHtml(warlight_shared_viewmodels_ConfigurationVM.Settings, game, null)))
}
openGamesTable.find("tbody").fadeTo('fast', 1, function () {
openGamesTable.css('overflow-y', 'scroll');
});
addOpenGamesSuffix();
domRefresh();
})
});
}
var refreshingPromotedGames = false;
function refreshPromotedGames() {
if(!refreshingPromotedGames) {
refreshingPromotedGames = true;
promotedGamesTable.find("tbody").fadeTo('fast', 0.15);
var page = $('
').load('https://www.warlight.net/MultiPlayer/ ', function () {
var data = page.find('#MorePromotedGamesData').html();
$('#MorePromotedGamesData').html(data);
wljs_PromotedGames = wljs_Jsutil.GamesFromDump(data);
refreshingPromotedGames = false;
var a = $("#PromotedGamesTable").children("tbody");
a.children().remove();
for (var b = 0; b < wljs_PromotedGames.length;) {
var game = wljs_PromotedGames[b];
b++;
(game = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 2, game, warlight_shared_viewmodels_SignIn.get_CurrentPlayer()), a.append(warlight_shared_viewmodels_main_MultiPlayerDashboardVM.RenderGameHtml(warlight_shared_viewmodels_ConfigurationVM.Settings, game, null)))
}
domRefresh();
promotedGamesTable.find("tbody").fadeTo('fast', 1, function () {
promotedGamesTable.css('overflow-y', 'scroll');
});
});
} else {
log("refreshing promoted blocked")
}
}
/**
* Setups the refresh functionality
*/
function setupRefreshFunction() {
lastRefresh = new Date();
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();
}
});
}
$(".MainColumn").prepend($('#refreshAll'))
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();
}
}
});
}
function getDate(text) {
var date;
if (text.match(/[0-9]+ second/)) {
date = new Date() - 1000;
} else if (text.match(/[0-9]+ seconds/)) {
date = new Date() - text.match(/[0-9]+/) * 1000;
} else if (text.match(/[0-9]+ minute/)) {
date = new Date() - text.match(/[0-9]+/) * 1000 * 60;
} else if (text.match(/[0-9]+ minutes/)) {
date = new Date() - text.match(/[0-9]+/) * 1000 * 60;
} else if (text.match(/[0-9]+ hour/)) {
date = new Date() - text.match(/[0-9]+/) * 1000 * 60 * 59;
} else if (text.match(/[0-9]+ hours/)) {
date = new Date() - text.match(/[0-9]+/) * 1000 * 60 * 60;
} else if (text.match(/[0-9]+ day/)) {
date = new Date() - text.match(/[0-9]+/) * 1000 * 60 * 60 * 36;
} else if (text.match(/[0-9]+ days/)) {
date = new Date() - text.match(/[0-9]+/) * 1000 * 60 * 60 * 24;
} else if (text.match(/[0-9]+[\/][0-9]+[\/][0-9]+/)) {
var split = text.split('/');
date = new Date(split[2], split[0] - 1, split[1]);
date.setHours(0, 0, 0, 0);
}
return date;
}
/**
* Refreshes Width & Height of Columns
*/
function refreshSingleColumnSize() {
var showSide = $(".showSide");
var showGames = $(".showGames");
showSide.scrollTop(0);
/**
* Sticky Titles
*/
$(".followMeBar").each(function () {
$(this).removeClass("fixed");
if ($(this).parent().hasClass("followWrap")) {
$(this).unwrap();
}
var thisSticky = $(this).wrap('
');
thisSticky.parent().height(thisSticky.outerHeight());
var pos = parseInt(thisSticky.offset().top) - parseInt(showSide.offset().top);
$.data(thisSticky[0], 'pos', pos);
});
var width = $("#ForumTable").width();
createSelector(".followMeBar", "width:" + width + "px;");
showGames.find("table").css({
height: window.innerHeight - 150
});
//var height = showGames.find("table thead tr").height() + 30;
var height = 48;
createSelector(".showGames table tbody tr:first-of-type td", "padding-top:" + height + "px");
showSide.css({
height: window.innerHeight - 150
});
showGames.find("table tbody tr:first-of-type td").css("padding-top", height);
$(".showGames thead tr").width($(".showGames thead tr").closest("table").width()-30)
$(".showGames thead tr td div").unwrap();
}
window.showGamesActive = "ShowMyGames";
window.openGames = [];
function setupBasicDashboardStyles() {
createSelector(".GameRow a", "font-size:16px !important;");
createSelector("a", "outline: none");
createSelector('#PromotedGamesTable td:last-of-type a img', 'display:none');
createSelector("#MyGamesTable td > a > img", 'display:none');
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;");
createSelector("#MyGamesTable td span a img, #MyGamesTable td span a img", "display:inherit;");
createSelector(".GameRow:hover", "background-color:rgb(50, 50, 50);cursor:pointer;");
createSelector(".GameRow a:hover", "text-decoration:none;");
createSelector(".TournamentRow a:hover", "text-decoration:none;");
createSelector(".TournamentRow:hover", "background-color:rgb(50, 50, 50);cursor:pointer;");
createSelector(".ui-buttonset label", "font-size:11px;");
createSelector("#OpenGamesTable label:hover", " border: 1px solid #59b4d4;background: #0078a3 50% 50% repeat-x;font-weight: bold;color: #ffffff;");
createSelector("#OpenGamesTable td:last-child,#MyGamesTable td:last-child, #PromotedGamesTable td:last-child", "position: relative;");
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;");
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;");
createSelector(".loading img", "position: absolute;top: 50%;left: 50%;margin-left: -16px;margin-top: -16px;");
createSelector("img", "position: relative;z-index:50;");
createSelector("input", "z-index: 98;position: relative;");
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;");
createSelector(".showGames table tbody", "display:table;width:100%;");
createSelector(".showGames table thead", "position:inherit;");
createSelector(".ui-tooltip", "background: #EBEBEB;padding: 4px;font-style: italic;");
$.each($(".TournamentRow td"), function () {
$(this).find("font:first-of-type").appendTo($(this).find("a")).css("font-size", "10px");
});
}
function setupFixedWindowStyles() {
createSelector('html', 'width: 100%; position:fixed')
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");
var top = parseInt($(".showSide").offset().top) + parseInt(43);
createSelector(".followMeBar.fixed", "position: fixed;top: " + top + "px;z-index: 0;z-index:98;");
createSelector(".followMeBar.fixed.absolute", "position: absolute;");
createSelector(".showSide", "overflow-y:scroll;float: left;margin-top: 43px;padding-right: 6px;");
createSelector(".showSide thead", "display:none");
createSelector(".showSide table", "border-top-right-radius:0;border-top-left-radius:0");
createSelector("#switchGameRadio label", "margin-left: 6px !important");
createSelector(".showGames table", "display:block !important");
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);");
createSelector("#MyGamesTable, #PromotedGamesTable, #OpenGamesTable", "display:none");
createSelector("#MainSiteContent > table > tbody > tr > td", "width:100%");
createSelector(".MainColumn", "width: calc(60% - 20px)!important;max-width: 800px;min-width:1px");
createSelector(".SideColumn", "float:left !important");
createSelector("h2 + span", "margin-right: 50px;");
createSelector("body", "overflow:hidden");
createSelector(".SideColumn", "width: 100% !important;");
createSelector("#MyGamesFilter", "width:200px");
createSelector(".showGames table", "display:block; overflow-y:scroll; overflow-x:hidden; border:1px gray solid; border-radius:8px");
createSelector(".adsbygoogle", "margin-top: 25px;");
createSelector(".showSide", "overflow-y:scroll;float: left;margin-top: 43px;padding-right: 6px;width:39%; min-width:1px;max-width:615px;margin-left: 20px;border-top-left-radius:8px;border-top-right-radius:8px");
createSelector("#refreshAll", "width: 140px;float: right;margin-top: 10px;");
createSelector("#fakeOpenGameMenu label", "margin-right:2px");
createSelector("#RestoreLotteryGamesBtn", "display:none");
createSelector('#ForumTable tbody tr td, #ClanForumTable tbody tr td', 'overflow:hidden;position:relative');
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;');
createSelector('#ForumTable tbody tr td span, #ClanForumTable tbody tr td span', 'display: inline-block;z-index: 1;float: left;position: relative;');
createSelector('#ForumTable tbody tr:not(:last-child):hover, #ClanForumTable tbody tr:hover', 'background-color:rgb(50, 50, 50)');
createSelector('#ForumTable tbody tr td a[href="/Forum/Forum"]', 'position: relative;');
createSelector('#ClanForumTable tbody tr td a[href="/Clans/Forum"]', 'position: relative;');
$("body").scrollTop(0)
addCSS(`
@media (max-width: 1400px) {
.showSide {
//min-width: 380px;
//width: 40%;
}
h2 + span {
margin-right: 10px!important;
}
}
@media (max-width: 1300px) {
#MyGamesTable > thead > tr * {
font-size: 14px;
}
#MyGamesTable > thead > tr > div:nth-of-type(1) {
margin-top: 5px!important;
display: block;
float: left;
padding-right: 5px;
}
#MyGamesTable select {
width: 110px;
}
}
@media (max-width: 1205px) {
.MainColumn {
width: 60% ;
min-width: 0;
}
#MyGamesTable select {
width: 75px;
}
}
@media (max-width: 1100px) {
#refreshAll {
width: 85px!important;
}
#MyGamesTable > thead > tr > div:nth-of-type(1) {
display: none;
}
}
@media (max-width: 1100px) {
.MainColumn {
float: left;
}
}
@media (max-width: 1000px) {
.showSide {
min-width:0px;
}
}
`);
}
function setupFixedTitlesInSideColumn() {
var blogTable = $("#BlogTable");
var realTimeLadderTable = $("#RealTimeLadderTable");
var forumTable = $("#ForumTable");
var clanForumTable = $("#ClanForumTable");
var mapOfTheWeekTable = $("#MapOfTheWeekTable");
var leaderboardTable = $("#LeaderboardTable");
var myTournamentsTable = $("#MyTournamentsTable");
var bookmarkTable = $("#BookmarkTable");
var shopTable = $("#ShopTable")
blogTable.before("
" + blogTable.find("thead > tr > td").html() + "
");
realTimeLadderTable.before("
" + realTimeLadderTable.find("thead > tr > td").html() + "
");
forumTable.before("
" + forumTable.find("thead > tr > td").html() + "
");
clanForumTable.before("
" + clanForumTable.find("thead > tr > td").html() + "
");
mapOfTheWeekTable.before("
" + mapOfTheWeekTable.find("thead > tr > td").html() + "
");
ifSettingIsEnabled("hideCoinsGlobally", function() {
}, function() {
leaderboardTable.before("
" + leaderboardTable.find("thead > tr > td").html() + "
");
}, function() {
myTournamentsTable.before("
" + myTournamentsTable.find("thead > tr > td").html() + "
");
bookmarkTable.before("
" + bookmarkTable.find("thead > tr > td").html() + "
");
shopTable.before("
" + shopTable.find("thead > tr > td").html() + "
");
var leagueTable = $("#LeagueTable");
leagueTable.before("
" + leagueTable.find("thead > tr > td").html() + "
");
new StickyTitles(jQuery(".followMeBar")).load();
})
}
function setupFixedWindowWithScrollableGames() {
var gameButtons = '
';
gameButtons += ' ';
gameButtons += 'My Games ';
ifOneOrMoreIsEnabled(["hidePromotedGames", "hideCoinsGlobally"], function() {
gameButtons += ' ';
gameButtons += 'Open Games ';
gameButtons += '
';
setupMainColumn(gameButtons)
}, function() {
gameButtons += '
';
gameButtons += '
Open Games ';
gameButtons += '
';
gameButtons += '
Coin Games ';
gameButtons += '
';
setupMainColumn(gameButtons)
})
}
function setupMainColumn(gameButtons) {
var mainColumn = $(".MainColumn ");
mainColumn.prepend('