// ==UserScript==
// @name Tidy up your Dashboard
// @namespace https://greasyfork.org/users/10154
// @grant none
// @run-at document-start
// @match https://www.warlight.net/*
// @description Customizable Userscript which tidies up your Dashboard!
// @version 1.14.16
// @icon http://i.imgur.com/XzA5qMO.png
// @require https://code.jquery.com/jquery-1.11.2.min.js
// @require https://code.jquery.com/ui/1.11.3/jquery-ui.min.js
// @require https://cdn.bootcss.com/datatables/1.10.10/js/jquery.dataTables.min.js
// @require https://cdn.bootcss.com/datatables/1.10.10/js/dataTables.bootstrap.js
// @require https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js
// @downloadURL none
// ==/UserScript==
window.timeUserscriptStart = new Date().getTime();
var version = "1.14.16";
this.$$$ = jQuery.noConflict(true);
var logData = "";
function log(entry) {
var time = moment(new Date()).format('h:mm:ss');
logData += `\n${time} | ${entry}`;
}
function logError(entry) {
var time = moment(new Date()).format('h:mm:ss');
logData += `\n${time} | ${entry}`;
}
//ctrl+shift+2
$$$(document).keydown(function(e){
if( e.which === 50 && e.ctrlKey && e.shiftKey ){
getLog()
}
});
window.logDialog = undefined;
window.getLog = function() {
if(logDialog) {
logDialog.html(``)
logDialog.dialog('open')
} else {
logDialog = $$$(`
").append(this.eq(0).clone()).html();
};
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))
}
$.fn.getsFiltered = function (openGamesFilters) {
var game = this[0];
if(game) {
if (openGamesFilters["hideMaxPlayers"] <= 100 && $(game).numOfPlayers() > openGamesFilters["hideMaxPlayers"]) return true;
if (openGamesFilters["hideMinPlayers"] <= 100 && $(game).numOfPlayers() < openGamesFilters["hideMinPlayers"]) return true;
if (openGamesFilters["hideLuck"] < 100 && game.SettingsOpt.LuckModifier * 100 > openGamesFilters["hideLuck"]) return true;
if (openGamesFilters["hideFFA"] && $(game).numOfTeams() == 0 && $(game).numOfPlayers() > 2) return true;
if (openGamesFilters["hideTeam"] && $(game).numOfTeams() > 0) return true;
if (openGamesFilters["hide1v1"] && $(game).numOfPlayers() == 2) return true;
if (openGamesFilters["hideCustomScenario"] && game.SettingsOpt.DistributionMode === -3) return true;
if (openGamesFilters["hideNonCustomScenario"] && game.SettingsOpt.DistributionMode !== -3) return true;
if (openGamesFilters["hideCommanderGames"] && game.SettingsOpt.HasCommanders) return true;
if (openGamesFilters["hideNoneCommanderGames"] && !game.SettingsOpt.HasCommanders) return true;
if (openGamesFilters["hidePractice"] && !game.SettingsOpt.RankedGame) return true;
if (openGamesFilters["hideNoSplit"] && game.SettingsOpt.NoSplit) return true;
if (openGamesFilters["hideLocalDeployments"] && game.SettingsOpt.LocalDeployments) return true;
if (openGamesFilters["hideNonPractice"] && game.SettingsOpt.RankedGame) return true;
if (openGamesFilters["hideManualDistribution"] && !game.SettingsOpt.AutoDistribution) return true;
if (openGamesFilters["hideAutoDistribution"] && game.SettingsOpt.AutoDistribution) return true;
if (openGamesFilters["hideKeyword"] && openGamesFilters["hideKeyword"].length > 0 && $(game).containsKeyword(openGamesFilters)) return true;
if (openGamesFilters["hideRealTimeBootTime"] > 0 && game.RealTimeGame && game.DirectBoot._totalMilliseconds < openGamesFilters["hideRealTimeBootTime"]) return true;
if (openGamesFilters["hideMultiDayBootTimeInMs"] > 0 && !game.RealTimeGame && game.DirectBoot._totalMilliseconds < openGamesFilters["hideMultiDayBootTimeInMs"]) return true;
}
return false;
};
$.fn.numOfPlayers = function () {
var game = this[0];
return game.Players.length + game.OpenSeats.length;
};
$.fn.playerJoined = function () {
var game = this[0];
var playerJoined = false;
var id = warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID;
$.each(game.Players, function (key, player) {
if (player.PlayerID == id) {
playerJoined = true;
}
});
return playerJoined;
};
$.fn.markJoined = function () {
var game = this[0];
game.Name += '##joined##';
return game;
};
$.fn.numOfTeams = function () {
var game = this[0];
var teams = 0;
if (game.AtStartDivideIntoTeamsOfIfOpenGame > 0) return $(game).numOfPlayers() / game.AtStartDivideIntoTeamsOfIfOpenGame;
if (Math.max.apply(Math, game.OpenSeats) == -1) return 0;
var maxTeam = Math.max.apply(Math, game.OpenSeats);
$.each(game.Players, function (key, player) {
if (player.Team > maxTeam) {
maxTeam = player.Team;
};
});
return maxTeam + 1;
}
$.fn.containsKeyword = function (openGamesFilters) {
var game = this[0];
var keywords = openGamesFilters["hideKeyword"].split(",");
var title = game._nameLowered || game.Name.toLowerCase();
var filtered = false;
$.each(keywords, function (key, keyword) {
if (title.indexOf(keyword.trim().toLowerCase()) >= 0) {
filtered = true;
}
})
return filtered;
};
$.fn.settingIsEnabled = function (setting) {
var selected = false;
$.each(userscriptSettings, function (key, set) {
if (set.id == setting) {
selected = set.selected;
}
});
return selected;
};
try {
$.extend( $$$.fn.dataTableExt.oSort, {
"rank-pre": function ( a ) {
return a.match(/([0-9]*)/)[1] || 9999;
},
"rank-asc": function( a, b ) {
return a < b;
},
"rank-desc": function(a,b) {
return a > b;
}
} );
$.extend( $$$.fn.dataTableExt.oSort, {
"numeric-comma-pre": function ( a ) {
return Number(a.replace(/,/g, ""))
},
"numeric-comma-asc": function( a, b ) {
return a < b;
},
"numeric-comma-desc": function(a,b) {
return a > b;
}
} );
} catch(e) {
log(e)
}
addCSS(`
input.unityId {
width: 100%;
box-sizing: border-box;
height: 40px;
text-align: center;
font-size: 20px;
}
h3.unityId {
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 != undefined && (id = href.match(/(gameid=|level\?id=|level=)([0-9]*)/i))) {
var title = $("
'
}
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 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() {
$("h1").text($("h1").text() + " & Community Events")
var clotInfo = getClots()
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() {
try {
var clotInfo = getClots()
if(!clotInfo) {
return
}
var ladders = clots['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 getClots() {
try {
return clots = $.parseJSON(sessionStorage.getItem('clots'))
} catch (e) {
log("Error reading CLOTs")
log(e.message)
hideTable("#LeagueTable")
}
return undefined
}
function loadClots() {
$.ajax({
type: 'GET',
//url: 'https://php-psenough.rhcloud.com/hub/list.php',
//url: 'https://w115l144.hoststar.ch/test.php',
url: 'https://php-psenough.rhcloud.com/hub/list_jsonp.php',
dataType: 'jsonp',
crossDomain: true,
}).done(function(response){
try {
var json = response.data
sessionStorage.setItem('clots', JSON.stringify(json));
parseLeagueTable()
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 isJson(str) {
try {
JSON.parse(str);
} catch (e) {
log(e)
return false;
}
return true;
}
function setupRightColumn(isInit) {
if(isInit) {
createSelector(".SideColumn > table", "margin-bottom: 17px;")
}
//Bookmarks
if(isInit) {
setupBookmarkTable()
} else {
refreshBookmarks()
}
//Tournament
// #MyTournamentsTable
//Clots
setupLeagueTable()
//RT Ladder
setupRealTimeLadderTable()
//Map of the Week
//Forum Posts
// hideBlacklistedThreads()
//Blog Posts
//Coin Leaderboard
sortRightColumnTables(function() {
if(isInit) {
ifSettingIsEnabled('scrollGames', function() {
setupFixedTitlesInSideColumn();
})
}
})
}
function sortRightColumnTables(callback) {
var sideColumn = $(".SideColumn")
getSortTables(function(tables) {
$.each(tables, function(key, table) {
if(table.hidden == true) {
hideTable(table.id)
} else {
var table = $(table.id)
if(table.prev().hasClass("followWrap")) {
var wrap = table.prev().remove()
sideColumn.append(wrap)
}
table = table.detach()
sideColumn.append(table)
}
})
$(".SideColumn > br").remove()
callback();
})
}
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;
}
function hideTable(seletor) {
if( $(seletor).prev().hasClass("followWrap")) {
$(seletor).prev().remove()
}
$(seletor).remove()
}
window.findMostCommonGames = function() {
$("#foundPlayers").empty()
warlight_shared_viewmodels_WaitDialogVM.Start("Searching Players...")
warlight_shared_messages_Message.GetFriendsAsync(null, warlight_shared_viewmodels_SignIn.Auth, null, function (b, c, players) {
if (null != c) throw c;
var myId = warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID;
warlight_shared_SharedUtility.RemoveWhere(players, function (p) {
return p.PlayerID == myId
});
var topPlayers = [];
var limit = -1;
for (var i = 0; i < players.length; i++) {
var player = players[i];
if(player.TimesPlayedWithYou > limit || topPlayers.length < 10) {
topPlayers.push(player)
topPlayers.sort(function (p1, p2) {
return p2.TimesPlayedWithYou - p1.TimesPlayedWithYou
});
topPlayers = topPlayers.slice(0, 10);
limit = topPlayers.slice(-1)[0].TimesPlayedWithYou
}
}
warlight_shared_viewmodels_WaitDialogVM.Stop()
parseFoundFriendPlayers(topPlayers)
})
}
function setupDashboardSearch() {
loadDataTableCSS();
$("body").append(``);
window.tabsInit = false;
$("#searchTabs").tabs();
$( "#searchTabs" ).on( "tabsactivate", function( event, ui ) {
$(ui.newPanel[0]).find("input").focus();
if($(ui.newPanel[0]).attr("id") == "tabs-clanSearch" && !tabsInit) {
initClanSearch();
tabsInit = true;
}
} );
createSelector("#searchTabs", "background: rgb(23, 23, 23);border: none;")
createSelector(".ui-tabs-nav", "border: none;border-bottom: 2px gray solid;border-radius: 0;background:none;")
createSelector("#tabs-playerSearch, #tabs-clanSearch", "padding: 15px 0px")
$("#SubTabRow").append('
Search ');
$("#searchPlayerLink").on("click", function() {
showPopup(".playersearch-show")
$("#playerSearchQuery").val("")
$("#playerSearchQuery").focus()
})
$("#searchPlayerBtn").on("click", function() {
searchPlayer()
})
$("#findPlayerExtra").on("click", function(event) {
$(".playersearch-context").finish().toggle(100).
css({
top: event.pageY + "px",
left: event.pageX + "px"
});
})
$('#playerSearchQuery').keyup(function(e){
if(e.keyCode == 13) {
searchPlayer()
}
});
createSelector(".SubTabCell", "cursor: pointer")
createSelector(".playersearch-show button", "padding: 5px;float: left; margin: 10px")
createSelector("#playerSearchQuery, #clanSearchQuery", "width: 200px; padding: 5px; margin: 10px;float: left")
createSelector(".foundPlayer", "display: block; height: 25px; padding: 2px; clear:both")
createSelector(".foundPlayer a", "line-height: 25px; float: left")
createSelector(".foundPlayer img", "height: 15px; display: block; float: left; margin: 5px")
createSelector(".notFound", "clear: both; display: block; color: gray;")
createSelector("#foundPlayers span", "color: gray; padding: 0 5px; line-height: 25px")
createSelector("#foundPlayers > span", "display: block; clear: both; margin: 0px; padding: 10px 0")
createSelector(".playerSearchName", "float: left")
createSelector(".playerSearchTypeSelect", "float: left; width: 30%")
createSelector(".playerSearchTypeSelect label", "color: gray; font-size: 13px; margin: 2px")
createSelector("#foundClansTable", "float: left; table-layout: fixed;width: 100%")
createSelector("#foundClansTable thead", "text-align: left")
createSelector("#foundClansTable td a", "display: block; width: 100%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;height: 19px;")
createSelector("#foundClansTable img", "margin-right: 5px;")
}
function initClanSearch() {
warlight_shared_viewmodels_WaitDialogVM.Start("Setting up clans...")
warlight_shared_messages_Message.GetClansAsync(null, null, function (a, b, clans) {
parseFoundClans(clans)
warlight_shared_viewmodels_WaitDialogVM.Stop();
})
}
window.blockSearch = false;
function searchPlayer() {
if(blockSearch) {
return;
}
blockSearch = true;
window.setTimeout(function() {
blockSearch = false;
}, 3000)
$("#foundPlayers").empty()
var query = $("#playerSearchQuery").val().toLowerCase()
if($('#playerSearchFriend').is(':checked')) {
warlight_shared_viewmodels_WaitDialogVM.Start("Searching Players...")
warlight_shared_messages_Message.GetFriendsAsync(null, warlight_shared_viewmodels_SignIn.Auth, null, function (b, c, players) {
if (null != c) throw c;
var myId = warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID;
warlight_shared_SharedUtility.RemoveWhere(players, function (p) {
return p.Name.toLowerCase().indexOf(query) < 0 || p.PlayerID == myId
});
warlight_shared_viewmodels_WaitDialogVM.Stop()
parseFoundFriendPlayers(players)
})
} else {
if(query.length < 3) {
warlight_shared_viewmodels_AlertVM.DoPopup("Please enter at least 3 characters to search for");
return
}
warlight_shared_viewmodels_main_manageplayers_ManagePlayersVM.SearchPlayers(query, function (players) {
players = players.Results
if(players.length >= 25) {
$("#foundPlayers").append("
This query found more than 25 results. Only the first 25 results are shown below. ")
}
parseFoundGlobalPlayers(players)
$("#playerSearchQuery").focus()
$("#playerSearchQuery").select()
})
}
}
function parseFoundFriendPlayers(players) {
if(!players || players.length == 0) {
$("#foundPlayers").append("
No Players found. ");
return;
}
players.sort(function (p1, p2) {
return (p2.TimesPlayedWithYou - p1.TimesPlayedWithYou != 0) ? p2.TimesPlayedWithYou - p1.TimesPlayedWithYou : p1.Level > p2.Level
});
for (var i = 0; i < players.length; i++) {
var player = players[i];
var id = String(player.ProfileToken).substr(0, 2) + String(player.PlayerID) + String(player.ProfileToken).substr(2, 2);
var nameLink = '
' + player.Name + ' '
var clan = player.ClanOpt != null ? '
' : "";
var member = player.IsMember ? '
' : "";
var description = '
' + nameLink + member + "(Level " + player.Level + ", " + player.TimesPlayedWithYou + " common games)
";
$("#foundPlayers").append('
' + clan + description + '
')
}
}
function parseFoundClans(clans) {
clans.sort(function (c1, c2) {
return (c2.TotalPointsInThousands - c1.TotalPointsInThousands)
});
var clanTableHTML = '
# Name Created By Total Points Created On '
for (var i = 0; i < clans.length; i++) {
var clan = clans[i];
var name = clan.Name;
var id = clan.ID;
var createdBy = clan.CreatedBy;
var iconId = clan.IconIncre;
var imgTag = iconId == 0 ? "" : ` `;
var totalpoints = (clan.TotalPointsInThousands * 1000).toLocaleString("en")
var createdDate = moment(clan.CreatedDate.date).format('MM/DD/YYYY')
var nameHTML = `${imgTag}${name} `;
clanTableHTML += `${i+1} ${nameHTML} Checking.. ${totalpoints} ${createdDate} `
}
clanTableHTML += "
"
$("#foundClans").append(clanTableHTML)
var dataTable = $$$("#foundClansTable").DataTable({
"order": [],
paging: true,
"pageLength": 10,
"bLengthChange": false,
"autoWidth": false,
columnDefs: [ {
targets: [ 0 ],
searchable: false
},{
targets: [ 1 ],
orderData: [ 1, 0 ],
sortable: false
},{
targets: [ 2 ],
orderData: [ 2, 1, 0 ],
sortable: false,
searchable: false
},{
targets: [ 3 ],
orderData: [ 3, 1, 0 ],
type: "numeric-comma"
} ,{
targets: [ 4 ],
orderData: [ 4, 1]
} ],
"aoColumns": [
{ "orderSequence": [ "desc", "asc" ] },
{"orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "desc", "asc" ] },
],
initComplete: function() {
window.setTimeout(loadClanCreators, 200);
},
"language": {
"zeroRecords": "No matching clans found",
"info": "Showing _START_ to _END_ of _TOTAL_ clans",
"infoEmpty": "Showing 0 to 0 of 0 clans",
"infoFiltered": "(filtered from _MAX_ total clans)",
}
});
dataTable.on('draw.dt', function () {
loadClanCreators()
})
}
function loadClanCreators() {
$.each($(".data-player"), function(k, cell) {
if($(cell).hasClass("data-player") && $(cell).is(":visible")) {
var id = $(cell).attr("data-player-id")
$.ajax({
type: 'GET',
url: `https://w115l144.hoststar.ch/wl/wl_profile.php?p=${id}`,
dataType: 'jsonp',
crossDomain: true,
}).done(function(response){
if(isFinite(response.data) ){
$(`[data-player-id="${id}"]`).html(`
${decodeURI(atob(response.name)) || "Unknown"} `)
} else {
$(`[data-player-id="${id}"]`).html(`Unknown`)
}
if($(cell).is(":visible")) {
$(cell).removeClass("data-player");
}
});
}
});
}
function parseFoundGlobalPlayers(players) {
if(!players || players.length == 0) {
$("#foundPlayers").append("
No Players found. ");
return;
}
players.sort(function(p1, p2){
return (p2.Level - p1.Level != 0) ? p2.Level - p1.Level : p1.Name > p2.Name
});
for (var i = 0; i < players.length; i++) {
var player = players[i];
var id = String(player.ProfileToken).substr(0, 2) + String(player.PlayerID) + String(player.ProfileToken).substr(2, 2);
var nameLink = '
' + player.Name + ' '
var clan = player.ClanOpt != null ? '
' : "";
var member = player.IsMember ? '
' : "";
var name = '
' + nameLink + "(" + player.Level + ")
";
$("#foundPlayers").append('
' + clan + name + member + '
');
}
}
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() {
})
}
var mapData;
function setupMapSearch() {
$("#PerPageBox").closest("tr").after('
Search Reset ')
$('#mapSearchQuery').on('keypress', function (event) {
if(event.which === 13){
searchMaps();
}
});
$("#mapSearchBtn").on("click", function() {
searchMaps();
})
$("#FilterBox, #SortBox, #PerPageBox").on("change", function() {
$("#mapSearchQuery").val("")
$("#searchResultsTitle").remove()
})
}
function searchMaps() {
if(mapData == undefined) {
$("
").load('Ajax/EnumerateMaps?Filter=' + 1 + '&Sort=' + 1 + "&PerPage=" + 2147483647 + "&Offset=" + 0, function(data) {
mapData = data;
filterMaps(this);
})
} else {
var maps = $("
").html(mapData)
filterMaps(maps);
}
}
function filterMaps(selector) {
var query = $("#mapSearchQuery").val()
$.each($(selector).find("div"), function(key, div) {
if($(div).text().trim().toLowerCase().replace(/(rated.*$)/, "").indexOf(query.toLowerCase()) == -1) {
$(div).remove()
}
})
var count = $(selector).find("div").length
$('#MapsContainer').empty()
$(selector).detach().appendTo('#MapsContainer')
$("#MapsContainer tr:last-of-type").html("Showing maps 1 - " + count + " of " + count);
$("#ReceivePager").html("Showing maps 1 - " + count + " of " + count);
$("#searchResultsTitle").length > 0 ? $("#searchResultsTitle").html("Searchresults for
" + query +" ") : $("#ReceivePager").after("
Searchresults for " + query +" ")
}
function setupLevelBookmark() {
$("h1").after(`
Bookmark
`)
}
function setupPlayerAttempDataTable() {
var playerData = []
$("#MainSiteContent ul").find("li").map(function(){
var player = $(this).children().map(function(){return $(this).outerHTML()}).get().join("")
var str = $(this).clone().children().remove().end().text();
var attemps = str.split(", ")[0].replace(/[^0-9]/g, '')
var wins = str.split(", ")[1].replace(/[^0-9]/g, '')
playerData.push({
player: player,
attemps: attemps,
wins: wins
})
})
var table = "
Name Attemps Wins "
$.each(playerData, function(k, player) {
var tr = `${player.player} ${player.attemps} ${player.wins} `;
table += tr;
})
table += "
"
$("#MainSiteContent ul").replaceWith(table)
loadDataTableCSS();
var dataTable = $$$("#playlogPreview").DataTable({
"order": [2],
paging: false,
sDom: 't',
columnDefs: [ {
targets: [ 0, 1, 2 ],
},{
targets: [ 1 ],
orderData: [ 1, 2, 0 ]
},{
targets: [ 2 ],
orderData: [ 2, 1, 0 ],
}],
"aoColumns": [
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "desc", "asc" ] },
{ "orderSequence": [ "desc", "asc" ] },
],
});
addCSS(`
#playlogPreview a {
margin-right: 10px;
}
#playlogPreview td {
white-space: nowrap;
}
`)
}
/**************************************
MANAGER LEAGUE
**************************************/
function setupManagerLeague() {
var script = document.createElement("script");
script.type = "text/javascript";
document.body.appendChild( script );
script.src = "https://cdn.jsdelivr.net/jqplot/1.0.8/jquery.jqplot.min.js";
script.onload = function() {
log("loaded1")
var script2 = document.createElement("script");
script2.type = "text/javascript";
document.body.appendChild( script2 );
script2.src = "https://cdn.jsdelivr.net/jqplot/1.0.8/plugins/jqplot.highlighter.min.js";
script2.onload = function() {
log("loaded2")
}
}
var styles = document.createElement("style");
styles.type = "text/css";
styles.innerHTML = getPlotCSS();
document.body.appendChild(styles);
var cosPoints = [];
for (var i=0; i<2*Math.PI; i+=0.1){
cosPoints.push([i, Math.cos(i)]);
}
log(cosPoints)
$.ajax({
type: 'GET',
url: 'https://w115l144.hoststar.ch/wl/managerleague.php',
dataType: 'jsonp',
crossDomain: true,
}).done(function(response){
try {
var max = 100;
var json = response.data
$.jqplot.config.enablePlugins = true;
this.tooltipOffset = 100
$("#MainSiteContent > table tr:nth-of-type(2) > td:nth-of-type(3)").append('
')
var points = [];
var ticksx = [];
for (var i = 1; i < json[0]["prices"].length; i++){
var price = json[0]["prices"][i]
max = price > 100 ? price : max
points.push([i, price])
ticksx.push([i, "Week " + i])
}
log(points)
var plot1 = $.jqplot('ManagerLeaguePrice', [points], {
series:[{color: '#5FAB78'}],
title: 'Ranking',
axes:{
xaxis:{
label:'Time',
min: 0,
ticks: ticksx,
tickOptions:{
formatString:'Time %s'
}
},
yaxis:{
label:'Rank',
min: 0,
max: Math.ceil(max/25)*25,
numberTicks: max / 25 + 1,
tickOptions:{
formatString:'%d r'
}
},
axesDefaults: {
labelRenderer: $.jqplot.CanvasAxisLabelRenderer
},
grid: {
backgroundColor: '#DEA493'
},
}
});
} catch (e) {
log("Error parsing Manager League")
log(e)
}
}).fail(function(e){
log("Error loading Manager League")
log(e);
});
}
/**************************************
SPAMMERS BE GONE BLACKLISTEDTHREADS
**************************************/
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 = 4;
showIgnoreCheckBox(newColumnCountOnPage);
hideIgnoredThreads();
}
$(".checkbox").on("change", function(){
if(this.checked) {
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 = "
Ignore ";
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) {
// var postId = $(this).find('a:first').attr('href');
if(postId = $(this).find('a:first').attr('href')) {
$(this).append("
");
}
}
});
}
/**
* 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();
}
})
}
})
}
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();
});
// var id = Number(sessionStorage.getItem("profileAccordion")) || false;
// $( "#accordion" ).accordion({
// collapsible: true,
// heightStyle: "content",
// active: id,
// activate: function( event, ui ) {
// var id = $("#MainSiteContent table table h3").index(ui.newHeader)
// sessionStorage.setItem("profileAccordion", id)
// },
// });
}
/**************************************
RANDOMIZED BONUSES
**************************************/
// Compute Player Ids
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) {
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 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)
}
}
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, " "));
}
/**************************************
SNOWFALL JQUERY PLUGIN
**************************************/
if (!Date.now)
Date.now = function() { return new Date().getTime(); };
(function() {
'use strict';
var vendors = ['webkit', 'moz'];
for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {
var vp = vendors[i];
window.requestAnimationFrame = window[vp+'RequestAnimationFrame'];
window.cancelAnimationFrame = (window[vp+'CancelAnimationFrame']
|| window[vp+'CancelRequestAnimationFrame']);
}
if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) // iOS6 is buggy
|| !window.requestAnimationFrame || !window.cancelAnimationFrame) {
var lastTime = 0;
window.requestAnimationFrame = function(callback) {
var now = Date.now();
var nextTime = Math.max(lastTime + 16, now);
return setTimeout(function() { callback(lastTime = nextTime); },
nextTime - now);
};
window.cancelAnimationFrame = clearTimeout;
}
}());
function setupSnowflakes() {
$.snowfall = function(element, options){
var flakes = [],
defaults = {
flakeCount : 50,
flakeColor : '#ffffff',
flakePosition: 'absolute',
flakeIndex: 999999,
minSize : 1,
maxSize : 2,
minSpeed : 1,
maxSpeed : 5,
round : false,
shadow : false,
collection : false,
collectionHeight : 40,
deviceorientation : false
},
options = $.extend(defaults, options),
random = function random(min, max){
return Math.round(min + Math.random()*(max-min));
};
$(element).data("snowfall", this);
// Snow flake object
function Flake(_x, _y, _size, _speed){
// Flake properties
this.x = _x;
this.y = _y;
this.size = _size;
this.speed = _speed;
this.step = 0;
this.stepSize = random(1,10) / 100;
if(options.collection){
this.target = canvasCollection[random(0,canvasCollection.length-1)];
}
var flakeMarkup = null;
if(options.image){
flakeMarkup = document.createElement("img");
flakeMarkup.src = options.image;
}else{
flakeMarkup = document.createElement("div");
$(flakeMarkup).css({'background' : options.flakeColor});
}
$(flakeMarkup).attr({
'class': 'snowfall-flakes',
}).css({
'width' : this.size,
'height' : this.size,
'position' : options.flakePosition,
'top' : this.y,
'left' : this.x,
'fontSize' : 0,
'zIndex' : options.flakeIndex
});
if($(element).get(0).tagName === $(document).get(0).tagName){
$('body').append($(flakeMarkup));
element = $('body');
}else{
$(element).append($(flakeMarkup));
}
this.element = flakeMarkup;
// Update function, used to update the snow flakes, and checks current snowflake against bounds
this.update = function(){
this.y += this.speed;
if(this.y > (elHeight) - (this.size + 6)){
this.reset();
}
this.element.style.top = this.y + 'px';
this.element.style.left = this.x + 'px';
this.step += this.stepSize;
if (doRatio === false) {
this.x += Math.cos(this.step);
} else {
this.x += (doRatio + Math.cos(this.step));
}
// Pileup check
if(options.collection){
if(this.x > this.target.x && this.x < this.target.width + this.target.x && this.y > this.target.y && this.y < this.target.height + this.target.y){
var ctx = this.target.element.getContext("2d"),
curX = this.x - this.target.x,
curY = this.y - this.target.y,
colData = this.target.colData;
if(colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] !== undefined || curY+this.speed+this.size > this.target.height){
if(curY+this.speed+this.size > this.target.height){
while(curY+this.speed+this.size > this.target.height && this.speed > 0){
this.speed *= .5;
}
ctx.fillStyle = "#fff";
if(colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] == undefined){
colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] = 1;
ctx.fillRect(curX, (curY)+this.speed+this.size, this.size, this.size);
}else{
colData[parseInt(curX)][parseInt(curY+this.speed)] = 1;
ctx.fillRect(curX, curY+this.speed, this.size, this.size);
}
this.reset();
}else{
// flow to the sides
this.speed = 1;
this.stepSize = 0;
if(parseInt(curX)+1 < this.target.width && colData[parseInt(curX)+1][parseInt(curY)+1] == undefined ){
// go left
this.x++;
}else if(parseInt(curX)-1 > 0 && colData[parseInt(curX)-1][parseInt(curY)+1] == undefined ){
// go right
this.x--;
}else{
//stop
ctx.fillStyle = "#fff";
ctx.fillRect(curX, curY, this.size, this.size);
colData[parseInt(curX)][parseInt(curY)] = 1;
this.reset();
}
}
}
}
}
if(this.x + this.size > (elWidth) - widthOffset || this.x < widthOffset){
this.reset();
}
}
// Resets the snowflake once it reaches one of the bounds set
this.reset = function(){
this.y = 0;
this.x = random(widthOffset, elWidth - widthOffset);
this.stepSize = random(1,10) / 100;
this.size = random((options.minSize * 100), (options.maxSize * 100)) / 100;
this.element.style.width = this.size + 'px';
this.element.style.height = this.size + 'px';
this.speed = random(options.minSpeed, options.maxSpeed);
}
}
// local vars
var i = 0,
elHeight = $(element).height(),
elWidth = $(element).width(),
widthOffset = 0,
snowTimeout = 0;
// Collection Piece ******************************
if(options.collection !== false){
var testElem = document.createElement('canvas');
if(!!(testElem.getContext && testElem.getContext('2d'))){
var canvasCollection = [],
elements = $(options.collection),
collectionHeight = options.collectionHeight;
for(var i =0; i < elements.length; i++){
var bounds = elements[i].getBoundingClientRect(),
$canvas = $('
',
{
'class' : 'snowfall-canvas'
}),
collisionData = [];
if(bounds.top-collectionHeight > 0){
$('body').append($canvas);
$canvas.css({
'position' : options.flakePosition,
'left' : bounds.left + 'px',
'top' : bounds.top-collectionHeight + 'px'
})
.prop({
width: bounds.width,
height: collectionHeight
});
for(var w = 0; w < bounds.width; w++){
collisionData[w] = [];
}
canvasCollection.push({
element : $canvas.get(0),
x : bounds.left,
y : bounds.top-collectionHeight,
width : bounds.width,
height: collectionHeight,
colData : collisionData
});
}
}
}else{
// Canvas element isnt supported
options.collection = false;
}
}
// ************************************************
// This will reduce the horizontal scroll bar from displaying, when the effect is applied to the whole page
if($(element).get(0).tagName === $(document).get(0).tagName){
widthOffset = 25;
}
// Bind the Window resize event so we can get the innerHeight again
$(window).bind("resize", function(){
elHeight = $(element)[0].clientHeight;
elWidth = $(element)[0].offsetWidth;
});
// initialize the flakes
for(i = 0; i < options.flakeCount; i+=1){
flakes.push(new Flake(random(widthOffset,elWidth - widthOffset), random(0, elHeight), random((options.minSize * 100), (options.maxSize * 100)) / 100, random(options.minSpeed, options.maxSpeed)));
}
// This adds the style to make the snowflakes round via border radius property
if(options.round){
$('.snowfall-flakes').css({'-moz-border-radius' : options.maxSize, '-webkit-border-radius' : options.maxSize, 'border-radius' : options.maxSize});
}
// This adds shadows just below the snowflake so they pop a bit on lighter colored web pages
if(options.shadow){
$('.snowfall-flakes').css({'-moz-box-shadow' : '1px 1px 1px #555', '-webkit-box-shadow' : '1px 1px 1px #555', 'box-shadow' : '1px 1px 1px #555'});
}
// On newer Macbooks Snowflakes will fall based on deviceorientation
var doRatio = false;
if (options.deviceorientation) {
$(window).bind('deviceorientation', function(event) {
doRatio = event.originalEvent.gamma * 0.1;
});
}
// this controls flow of the updating snow
function snow(){
for( i = 0; i < flakes.length; i += 1){
flakes[i].update();
}
snowTimeout = requestAnimationFrame(function(){snow()});
}
snow();
// clears the snowflakes
this.clear = function(){
$('.snowfall-canvas').remove();
$(element).children('.snowfall-flakes').remove();
cancelAnimationFrame(snowTimeout);
}
};
// Initialize the options and the plugin
$.fn.snowfall = function(options){
if(typeof(options) == "object" || options == undefined){
return this.each(function(i){
(new $.snowfall(this, options));
});
}else if (typeof(options) == "string") {
return this.each(function(i){
var snow = $(this).data('snowfall');
if(snow){
snow.clear();
}
});
}
};
ifSettingIsEnabled('showSnow', function() {
var flakes;
ifSettingIsEnabled('snowLight', function() {
flakes = pageIsGame() ? 40 : 125
$(document).snowfall({flakeCount : flakes});
}, function() {
flakes = pageIsGame() ? 75 : 225
$(document).snowfall({flakeCount : flakes});
})
}, function() {
})
}
/**************************************
Burn
**************************************/
function setupBurn() {
(function(e){function f(a){this.burning=null;this.settings=a;return this}var d={a:0.3,k:0.05,w:10,wind:1,strength:1,diffusion:1,flames:[{x:0,hsla:[58,96,89,1],y:0,blur:0.1},{x:0,hsla:[51,98,76,1],y:0.02,blur:0.15},{x:0,hsla:[36,100,60,1],y:0.04,blur:0.2},{x:0,hsla:[28,91,49,1],y:0.08,blur:0.25},{x:0,hsla:[19,94,41,1],y:0.15,blur:0.3},{x:0,hsla:[15,75,34,1],y:0.2,blur:0.4},{x:0,hsla:[14,66,16,1],y:0.5,blur:0.5}]};e.fn.burn=function(a,c){var b;if(!1===a)return(b=this.data("_burn"))&&b.off(),this;if("object"===typeof a)c=a;else if("string"==typeof a)return(b=this.data("_burn"))&&void 0!==d[a]?void 0!==c?("title"==a&&b.content.html(c),b.settings[a]=c,!0):b.settings[a]:!1;c=e.extend({},d,c||{});return this.each(function(){var a=e.extend(!0,{},c),a=new f(a);a.elem=e(this);a.ignite();a.elem.data("_burn",a)})};f.prototype={ignite:function(){var a=this;if(a.burning)return a.burning;a.oldShadow=a.elem.css("text-shadow");(function b(){a.timer=window.requestAnimationFrame(b);a.burn()})()},wave:function(a,c,b){var g=this.settings;return b*g.a*Math.sin(g.k*a-g.w*c)},burn:function(){var a=this,c=this.settings,b;b=e.map(c.flames,function(b){var e=-b.y,d=Math.sqrt(Math.random());b.x=a.wave(b.y,Date.now()/1E3,d);return(b.x+c.wind)*b.y*c.strength*c.diffusion+"em "+e*c.strength*c.diffusion+"em "+b.blur*c.strength*c.diffusion+"em hsla("+b.hsla[0]+", "+b.hsla[1]+"%, "+b.hsla[2]+"%, "+b.hsla[3]+")"});a.elem.css("text-shadow",b.join(", "))},off:function(){window.cancelAnimationFrame(this.timer);this.timer=null;this.elem.css("text-shadow",this.oldShadow)}}})(jQuery);(function(){for(var e=0,f=["ms","moz","webkit","o"],d=0;d
$1"));
$(this).html($(this).html().replace(/hot/g, "hot "));
$(this).html($(this).html().replace(/(3[0-9] degrees)/g, "$1 "));
$(this).html($(this).html().replace(/31°/g, "31° "));
});
$(".burning").burn({w: 15})
}
})
}
/**************************************
Textarea HTML Box
**************************************/
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 browserIsFirefox() {
return navigator.userAgent.toLowerCase().indexOf('firefox') > -1
}
/**************************************
INDEXED DB
**************************************/
function setupDatabase() {
log("indexedDB start setup")
window.Database = {
db: null,
Table: {
Bookmarks: "Bookmarks",
Settings: "Settings",
BlacklistedForumThreads: "BlacklistedForumThreads",
TournamentData: "TournamentData"
},
Exports: {
Bookmarks: "Bookmarks",
Settings: "Settings",
BlacklistedForumThreads: "BlacklistedForumThreads"
},
Row: {
BlacklistedForumThreads: {
ThreadId: "threadId",
Date: "date"
},
Bookmarks: {
Order: "order"
},
Settings: {
Name: "name"
},
TournamentData: {
Id: "tournamentId",
}
},
init: function(callback) {
log("indexedDB start init")
if(!"indexedDB" in window) {
log("IndexedDB not supported")
return;
}
var openRequest = indexedDB.open("TidyUpYourDashboard_v3", 3);
openRequest.onupgradeneeded = function(e) {
var thisDB = e.target.result;
if(!thisDB.objectStoreNames.contains("Bookmarks")) {
var objectStore = thisDB.createObjectStore("Bookmarks", {autoIncrement:true});
objectStore.createIndex("order", "order", {unique:true});
}
if(!thisDB.objectStoreNames.contains("Settings")) {
var objectStore = thisDB.createObjectStore("Settings", { keyPath: "name" });
objectStore.createIndex("name", "name", {unique: true});
objectStore.createIndex("value", "value", {unique: false});
}
if(!thisDB.objectStoreNames.contains("BlacklistedForumThreads")) {
var objectStore = thisDB.createObjectStore("BlacklistedForumThreads", {autoIncrement:true});
objectStore.createIndex("threadId", "threadId", {unique:true});
objectStore.createIndex("date", "date", {unique:false});
}
if(!thisDB.objectStoreNames.contains("TournamentData")) {
var objectStore = thisDB.createObjectStore("TournamentData",{ keyPath: "tournamentId" });
objectStore.createIndex("tournamentId", "tournamentId", {unique:true});
objectStore.createIndex("value", "value", {unique: false});
}
}
openRequest.onsuccess = function(e) {
log("indexedDB init sucessful");
db = e.target.result;
callback()
}
openRequest.onerror = function(e) {
log("Error Init IndexedDB")
log(e.target.error)
// alert("Sorry, Tidy Up Your Dashboard is not supported")
$("Sorry, Tidy Up Your Dashboard is not supported.
").dialog();
}
},
update: function(table, value, key, callback) {
var transaction = db.transaction([table],"readwrite");
var store = transaction.objectStore(table);
//Perform the add
try {
var request = store.put(value, key != undefined ? Number(key) : undefined);
request.onerror = function(e) {
log(`Error saving ${JSON.stringify(value)} in ${table}`)
log(JSON.stringify(e));
}
request.onsuccess = function(e) {
log(`Saved ${JSON.stringify(value)} in ${table}`)
callback()
}
} catch(e) {
log(`Error saving ${JSON.stringify(value)} in ${table}`)
log(JSON.stringify(e));
}
},
read: function(table, key, callback) {
var transaction = db.transaction([table], "readonly");
var objectStore = transaction.objectStore(table);
var ob = objectStore.get(Number(key));
ob.onsuccess = function(e) {
var result = e.target.result;
callback(result)
}
},
readIndex: function(table, row, value, callback) {
var transaction = db.transaction([table], "readonly");
var objectStore = transaction.objectStore(table);
var index = objectStore.index(row);
//name is some value
var ob = index.get(value);
ob.onsuccess = function(e) {
var result = e.target.result;
callback(result)
}
},
readAll: function(table, callback) {
var transaction = db.transaction([table], "readonly");
var objectStore = transaction.objectStore(table);
var items = []
var ob = objectStore.openCursor()
ob.onsuccess = function(e) {
var cursor = e.target.result;
if (cursor) {
var item = cursor.value;
item.id = cursor.primaryKey;
items.push(item);
cursor.continue();
} else {
callback(items)
}
}
},
add: function(table, value, callback) {
var transaction = db.transaction([table],"readwrite");
var store = transaction.objectStore(table);
try {
var request = store.add(value);
request.onerror = function(e) {
log(`Error saving ${JSON.stringify(value)} in ${table}`)
log(JSON.stringify(e));
}
request.onsuccess = function(e) {
log(`Saved ${JSON.stringify(value)} in ${table}`)
callback()
}
} catch(e) {
log(`Error saving ${JSON.stringify(value)} in ${table}`)
log(JSON.stringify(e));
}
request.onerror = function(e) {
log(`Error saving ${JSON.stringify(value)} in ${table}`)
log(JSON.stringify(e));
}
request.onsuccess = function(e) {
log(`Saved ${JSON.stringify(value)} in ${table}`)
callback()
}
},
delete: function(table, key, callback) {
var transaction = db.transaction([table],"readwrite");
var store = transaction.objectStore(table);
//Perform the add
var request = store.delete(key)
request.onerror = function(e) {
log("Error deleting in " + table)
log(e.target.error);
//some type of error handler
}
request.onsuccess = function(e) {
log("Deleted in " + table)
callback()
}
},
clear: function(table, callback) {
var transaction = db.transaction([table],"readwrite");
var store = transaction.objectStore(table);
//Perform the add
var request = store.clear();
request.onerror = function(e) {
log("Error clearing " + table)
log(e.target.error);
//some type of error handler
}
request.onsuccess = function(e) {
log("Cleared " + table)
callback()
}
},
}
}
/**************************************
Other
**************************************/
function addCSS(css) {
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
}
function addVersionLabel() {
if(!pageIsGame() && !pageIsExamineMap() && !pageIsDesignMap()) {
$("body").append('' + GM_info.script.version +'
')
createSelector(".versionLabel", "position:fixed; right:0; bottom: 0; padding: 5px; color: #555; font-size: 10px; cursor:pointer")
$(".versionLabel").on("click", showUserscriptMenu)
}
}
function WLJSDefined() {
return (typeof WLJSLoaded) != "undefined" && WLJSLoaded();
}
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 getPlotCSS() {
return `.jqplot-target{position:relative;color:#666;font-family:"Trebuchet MS",Arial,Helvetica,sans-serif;font-size:1em;}.jqplot-axis{font-size:.75em;}.jqplot-xaxis{margin-top:10px;}.jqplot-x2axis{margin-bottom:10px;}.jqplot-yaxis{margin-right:10px;}.jqplot-y2axis,.jqplot-y3axis,.jqplot-y4axis,.jqplot-y5axis,.jqplot-y6axis,.jqplot-y7axis,.jqplot-y8axis,.jqplot-y9axis{margin-left:10px;margin-right:10px;}.jqplot-axis-tick,.jqplot-xaxis-tick,.jqplot-yaxis-tick,.jqplot-x2axis-tick,.jqplot-y2axis-tick,.jqplot-y3axis-tick,.jqplot-y4axis-tick,.jqplot-y5axis-tick,.jqplot-y6axis-tick,.jqplot-y7axis-tick,.jqplot-y8axis-tick,.jqplot-y9axis-tick{position:absolute;}.jqplot-xaxis-tick{top:0;left:15px;vertical-align:top;}.jqplot-x2axis-tick{bottom:0;left:15px;vertical-align:bottom;}.jqplot-yaxis-tick{right:0;top:15px;text-align:right;}.jqplot-yaxis-tick.jqplot-breakTick{right:-20px;margin-right:0;padding:1px 5px 1px 5px;z-index:2;font-size:1.5em;}.jqplot-y2axis-tick,.jqplot-y3axis-tick,.jqplot-y4axis-tick,.jqplot-y5axis-tick,.jqplot-y6axis-tick,.jqplot-y7axis-tick,.jqplot-y8axis-tick,.jqplot-y9axis-tick{left:0;top:15px;text-align:left;}.jqplot-meterGauge-tick{font-size:.75em;color:#999;}.jqplot-meterGauge-label{font-size:1em;color:#999;}.jqplot-xaxis-label{margin-top:10px;font-size:11pt;position:absolute;}.jqplot-x2axis-label{margin-bottom:10px;font-size:11pt;position:absolute;}.jqplot-yaxis-label{margin-right:10px;font-size:11pt;position:absolute;}.jqplot-y2axis-label,.jqplot-y3axis-label,.jqplot-y4axis-label,.jqplot-y5axis-label,.jqplot-y6axis-label,.jqplot-y7axis-label,.jqplot-y8axis-label,.jqplot-y9axis-label{font-size:11pt;position:absolute;}table.jqplot-table-legend{margin-top:12px;margin-bottom:12px;margin-left:12px;margin-right:12px;}table.jqplot-table-legend,table.jqplot-cursor-legend{background-color:rgba(255,255,255,0.6);border:1px solid #ccc;position:absolute;font-size:.75em;}td.jqplot-table-legend{vertical-align:middle;}td.jqplot-seriesToggle:hover,td.jqplot-seriesToggle:active{cursor:pointer;}td.jqplot-table-legend>div{border:1px solid #ccc;padding:1px;}div.jqplot-table-legend-swatch{width:0;height:0;border-top-width:5px;border-bottom-width:5px;border-left-width:6px;border-right-width:6px;border-top-style:solid;border-bottom-style:solid;border-left-style:solid;border-right-style:solid;}.jqplot-title{top:0;left:0;padding-bottom:.5em;font-size:1.2em;}table.jqplot-cursor-tooltip{border:1px solid #ccc;font-size:.75em;}.jqplot-cursor-tooltip{border:1px solid #ccc;font-size:.75em;white-space:nowrap;background:rgba(208,208,208,0.5);padding:1px;}.jqplot-highlighter-tooltip{border:1px solid #ccc;font-size:.75em;white-space:nowrap;background:rgba(208,208,208,0.5);padding:1px;}.jqplot-point-label{font-size:.75em;z-index:2;}td.jqplot-cursor-legend-swatch{vertical-align:middle;text-align:center;}div.jqplot-cursor-legend-swatch{width:1.2em;height:.7em;}.jqplot-error{text-align:center;}.jqplot-error-message{position:relative;top:46%;display:inline-block;}div.jqplot-bubble-label{font-size:.8em;padding-left:2px;padding-right:2px;color:rgb(20%,20%,20%);}div.jqplot-bubble-label.jqplot-bubble-label-highlight{background:rgba(90%,90%,90%,0.7);}div.jqplot-noData-container{text-align:center;background-color:rgba(96%,96%,96%,0.3);}`
}
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'
}
}
function setupAWPWorldTour() {
if($("title").text().toLowerCase().indexOf("awp world tour") != -1) {
setupAWPRanking();
setupAWPEvents();
$("#MainSiteContent div:first").after("
")
$("#MainSiteContent div:first").css("float", "left")
$("#MainSiteContent div:first").css("width", "60%")
$("#MainSiteContent > table").css("width", "100%")
addCSS(`
.awp {
float: left;
margin: 60px 0 20px 20px;
width: 30%;
max-width: 400px;
}
.AWPRanking {
margin-bottom: 20px;
width: 100%;
}
.awpUpdated {
color: gray;
float: right;
font-size: 11px;
`)
}
}
function setupAWPRanking() {
var minRow = 12;
var maxRow = 30;
var minCol = 1;
var maxCol = 25;
var url = `https://spreadsheets.google.com/feeds/cells/1YuV5WqthgmYsZqv4rFVSE1xhM0BKVrcbkivRZ8ht6-E/1/public/values?min-row=${minRow}&max-row=${maxRow}&min-col=${minCol}&max-col=${maxCol}&alt=json-in-script&callback=parseAWPRankingData`
$.ajax({
url: url,
dataType: "script",
});
}
function setupAWPEvents() {
var minRow = 10;
var minCol = 1;
var maxCol = 6;
var url = `https://spreadsheets.google.com/feeds/cells/1YuV5WqthgmYsZqv4rFVSE1xhM0BKVrcbkivRZ8ht6-E/2/public/values?min-row=${minRow}&min-col=${minCol}&max-col=${maxCol}&alt=json-in-script&callback=parseAWPEventData`
$.ajax({
url: url,
dataType: "script",
});
}
window.parseAWPEventData = function(data) {
var entries = data.feed.entry
var lastUpdated = moment(data.feed.updated.$t)
var table = $('')
var tbody = $(" ")
var tr = $(" ");
var events = [];
var event = {finished: true};
var currentRow = entries[0].gs$cell.row
try {
$.each(entries, function(key, entry){
var col = entry.gs$cell.col
var row = entry.gs$cell.row
if((row - currentRow) >= 3) {
currentRow = row;
events.push(event)
if(event.url.match(/forum/i)) {
return;
}
event = {finished: true}
}
if(col == 1 && entry.content.$t) {
event.url = entry.content.$t.match(/docs.google.com/i) ? undefined : entry.content.$t
} else if(col == 3) {
event.date = entry.content.$t
} else if(col == 4) {
if(event.name == undefined) {
event.name = entry.content.$t
} else if(event.series == undefined) {
event.series = entry.content.$t
}
} else if(col == 5) {
event.champion = entry.content.$t
} else if(col == 6) {
event.finished = false
}
})
} catch(e) {
log("error parsing awp event data")
log(e)
}
var eventRows = events.filter(function(e){
return e.url && Math.abs(moment().diff(moment(e.date), 'days')) < 150
}).map(function(e){
return `
${moment(e.date).format('DD/MMM')}
${e.name} ${e.series}
${e.finished ? e.champion : (e.url.match(/tournament/i) ? "in progress" : "not started")}
`
}).join("")
tbody.append(eventRows)
tbody.append(`Show All Updated ${lastUpdated.from()} `)
table.append(tbody);
$(".awp").append(table.outerHTML())
}
window.parseAWPRankingData = function(data) {
var entries = data.feed.entry
var lastUpdated = moment(data.feed.updated.$t)
var table = $('')
var tbody = $(" ")
var tr = $(" ");
var url;
try {
$.each(entries, function(key, entry){
var col = entry.gs$cell.col
var row = entry.gs$cell.row
if(col == 1) {
url = entry.content.$t;
} else if(col == 3) {
//rank
tr.append($(`${entry.content.$t} `))
} else if(col == 5) {
//name
tr.append($(`${entry.content.$t} `))
} else if(col == 25) {
//points
tr.append($(`${entry.content.$t} `))
tbody.append(tr)
tr = $(" ");
}
})
} catch(e) {
log("error parsing awp event data")
log(JSON.parse(e))
}
table.append(tbody);
tbody.append(`Show All Updated ${lastUpdated.from()} `)
$(".awp").prepend(table.outerHTML())
}
/**************************************
Community Levels
**************************************/
function setupCommunityLevels() {
var fonts = $("#LevelsTable tr td:nth-of-type(2) font:nth-of-type(1)")
$.each(fonts, function(key, font){
$(font).html($(font).html().replace(" 0 wins", " 0 wins "))
})
$("#MainSiteContent").wrapInner("
")
$("#MainSiteContent").wrapInner("
")
$("#content").append(`
Popular New Levels
Most Liked Levels
Most Difficult Levels
Most Played Levels
Most Records (Player)
Most Records (Clan)
Top Creators
Your Levels
This data is updated every 12 hours.
`)
$("#content").prepend(`
`)
$("h1").prependTo("#MainSiteContent")
$("#content").tabs();
$("#sorted").tabs();
$(".searchLevelBtn").on("click", function() {
searchLevel()
})
$('.searchLevelInput').keyup(function(e){
if(e.keyCode == 13) {
searchLevel()
}
});
addCSS(`
.ui-tabs {
border: none;
background: none;
}
.ui-tabs-nav {
background: none;
border: none;
border-bottom: 1px gray solid;
}
.striped th, .striped td {
border-bottom: 1px gray solid;
text-align: left;
}
`)
var mainjsReady = $.Deferred();
$(".tab_hot").on("click", function() {
$.when(mainjsReady).done(function () {
$.each($("#tab_hot tr[data-levelid]:visible"), function(key, row) {
var id = $(row).attr("data-levelid")
loadLevelData(id)
})
})
})
$(".tab_liked").on("click", function() {
$.when(mainjsReady).done(function () {
$.each($("#tab_liked tr[data-levelid]:visible"), function(key, row) {
var id = $(row).attr("data-levelid")
loadLevelData(id)
})
})
})
$(".tab_hardest").on("click", function() {
$.when(mainjsReady).done(function () {
$.each($("#tab_hardest tr[data-levelid]:visible"), function(key, row) {
var id = $(row).attr("data-levelid")
loadLevelData(id)
})
})
})
$(".tab_mostplayed").on("click", function() {
$.when(mainjsReady).done(function () {
$.each($("#tab_mostplayed tr[data-levelid]:visible"), function(key, row) {
var id = $(row).attr("data-levelid")
loadLevelData(id)
})
})
})
$.ajax({
type: 'GET',
url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=7`,
dataType: 'jsonp',
crossDomain: true,
}).done(function (response) {
if (response.data) {
var levels = response.data
$("#tab_hot").append(``)
$.each(levels, function (key, level) {
$("#HotLevelsTable").append(renderLevelRow(level, key))
$(`[data-levelid='${level.levelId}']`).attr("data-rating", level.rating)
})
$("#HotLevelsTable").append("Load More ")
$("#loadMoreHot").on("click", function() {
$.each($("#tab_hot tr:hidden:lt(5)"), function(key, row) {
$(this).fadeIn()
$.when(mainjsReady).done(function () {
loadLevelData($(row).attr("data-levelid"))
})
})
if($("#tab_hot tr:hidden:lt(5)").length == 0) {
$("#loadMoreHot").remove();
}
})
}
});
$.ajax({
type: 'GET',
url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=8`,
dataType: 'jsonp',
crossDomain: true,
}).done(function (response) {
if (response.data) {
var levels = response.data
$("#tab_liked").append(``)
$.each(levels, function (key, level) {
$("#MostLikedLevels").append(renderLevelRow(level, key))
$(`[data-levelid='${level.levelId}']`).attr("data-rating", level.rating)
})
$("#MostLikedLevels").append("Load More ")
$("#loadMoreLiked").on("click", function() {
$.each($("#tab_liked tr:hidden:lt(5)"), function(key, row) {
$(this).fadeIn()
$.when(mainjsReady).done(function () {
loadLevelData($(row).attr("data-levelid"))
})
})
if($("#tab_liked tr:hidden:lt(5)").length == 0) {
$("#loadMoreLiked").remove();
}
})
}
});
$.ajax({
type: 'GET',
url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=1`,
dataType: 'jsonp',
crossDomain: true,
}).done(function (response) {
if (response.data) {
var levels = response.data
$("#tab_hardest").append(``)
$.each(levels, function (key, level) {
$("#HardestLevelsTable").append(renderLevelRow(level, key))
})
$("#HardestLevelsTable").append("Load More ")
$("#loadMoreDifficult").on("click", function() {
$.each($("#tab_hardest tr:hidden:lt(5)"), function(key, row) {
$(this).fadeIn()
$.when(mainjsReady).done(function () {
loadLevelData($(row).attr("data-levelid"))
})
})
if($("#tab_hardest tr:hidden:lt(5)").length == 0) {
$("#loadMoreDifficult").remove();
}
})
}
});
$.ajax({
type: 'GET',
url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=2`,
dataType: 'jsonp',
crossDomain: true,
}).done(function (response) {
if (response.data) {
var levels = response.data
$("#tab_mostplayed").append(``)
$.each(levels, function (key, level) {
$("#MostPlayedLevelsTable").append(renderLevelRow(level, key))
})
$("#MostPlayedLevelsTable").append("Load More ")
$("#loadMoreMostPlayed").on("click", function() {
$.each($("#tab_mostplayed tr:hidden:lt(5)"), function(key, row) {
$(this).fadeIn()
$.when(mainjsReady).done(function () {
loadLevelData($(row).attr("data-levelid"))
})
})
if($("#tab_mostplayed tr:hidden:lt(5)").length == 0) {
$("#loadMoreMostPlayed").remove();
}
})
}
});
$.ajax({
type: 'GET',
url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=3`,
dataType: 'jsonp',
crossDomain: true,
}).done(function (response) {
if (response.data) {
var players = response.data
$("#tab_records_player").append(``)
$("#PlayerRecordsTable").prepend(`# Name Number of Records `)
$.each(players, function (key, player) {
$("#PlayerRecordsTable").append(renderRecordPlayerRow(player, key))
})
}
});
$.ajax({
type: 'GET',
url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=4`,
dataType: 'jsonp',
crossDomain: true,
}).done(function (response) {
if (response.data) {
var clans = response.data
$("#tab_records_clan").append(``)
$("#ClanRecordsTable").prepend(`# Name Number of Records `)
$.each(clans, function (key, clan) {
$("#ClanRecordsTable").append(renderClanRow(clan, key))
})
}
});
$.ajax({
type: 'GET',
url: `https://w115l144.hoststar.ch/wl/communityLevels.php?m=6`,
dataType: 'jsonp',
crossDomain: true,
}).done(function (response) {
if (response.data) {
var players = response.data
$("#tab_topCreators").append(``)
$("#CreatorsTable").prepend(`# Name Total Likes Total Attempts Total Wins Overall Win Rate Total Levels - `)
$.each(players, function (key, player) {
$("#CreatorsTable tbody").append(renderCreatorPlayerRow(player, key))
})
var dataTable = $$$("#CreatorsTable").DataTable({
paging: false,
sDom: 't',
});
}
});
var id = $(".TopRightBar a:nth-of-type(2)").attr("href").match("[0-9]+")[0];
$.ajax({
type: 'GET',
url: `https://w115l144.hoststar.ch/wl/communityLevels.php?p=${id}`,
dataType: 'jsonp',
crossDomain: true,
}).done(function (response) {
if (response.data) {
var levels = response.data
$("#tab_ownLevels").append(``)
$.each(levels, function (key, level) {
$("#OwnLevelsTable").append(renderLevelRow(level, key, true))
})
}
});
var div = $("
")
var mainjs = "";
div.load('https://www.warlight.net/SinglePlayer/Level?ID=882053', function(){
mainjs = div.find("script:contains(MainJS.Init)").html()
$.getScript("https://d2wcw7vp66n8b3.cloudfront.net/js/Release/wl.js?v=636045359309573936")
.done(function() {
eval(mainjs);
$("#WaitDialogJSWhiteBox").remove();
$("#WaitDialogJSBacking").remove();
mainjsReady.resolve();
})
});
}
function searchLevel() {
var query = $(".searchLevelInput").val().toLowerCase();
$(".foundLevels *").remove();
$.ajax({
type: 'GET',
url: `https://w115l144.hoststar.ch/wl/communityLevels.php?q=${query}`,
dataType: 'jsonp',
crossDomain: true,
}).done(function (response) {
if (response.data) {
if(response.data.length > 0) {
var levels = response.data
$(".foundLevels").append(``)
$.each(levels, function (key, level) {
$("#FoundLevelTable").append(renderLevelRow(level, key))
})
} else {
$(".foundLevels").append(`No levels found! `)
}
} else {
$(".foundLevels").append(`Error searching for levels `)
}
});
}
function addCSS(css) {
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
}
function decode (str) {
var decoded = "";
try {
decoded = decodeURIComponent((str + '')
.replace(/%(?![\da-f]{2})/gi, function () {
return '%25'
})
.replace(/\+/g, '%20'))
} catch(e) {
decoded = unescape(str);
}
return decoded;
return decodeURIComponent((str + '')
.replace(/%(?![\da-f]{2})/gi, function () {
// PHP tolerates poorly formed escape sequences
return '%25'
})
.replace(/\+/g, '%20'))
}
function renderRecordPlayerRow(player, key) {
var rank = getRankHtml(key+1)
return `
${rank}
${player.recordClanId > 0 ? ' ' : ''}
${decode(player.recordHolderName)}
${player.numOfRecords}
`
}
function renderCreatorPlayerRow(player, key) {
var id = player.createdByUrl.match(/[0-9]+/)[0]
var rank = getRankHtml(key+1)
return `
${rank}
${player.creatorClanId > 0 ? ' ' : ''}
${decode(player.createdByName)}
${player.numOfTotalLikes}
${player.numOfTotalAttempts}
${player.numOfTotalWins}
${(player.numOfTotalWins / player.numOfTotalAttempts * 100).toFixed(2)}%
${player.numOfCreatedLevels}
Show Levels
`
}
function renderClanRow(clan, key) {
var rank = getRankHtml(key+1)
return `
${rank}
${decode(clan.recordClanName)}
${clan.numOfRecords}
`
}
function renderLevelRow(level, key, showAll) {
return `
= 10 && showAll != true) ? 'style="display:none"' : ''}>
${key+1}. ${decode(level.name)}
${level.likes} likes, ${level.wins} wins in ${level.attempts} attempts
Created by ${level.creatorClanId > 0 ? ' ' : ''} ${decode(level.createdByName)}
Record holder: ${level.recordClanId > 0 ? ' ' : ''} ${level.recordHolderName ? '' + decode(level.recordHolderName) + ' ' + getTurnText(level.recordHolderText) : 'None'}
Win rate: ${level.percentage}%
Play
`
}
function getTurnText(turns) {
return ` in ${turns} ${turns > 1 ? 'turns' : 'turn'}`
}
function getRankHtml(rank) {
if(rank == 1) {
return ` `
} else if(rank == 2) {
return ` `
} else if(rank == 3) {
return ` `
}
return rank;
}
function loadLevelData(id) {
warlight_shared_viewmodels_spe_SPEManager.GetLevelResult(id, function (levelData) {
if(levelData && levelData.WinCount > 0) {
$(`[data-levelid="${id}"] td:nth-of-type(2)`).append(`You won ${getTurnText(levelData.WonInTurns)}`)
$(`[data-levelid="${id}"] td:nth-of-type(1)`).append(' ')
}
$(`[data-levelid="${id}"]`).attr("data-levelid", "done")
})
}