Tidy up your Dashboard

Customizable Userscript which tidies up your Dashboard!

12.09.2015 itibariyledir. En son verisyonu görün.

Bu betiği kurabilmeniz için Tampermonkey, Greasemonkey ya da Violentmonkey gibi bir kullanıcı betiği eklentisini kurmanız gerekmektedir.

Bu betiği kurabilmeniz için Tampermonkey ya da Violentmonkey gibi bir kullanıcı betiği eklentisini kurmanız gerekmektedir.

Bu betiği kurabilmeniz için Tampermonkey ya da Violentmonkey gibi bir kullanıcı betiği eklentisini kurmanız gerekmektedir.

Bu betiği kurabilmeniz için Tampermonkey ya da Userscripts gibi bir kullanıcı betiği eklentisini kurmanız gerekmektedir.

You will need to install an extension such as Tampermonkey to install this script.

Bu komut dosyasını yüklemek için bir kullanıcı komut dosyası yöneticisi uzantısı yüklemeniz gerekecek.

(Zaten bir kullanıcı komut dosyası yöneticim var, kurmama izin verin!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(Zateb bir user-style yöneticim var, yükleyeyim!)

// ==UserScript==
// @name Tidy up your Dashboard
// @namespace https://greasyfork.org/users/10154
// @grant none
// @match https://www.warlight.net/*
// @description Customizable Userscript which tidies up your Dashboard!
// @version 1.9.5.8
// @icon http://i.imgur.com/XzA5qMO.png
/*jslint browser: true, regexp: true*/
/*global $, jQuery*/
// ==/UserScript==


var version = "1.9.5.8";

function checkVersion() {
	var currentVersion = localStorage.getItem('version');
	
	if (currentVersion == version) {
		//Script Up to date
        
	} else if (currentVersion == undefined) {
		//Script new installed
        $(".userscript-show").fadeIn();
        $(".overlay").fadeIn();
	} else {
		//Script Updated
//        $("label[for='hidePromotedGames']").addClass('newSetting');
//        $("label[for='hideCoinsGlobally']").addClass('newSetting');
//        $(".userscript-show").fadeIn();
//        $(".overlay").fadeIn();
	}
	
	localStorage.setItem('version', version);
}


var lastRefresh;
var delayedFunction;
var myGamesTable = $("#MyGamesTable");
var openGamesTable = $("#OpenGamesTable");
var promotedGamesTable = $("#PromotedGamesTable");
var lastClick = new Date();

var openGamesFilters;

var userscriptSettings = [
    {id: 'scrollGames', text: 'Fixed Window with scrollable Games', selected: false, title: 'Dashboard', addBreak: false},
    {id: 'hideMyGamesIcons', text: 'Hide Icons in "My Games"', selected: false, title: '', addBreak: false},
    {id: 'autoRefreshOnFocus', text: 'Automatically refresh Games on Tab-Focus', selected: false, title: '', addBreak: false},
    {id: 'highlightTournaments', text: 'Highlight Tournament invites', selected: false, title: '', addBreak: false},
    {id: 'highlightNewForumPosts', text: 'Highlight new Clan Posts', selected: false, title: '', addBreak: false},
    {id: 'hideRightColumn', text: 'Hide Right Column', selected: false, title: '', addBreak: false},
    {id: 'showOpenGamesFilter', text: 'Enable Open Games Filter', selected: false, title: '', addBreak: false},
    {id: 'hidePromotedGames', text: 'Hide Promoted Games', selected: false, title: '', addBreak: false},
    {id: 'useDefaultBootLabel', text: 'Use the Default Boot Time Label', selected: false, title: '', addBreak: false},
    {id: 'showOpenGamesTab', text: 'Show Open Games Tab in Menu Bar', selected: false, title: 'Global', addBreak: false},
    {id: 'hideCoinsGlobally', text: 'Hide Coins Globally', selected: false, title: '', addBreak: false}
];



var showGamesActive = "ShowMyGames";

//Expand Games Buttons
var showAllGames = "";
var showAllCoinGames = "";

var openGames = [];
readLocalstorage();
setGlobalStyles();
setupUserscriptMenu();
checkVersion();

$.fn.settingIsEnabled = function (setting) {
    var selected = false;
    $.each(userscriptSettings, function (key, set) {
        if (set.id == setting) {
            selected = set.selected;
        }
    });
    return selected;
};

if (pageIsMultiplayer()) {
    //Show Open Games Link
    if (isEnabled('showOpenGamesTab')) {
		showOpenGamesLink();
	}
}

if (pageIsDashboard()) {
    
	setupRefreshFunction();
	expandGames();
	markJoinedGames();
	hideBlacklistedThreads();
    setupBasicDashboardStyles();

    if (isEnabled('showOpenGamesFilter')) {
        setupOpenGamesFilter();
    }

    if (isEnabled('highlightTournaments')) {
		createSelector("#MyTournamentsTable tbody", "background:#4C4C33;");
	}
    
    if (isEnabled('hidePromotedGames') || isEnabled('hideCoinsGlobally')) {
		createSelector("#PromotedGamesTable", "display:none");
	}
    
    if (isEnabled('hideMyGamesIcons')) {
		createSelector("#MyGamesTable td div img, #MyGamesTable td div a img", "display:none;");
	}

    if (isEnabled('highlightNewForumPosts')) {
        hightlightNewClanForumPosts();
	}
    
	if (isEnabled('scrollGames')) {
        setupFixedWindowWithScrollableGames();
	}
	
	if (isEnabled('hideRightColumn')) {
        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 () {
		if (isEnabled('scrollGames')) {
			refreshSingleColumnSize();
		}
	});
}

if (pageIsClanThread()) {
	registerClanThread();
		
}


/**
 * Globally Hide Coins 
 */
if (isEnabled('hideCoinsGlobally')) {
    $("#CoinsBtn").parent().next().css('left', 512);
    $("#CoinsBtn").parent().next().next().css('left', 635);
    $("#CoinsBtn").parent().next().next().next().css('left', 740);
    
    $("#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');
}



/**
 * Reads the User-Settings from Localstorage
 */
function readLocalstorage() {

	//Settings
    
    $.each(userscriptSettings, function (key, setting) {
        setting.selected = localStorage.getItem(setting.id) == "true";
    });
    
	//Filters
	var filters = localStorage.getItem("openGamesFilters");

	if (filters) {
		openGamesFilters = $.parseJSON(filters);	
	} else {
		openGamesFilters = {};	
	}

	hideCoinSymbol = true;
}

/**
 * Creates the Userscript-Menu
 */
function setupUserscriptMenu() {
    
    var inputs = '';
    
    $.each(userscriptSettings, function (key, setting) {
        if (setting.title != '') {
            inputs += '<span class="title">' + setting.title + '</span><br>';
        }
        inputs += '<label for="' + setting.id + '">' + setting.text + '</label><input type="checkbox" id="' + setting.id + '"><br>';
        if (setting.addBreak) {
            inputs += '<hr>';
        }
    });
    
	inputs += '<div class="close-userscript">Close and Refresh</div>';

	$("body").append("<div class='overlay' style='display: none'></div><div class='popup userscript-show' style='display: none'><div class='head'>Change Userscript Settings<img class='close-popup-img' src='https://i.imgur.com/RItbpDS.png' height='25' width='25'></div>" + inputs + "</div>");
	$(".userscript-show").on("change", function () {
		storeSettingsVariables();
	});
	$("#TopRightDropDown .dropdown-divider").before('<li><div class="userscript-menu">Userscript</div></li>');

	$(".userscript-menu").on("click", function () {
		$(".userscript-show").fadeIn();
		$(".overlay").fadeIn();
		$("#TopRightDropDown").fadeOut();
        $("embed#main").attr('wmode', 'transparent');
		$("embed#main").css('opacity', '0');
        $("embed#main").attr('align', 'left');
        
	});

	$(".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');
	});

	checkUserscriptMenuButtons();

}

function checkUserscriptMenuButtons() {
    $.each(userscriptSettings, function (key, setting) {
        $("#"+setting.id).prop("checked", setting.selected);
    });
}

function StickyTitles(stickies) {
	var thisObj = this;
	thisObj.load = function () {
		stickies.each(function () {
			var thisSticky = $(this).wrap('<div class="followWrap" />');
			thisSticky.parent().height(thisSticky.outerHeight());
			var pos = parseInt(thisSticky.offset().top, 10) - parseInt($(".showSide").offset().top, 10);
			$.data(thisSticky[0], 'pos', pos);
		});
		$(".showSide").off("scroll.stickies").on("scroll.stickies", function () {
			thisObj.scroll();
		});
	};

	thisObj.scroll = function () {
		stickies.each(function (i) {
			var thisSticky = $(this),
				nextSticky = stickies.eq(i + 1),
				prevSticky = stickies.eq(i - 1),
				pos = $.data(thisSticky[0], 'pos');
			var showSide = $(".showSide");
			if (pos <= showSide.scrollTop()) {
				thisSticky.addClass("fixed");
				if (nextSticky.length > 0 && thisSticky.offset().top >= $.data(nextSticky[0], 'pos') - thisSticky.outerHeight()) {
					thisSticky.addClass("absolute").css("top", jQuery.data(nextSticky[0], 'pos') - thisSticky.outerHeight());
				}
			} else {
				thisSticky.removeClass("fixed");
				if (prevSticky.length > 0 && showSide.scrollTop() <= $.data(thisSticky[0], 'pos') - prevSticky.outerHeight()) {
					prevSticky.removeClass("absolute").removeAttr("style");
				}
			}
		});
	}
}

jQuery.fn.outerHTML = function (s) {
	return s ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html();
};


/**
 * Triggers a click on the expand Games Button
 */
function triggerExpandGames() {
	if (showAllGames == "" || showAllGames.length == 0) {
		showAllGames = $("#ShowMoreOpenGamesLink");
		showAllGames.trigger("click");
	}
	if (showAllCoinGames == "") {
		showAllCoinGames = $("#ShowMorePromotedGamesLink");
		showAllCoinGames.trigger("click");
	}

}

function markJoinedGames() {
	var gamesSwitch = setInterval(function (){ 
		applyOpenGameFilters();
        updateOpenGamesCounter();
		var name = $(".TopRightBar a:nth-of-type(2)").text();
		var playerLabel = '<span style="font-size:12px; color:gray"> You already joined</span>'
		$.each($("#OpenGamesTable tr"), function (key, tableRow) {
			$.each($(tableRow).find("span span"), function (key2, player) {
				if ($(player).attr("title") == name && $(tableRow).html().indexOf("You already joined") < 0) {
					$(tableRow).find("td:nth-of-type(2) a").append(playerLabel)
				}
			});

		})
	}, 5);
	
	setTimeout(function () {
		clearInterval(gamesSwitch);
	}, 400)	
}

	/**
	 * Delayed function for expanding Games
	 */
	function expandGames() {
		numOfGames = 0;
		delayedFunction = setInterval(triggerExpandGames, 100);
		setTimeout(function () {
			clearInterval(delayedFunction);
		}, 3000);
	}

	/**
	 * Stores User-Settings to local Storage
	 */
	function storeSettingsVariables() {
        
        $.each(userscriptSettings, function (key, setting) {
            localStorage.setItem(setting.id, $("#"+setting.id).prop("checked"));
        });
		
	}

	/**
	 * 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('<div class="followWrap" />');
			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 td div").unwrap();        
	}

	/**
	 * 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 style = document.createElement('style');
		style.type = 'text/css';
		document.getElementsByTagName('head')[0].appendChild(style);
		if (!(style.sheet || {}).insertRule) {
			(style.styleSheet || style.sheet).addRule(name, rules);
		} else {
			style.sheet.insertRule(name + "{" + rules + "}", 0);
		}
	}

	/**
	 * Reloads all Games
	 */

	function refreshAllGames(force) {
		
		if ($(".popup").is(":visible") && !force) {
			return;
		}
        
        if (isEnabled('scrollGames')) {
            openGamesTable.scrollTop(0);
            myGamesTable.scrollTop(0);
            promotedGamesTable.scrollTop(0);
        }
        
        $('table').css('overflow-y','hidden')
		myGamesTable.find("tbody").fadeTo('slow', 0.15);
		openGamesTable.find("tbody").fadeTo('slow', 0.15);
		promotedGamesTable.find("tbody").fadeTo('slow', 0.15);

		var page = $('<div />').load('https://www.warlight.net/MultiPlayer/ ', function () {
			var myGames = page.find('#MyGamesTable tbody tr');
			//var openGames = page.find('#OpenGamesTable tbody tr');
			var promotedGames = page.find('#PromotedGamesTable tbody tr');
			showAllGames = page.find("#ShowMoreOpenGamesLink");

			promotedGamesTable.find("tbody tr").remove();

			$.each(myGamesTable.find("tbody tr"), function (key, value) {
				if ($(value).html().indexOf("PastGames") == -1) {
					$(value).remove();
				}
			});

			
			myGamesTable.find("tbody").prepend(myGames);
			//$("#OpenGamesTable").find("tbody").prepend(openGames);
			promotedGamesTable.find("tbody").prepend(promotedGames);
			
			$("#MorePromotedGamesHorizontalRow").remove();

			$("#ShowMorePromotedGamesLinkContainer").remove();

			$.each($(".TournamentRow td"), function () {
				$(this).find("font:first-of-type").appendTo($(this).find("a")).css("font-size", "10px");
			});


			myGamesTable.find("tbody").fadeTo('slow', 1, function() {
                myGamesTable.css('overflow-y','scroll');
            });
            
			//openGamesTable.find("tbody").fadeTo('slow', 1);
			promotedGamesTable.find("tbody").fadeTo('slow', 1, function() {
                promotedGamesTable.css('overflow-y','scroll');
            });
            
			markJoinedGames();
            if (isEnabled('scrollGames')) {
                refreshSingleColumnSize();
            }
			

		});

		var activeTabLoad;
		var activeTabClass;
        openGames = [];
        
		var active = $("#OpenGamesTable .ui-buttonset .ui-state-active").text();

		if (active.indexOf('Both') > -1) {
			activeTabLoad = ["BothRadio", "RealTimeRadio", "MultiDayRadio"];
			activeTabClass = ["bothOpenGames", "realOpenGames", "multiOpenGames"];
		} else if (active.indexOf('Real') > -1) {
			activeTabLoad = ["RealTimeRadio", "MultiDayRadio", "BothRadio"];
			activeTabClass = ["realOpenGames", "multiOpenGames", "bothOpenGames"];
		} else {
			activeTabLoad = ["MultiDayRadio", "RealTimeRadio", "BothRadio"];
			activeTabClass = ["multiOpenGames", "realOpenGames", "bothOpenGames"];
		}
        $("#iframeiii").remove();
		//Reload open games
		var ifr = $('<iframe/>', {
			id: 'iframeiii',
			src: 'https://www.warlight.net/MultiPlayer/OpenGames',
			style: 'position:fixed;z-index: 100000;right: 0;top:0;width:1px;height:1px;opacity:0',
			load: function () {
				setTimeout(function () {
					$("#iframeiii").contents().find("label[for='" + activeTabLoad[2] + "']").trigger('click');
					setTimeout(function () {
						openGames.push($("#iframeiii").contents().find('#OpenGamesTable tbody tr').addClass(activeTabClass[2]));
						$("#iframeiii").contents().find("label[for='" + activeTabLoad[1] + "']").trigger('click');
						setTimeout(function () {
							openGames.push($("#iframeiii").contents().find('#OpenGamesTable tbody tr').addClass(activeTabClass[1]));
							$("#iframeiii").contents().find("label[for='" + activeTabLoad[0] + "']").trigger('click');
							setTimeout(function () {

								var openGamesMenu = '<div id="fakeOpenGameMenu" style="float: right" class="ui-buttonset">	<input type="radio" id="MultiDayRadio" name="pace" checked="checked" class="ui-helper-hidden-accessible"><label for="MultiDayRadio" class="ui-state-active ui-button ui-widget ui-state-default ui-button-text-only ui-corner-left" role="button"><span class="ui-button-text">' + $("#iframeiii").contents().find("label[for='MultiDayRadio']").text() + '</span></label><input type="radio" id="RealTimeRadio" name="pace" class="ui-helper-hidden-accessible"><label for="RealTimeRadio" class="ui-button ui-widget ui-state-default ui-button-text-only" role="button"><span class="ui-button-text">' + $("#iframeiii").contents().find("label[for='RealTimeRadio']").text() + '</span></label><input type="radio" id="BothRadio" name="pace" class="ui-helper-hidden-accessible"><label for="BothRadio" class="ui-button ui-widget ui-state-default ui-button-text-only ui-corner-right" role="button"><span class="ui-button-text">' + $("#iframeiii").contents().find("label[for='BothRadio']").text() + '</span></label></div>';

								openGames.push($("#iframeiii").contents().find('#OpenGamesTable tbody tr').addClass(activeTabClass[0]));
								$("#OpenGamesTable thead tr td .ui-buttonset").remove();
								$("#OpenGamesTable thead tr td").append(openGamesMenu);
								$("#OpenGamesTable tbody tr").remove();


								$("#OpenGamesTable tbody").append(openGames[0]);
								$("#OpenGamesTable tbody").append(openGames[1]);
								$("#OpenGamesTable tbody").append(openGames[2]);
								$("RestoreLotteryGamesBtn").remove();

								$("label[for='MultiDayRadio']").on("click", function () {
                                    $(".hidden").removeClass("hidden");
                                    openGamesTable.scrollTop(0);
									$(".multiOpenGames").show();
									$(".multiOpenGames").prependTo("#OpenGamesTable tbody");
									$(".realOpenGames").addClass('hidden').hide();
									$(".bothOpenGames").addClass('hidden').hide();
									openGamesTable.scrollTop(0);
									$(this).addClass('ui-state-active');
									$("label[for='BothRadio']").removeClass('ui-state-active');
									$("label[for='RealTimeRadio']").removeClass('ui-state-active');
                                    $("#iframeiii").contents().find("label[for='MultiDayRadio']").trigger('click');
                                    markJoinedGames();

								});
								$("label[for='RealTimeRadio']").on("click", function () {
                                    $(".hidden").removeClass("hidden");
									openGamesTable.scrollTop(0);
									$(".multiOpenGames").addClass('hidden').hide();
									$(".realOpenGames").show();
									$(".realOpenGames").prependTo("#OpenGamesTable tbody");
									$(".bothOpenGames").addClass('hidden').hide();
									$(this).addClass('ui-state-active');
									$("label[for='MultiDayRadio']").removeClass('ui-state-active');
									$("label[for='BothRadio']").removeClass('ui-state-active');
                                    $("#iframeiii").contents().find("label[for='RealTimeRadio']").trigger('click');
                                    markJoinedGames();
								});
								$("label[for='BothRadio']").on("click", function () {
                                    $(".hidden").removeClass("hidden");
									openGamesTable.scrollTop(0);
									$(".multiOpenGames").addClass('hidden').hide();
									$(".realOpenGames").addClass('hidden').hide();
									$(".bothOpenGames").show();
									$(".bothOpenGames").prependTo("#OpenGamesTable tbody");
									$(this).addClass('ui-state-active');
									$("label[for='MultiDayRadio']").removeClass('ui-state-active');
									$("label[for='RealTimeRadio']").removeClass('ui-state-active');
                                    $("#iframeiii").contents().find("label[for='BothRadio']").trigger('click');
                                    markJoinedGames();

								});

								$($(".realOpenGames")[0]).find("td").css("padding-top", 48);
								$($(".bothOpenGames")[0]).find("td").css("padding-top", 48)
								var activeT = "label[for='" + activeTabLoad[0] + "']";
								$("#OpenGamesTable").hide();
								$(activeT).trigger('click');
								$("#OpenGamesTable").show();
								openGamesTable.find("tbody").fadeTo('slow', 1, function() {
                                    openGamesTable.css('overflow-y','scroll');
                                });
                                
								markJoinedGames();
								

							}, 100);
						}, 100);
					}, 100);
				}, 100);

			}
		});
		$('body').append(ifr);
	}

	/**
	 * 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();
					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();
					refreshAllGames();
				}
			});
		}
        
        $(".SideColumn").after($("#refreshAll"))

		if (isEnabled('autoRefreshOnFocus')) {
			$(window).on('focus', function () {
				if (new Date() - lastRefresh > 30000) {
					lastRefresh = new Date();
					refreshAllGames();
				}
			});
		}

		$("body").keyup(function (event) {
			// "R" is pressed
			if (event.which == 82) {
				if (new Date() - lastRefresh > 3000) {
					lastRefresh = new Date();
					refreshAllGames();
				}
			}
		});

		openGamesTable.prepend("<div class='loading loading-open'><img src='https://www.adobe.com/business/calculator/VIP/image/loader.gif' height='32' width='32'></div>");
		myGamesTable.prepend("<div class='loading loading-my'><img src='https://www.adobe.com/business/calculator/VIP/image/loader.gif' height='32' width='32'></div>");
		promotedGamesTable.prepend("<div class='loading loading-prom'><img src='https://www.adobe.com/business/calculator/VIP/image/loader.gif' height='32' width='32'></div>");
	}


	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;
	}


var searches = 0;
function filterMailTo() {
	if (searches == 0) {
		$($("#MainSiteContent div:nth-of-type(1)")[0]).children().remove()
		searches++;
	}
	var find = $("#search_input").val().toLowerCase()
	if (find.length > 1) {
		removeUncheckedMail()
		$.each(data_mail, function (index, val) {
		if ($(val).text().toLowerCase().indexOf(find) > -1) {
			var id = $(val).attr("id").replace("Lbl_", "")
			if ($("#Lbl_"+id).length == 0) {
				$($("#MainSiteContent div:nth-of-type(1)")[0]).append('<input type="checkbox" id="CB_' + id + '" onclick="PlayerClicked(' + id + ')">').append(val).append("<br>")
			}
			
		}
	})
	}
	else {
		removeUncheckedMail()
	}
	
}

function hideBlacklistedThreads() {
	var ids = JSON.parse(localStorage.getItem("blackListedThreads"));       
	$.each($("#ForumTable tr"), function (key, row) {
		var href =  $(row).html().match(/href="\/([^"]*)"/m);
		
		if (href) {
			href = "/" + href[1]
			if ($.inArray(href, ids) != -1) {
				$(row).remove()
			}
		}
		
	})
}

function removeUncheckedMail() {
	$.each($($("#MainSiteContent div:nth-of-type(1)")[0]).find("label"), function (index, val) {
			var id = $(val).attr("id").replace("Lbl_", "")
			if ( ! $('#CB_'+id).is(":checked")) {
				$(val).next().remove()
				$(val).prev().remove()
				$(val).remove()
			}
		})
}
var data_mail = []
if (location.href.match(/.*warlight[.]net\/Discussion\/SendMail$/)) {
	$($("#MainSiteContent div:nth-of-type(1)")[0]).before('<input id="search_input" placeholder="Filter" style="margin-bottom:10px">')
	$("#search_input").on("input", function () {
			filterMailTo()
		
	}) 
	
	$.each($($("#MainSiteContent div:nth-of-type(1)")[0]).find("label"), function (index, val) {
		data_mail.push($(val))
	});	

}

if (!isEnabled('useDefaultBootLabel')) {
        createSelector(".BootTimeLabel", "color:white !important;font-weight:normal!important;font-style:italic;font-size:13px!important;z-index:50;");
} else {
    createSelector(".BootTimeLabel", "z-index:50;");
}

function setGlobalStyles() {
	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;width: 420px;left: 50%;background: #171717;margin-left: -242px;top: 100px;z-index: 50000001; 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-top: 40px;width: 100%;text-align: center;font-size: 15px;cursor: pointer;background: gray;line-height: 30px;border-radius: 8px;");
	createSelector(".close-popup-img", "float:right;margin:5px;cursor:pointer");
	createSelector(".popup label", "width: 80%;display: inline-block;font-size: 15px;margin: 5px;");
	createSelector(".popup .title", "color: gray;font-size: 15px;margin-top: 10px;display: inline-block;width: 95%;border-bottom: 1px gray solid;padding-bottom: 3px;");
	createSelector(".popup input[type='checkbox']", "width: 20px;height: 20px;margin-left:30px;margin: 5px;-moz-appearance:none;");
	createSelector(".overlay", "position: absolute;background: white;top: 0;left: 0;right: 0;bottom: 0;z-index: 50000000;opacity: 0.5;");
	createSelector(".popup .head", "position: fixed;height: 40px;background: #330000;width: 480px;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;");
}

function hideFFAGames() {
	var hiddenGames = 0;
	$.each($("#OpenGamesTable tr"), function (key, tableRow) {
		if (rowIsFFAGame(tableRow) && $(tableRow).hasClass('GameRow')) {
			rowSlideUp(tableRow);
			hiddenGames++;
		}
		//var players = $(tableRow).find("td:nth-of-type(2) span span").length;
		//$(tableRow).find("td:nth-of-type(2) a").append(" " + players )
	});
	return hiddenGames;
}

function hideTeamGames() {
	var hiddenGames = 0;
	$.each($("#OpenGamesTable tr"), function (key, tableRow) {
		if (rowIsTeamGame(tableRow) && $(tableRow).hasClass('GameRow')) {
			rowSlideUp(tableRow);
			hiddenGames++;
		}
		//var players = $(tableRow).find("td:nth-of-type(2) span span").length;
		//$(tableRow).find("td:nth-of-type(2) a").append(" " + players )
	});
	return hiddenGames;
}

function hideGamesWithLuckOver(maxLuck) {
	var hiddenGames = 0;
	if (maxLuck < 100) {
		$.each($("#OpenGamesTable tr"), function (key, tableRow) {
			var luck = getLuckFromRow(tableRow);
			if (parseInt(luck) > maxLuck) {
				rowSlideUp(tableRow);
				hiddenGames++;
			}
		});
	}
	return hiddenGames;
}

function hide1v1Games() {
	var hiddenGames = 0;
	$.each($("#OpenGamesTable tr"), function (key, tableRow) {
		if (rowIs1v1Game(tableRow) && $(tableRow).hasClass('GameRow')) {
			rowSlideUp(tableRow);
			hiddenGames++;
		}
	});
	
	return hiddenGames;
}

function hideCustomScenarioGames() {
	var hiddenGames = 0;
	$.each($("#OpenGamesTable tr"), function (key, tableRow) {
		if (rowIsCustomScenarioGame(tableRow) && $(tableRow).hasClass('GameRow')) {
			rowSlideUp(tableRow);
			hiddenGames++;
		}
	});
	return hiddenGames;
}

function hidePracticeGames() {
	var hiddenGames = 0;
	$.each($("#OpenGamesTable tr"), function (key, tableRow) {
		if (rowIsPracticeGame(tableRow) && $(tableRow).hasClass('GameRow')) {
			rowSlideUp(tableRow);
			hiddenGames++;
		}
	});
	return hiddenGames;
}

function hideManualDistributionGames() {
	var hiddenGames = 0;
	$.each($("#OpenGamesTable tr"), function (key, tableRow) {
		if (rowIsManualDistributionGame(tableRow) && $(tableRow).hasClass('GameRow')) {
			rowSlideUp(tableRow);
			hiddenGames++;
		}
	});
	return hiddenGames;
}

function hideAutoDistributionGames() {
	var hiddenGames = 0;
	$.each($("#OpenGamesTable tr"), function (key, tableRow) {
		if (rowIsAutoDistributionGame(tableRow) && $(tableRow).hasClass('GameRow')) {
			rowSlideUp(tableRow);
			hiddenGames++;
		}
	});
	return hiddenGames;
}
function hideKeywordGames() {
	var keywords = openGamesFilters["hideKeyword"].split(",");
	var hiddenGames = 0;
	$.each($("#OpenGamesTable tr"), function (key, tableRow) {
		var title = $(tableRow).find("td > a").text().toLowerCase();
		$.each(keywords, function (key, keyword) {
			if (title.indexOf(keyword.trim().toLowerCase()) != -1 && keyword.trim().length > 1 && $(tableRow).hasClass('GameRow')) {
				rowSlideUp(tableRow);
				hiddenGames++;
			}
		})
	});
	return hiddenGames;
}

function hideRealTimeBootGames() {
	var bootMin = openGamesFilters["hideRealTimeBootTime"] || 0;
	var hiddenGames = 0;
	$.each($("#OpenGamesTable tr"), function (key, tableRow) {
		if (getBootMin(tableRow) < 240 && getBootMin(tableRow) < bootMin && $(tableRow).hasClass('GameRow')) {
			rowSlideUp(tableRow);
			hiddenGames++;
		}
	});
	return hiddenGames;
}

function hideMultiDayBootGames() {
	var bootMin = parseFloat(openGamesFilters["hideMultiDayBootTimeDays"] || 0) * 24 * 60 + parseFloat(openGamesFilters["hideMultiDayBootTimeHours"] || 0) * 60;
	var hiddenGames = 0;
	$.each($("#OpenGamesTable tr"), function (key, tableRow) {
		if (getBootMin(tableRow) >= 240 && getBootMin(tableRow) < bootMin && $(tableRow).hasClass('GameRow')) {
			rowSlideUp(tableRow);
			hiddenGames++;
		}
	});
	return hiddenGames;
}

function getBootMin(row) {
	var bootTimeLabel = $(row).find(".BootTimeLabel").text();
	var min = bootTimeLabel.match(/(?:[0-9]* hour[s]? |)([0-9]*) minutes?/) || 0;
	var hours = bootTimeLabel.match(/(?:([0-9]*) hour[s]? |)[0-9]* minutes?/) || bootTimeLabel.match(/(?:[0-9]* day[s]? |)([0-9]*) hours?/) || 0;
	var days = bootTimeLabel.match(/([0-9]*) day[s]?(?: [0-9]* hours?|)/) || 0;	
	
	var totalMin = parseFloat(min[1] || 0) + parseFloat(hours[1] || 0) * 60 + parseFloat(days[1] || 0) * 24 * 60;
		
	return totalMin;
}

function rowIsFFAGame(row) {
	return $(row).find("[src='https://d2wcw7vp66n8b3.cloudfront.net/Images/GameInfoIcons/Teams.png']").length == 0 && $(row).find("td:nth-of-type(2) span span").length > 2;
}

function rowIs1v1Game(row) {
	return $(row).find("td:nth-of-type(2) span span").length == 2;
}

function rowIsTeamGame(row) {
	return $(row).find("[src='https://d2wcw7vp66n8b3.cloudfront.net/Images/GameInfoIcons/Teams.png']").length == 1 && $(row).find("td:nth-of-type(2) span span").length > 2;
}

function rowIsCustomScenarioGame(row) {
	return $(row).find("[src='https://d2wcw7vp66n8b3.cloudfront.net/Images/GameInfoIcons/CustomScenario.png']").length == 1;
}

function rowIsPracticeGame(row) {
	return $(row).find("[src='https://d2wcw7vp66n8b3.cloudfront.net/Images/GameInfoIcons/PracticeGame.png']").length == 1;
}

function rowIsManualDistributionGame(row) {
	return $(row).find("[src='https://d2wcw7vp66n8b3.cloudfront.net/Images/GameInfoIcons/ManualDistribution.png']").length == 1;
}

function rowIsAutoDistributionGame(row) {
	return $(row).find("[src='https://d2wcw7vp66n8b3.cloudfront.net/Images/GameInfoIcons/AutoDist.png']").length == 1;
}

function getLuckFromRow(row) {
	var luck = 0;
	
	if ($(row).find("[src='https://d2wcw7vp66n8b3.cloudfront.net/Images/GameInfoIcons/LuckModifier.png']").length == 1) {
		luck = 	$(row).find("[src='https://d2wcw7vp66n8b3.cloudfront.net/Images/GameInfoIcons/LuckModifier.png']").attr('title').match(/^[^1-9]*(.*)%/)[1]
	}
	
	return luck;
}

window.applyOpenGameFilters = function () {
	var hiddenGames = 0;
	if (showOpenGamesFilter && openGamesFilters["disableAll"] != true) {
		if (openGamesFilters["hideLuck"] < 100) {
			hiddenGames += hideGamesWithLuckOver(openGamesFilters["hideLuck"])
		}
	
		if (openGamesFilters["hideFFA"]) {
			hiddenGames += hideFFAGames();
		}

		if (openGamesFilters["hideTeam"]) {
			hiddenGames += hideTeamGames();
		}

		if (openGamesFilters["hide1v1"]) {
			hiddenGames += hide1v1Games();
		}
		
		if (openGamesFilters["hideCustomScenario"]) {
			hiddenGames += hideCustomScenarioGames();
		}
		
		if (openGamesFilters["hidePractice"]) {
			hiddenGames += hidePracticeGames();
		}
		if (openGamesFilters["hideManualDistribution"]) {
			hiddenGames += hideManualDistributionGames();
		}
		
		if (openGamesFilters["hideAutoDistribution"]) {
			hiddenGames += hideAutoDistributionGames();
		}
		
		if (openGamesFilters["hideKeyword"] && openGamesFilters["hideKeyword"].trim() != "") {
			hiddenGames += hideKeywordGames();
		}
		
		if (openGamesFilters["hideRealTimeBootTime"] > 0) {
			hiddenGames += hideRealTimeBootGames();
		}
		
		if (openGamesFilters["hideMultiDayBootTimeDays"] > 0 || openGamesFilters["hideMultiDayBootTimeHours"] > 0) {
			hiddenGames += hideMultiDayBootGames();
		}
	}
	if (hiddenGames > 0 && $("#gamesAreHidden").length == 0) {
		$("#RestoreLotteryGamesBtn").after("<span id='gamesAreHidden' style='color: gray;font-style: italic;'>Some Games are hidden</span>");
		$("#gamesAreHidden").parent().parent().removeClass()
	}
	
}


function rowSlideUp(row) {
	$(row).remove();
	//$(row).css("background", "red")
}

function storeFilterVariables() {
	openGamesFilters = {};
	openGamesFilters["disableAll"] = $("#disableAll").prop("checked")
	openGamesFilters["hideTeam"] = $("#hideTeam").prop("checked")
	openGamesFilters["hideFFA"] = $("#hideFFA").prop("checked")
	openGamesFilters["hide1v1"] = $("#hide1v1").prop("checked")
	openGamesFilters["hideManualDistribution"] = $("#hideManualDistribution").prop("checked")
	openGamesFilters["hideAutoDistribution"] = $("#hideAutoDistribution").prop("checked")
	openGamesFilters["hideCustomScenario"] = $("#hideCustomScenario").prop("checked")
	openGamesFilters["hidePractice"] = $("#hidePractice").prop("checked")
	openGamesFilters["hideKeyword"] = $("#hideKeyword").val()
	openGamesFilters["hideRealTimeBootTime"] = $("#hideRealTimeBootTime").val()
	openGamesFilters["hideMultiDayBootTimeDays"] = $("#hideMultiDayBootTimeDays").val()
	openGamesFilters["hideMultiDayBootTimeHours"] = $("#hideMultiDayBootTimeHours").val()

	var luck = $("#hideLuck").val();
	if ($.isNumeric(luck) && luck <= 100 && luck >= 0) {
		openGamesFilters["hideLuck"] = luck;
	} else {
		openGamesFilters["hideLuck"] = 0;
	}
	var rtBoot = $("#hideRealTimeBootTime").val();
	if ($.isNumeric(rtBoot)) {
		openGamesFilters["hideRealTimeBootTime"] = rtBoot;
	} else {
		openGamesFilters["hideRealTimeBootTime"] = 0;
	}
	var mdBootDay = $("#hideMultiDayBootTimeDays").val();
	if ($.isNumeric(mdBootDay)) {
		openGamesFilters["hideMultiDayBootTimeDays"] = mdBootDay;
	} else {
		openGamesFilters["hideMultiDayBootTimeDays"] = 0;
	}
	var mdBootHour = $("#hideMultiDayBootTimeHours").val();
	if ($.isNumeric(mdBootHour)) {
		openGamesFilters["hideMultiDayBootTimeHours"] = mdBootHour;
	} else {
		openGamesFilters["hideMultiDayBootTimeHours"] = 0;
	}
	
	localStorage.setItem("openGamesFilters", JSON.stringify(openGamesFilters));
	updateFilterSettings()
}

function updateFilterSettings() {
	$("#disableAll").prop("checked", openGamesFilters["disableAll"]);
	$("#hideTeam").prop("checked", openGamesFilters["hideTeam"]);
	$("#hideFFA").prop("checked", openGamesFilters["hideFFA"]);
	$("#hide1v1").prop("checked", openGamesFilters["hide1v1"]);
	$("#hideManualDistribution").prop("checked", openGamesFilters["hideManualDistribution"]);
	$("#hideAutoDistribution").prop("checked", openGamesFilters["hideAutoDistribution"]);
	$("#hideCustomScenario").prop("checked", openGamesFilters["hideCustomScenario"]);
	$("#hidePractice").prop("checked", openGamesFilters["hidePractice"]);
	$("#hideLuck").val(openGamesFilters["hideLuck"] || 100);
	$("#hideKeyword").val(openGamesFilters["hideKeyword"] || "");
	$("#hideRealTimeBootTime").val(openGamesFilters["hideRealTimeBootTime"] || 0);
	$("#hideMultiDayBootTimeDays").val(openGamesFilters["hideMultiDayBootTimeDays"] || 0);
	$("#hideMultiDayBootTimeHours").val(openGamesFilters["hideMultiDayBootTimeHours"] || 0);
}

function isEnabled(setting) {
    return $(userscriptSettings).settingIsEnabled(setting);
}

function pageIsMultiplayer() {
    return location.href.match(/.*warlight[.]net\/MultiPlayer.*/);
}

function pageIsDashboard() {
    return location.href.match(/.*warlight[.]net\/MultiPlayer\/#?$/);   
}

function pageIsClanThread() {
    return location.href.match(/.*warlight[.]net\/Discussion/);
}

function showOpenGamesLink() {
    $("#SubTabRow td:nth-child(8)").after('<td valign="top"><img src="https://d2wcw7vp66n8b3.cloudfront.net/Images/Tabs/SubSelectedLeft.png" width="6" height="16" style="visibility: hidden"></td><td nowrap="nowrap" class="SubTabCell" id="openGamesTab"><a href="/MultiPlayer/OpenGames">Open Games</a></td><td valign="top"><img src="https://d2wcw7vp66n8b3.cloudfront.net/Images/Tabs/SubSelectedRight.png" width="6" height="16" style="visibility: hidden"></td><td width="10">&nbsp;</td>');
	
    if (location.href.match(/.*warlight[.]net\/MultiPlayer\/OpenGames.*/)) {
        $("#openGamesTab").addClass("SubTabCellSelected");
        $("#openGamesTab").prev().children().css("visibility", "visible");
        $("#openGamesTab").next().children().css("visibility", "visible");
    }
}

function setupOpenGamesFilter() {
    $("#OpenGamesTable thead tr td").prepend('<a id="editFilters" style="color:#DDDDDD;font-size: 14px;float: right;">▼</a>');
		
    var filters_body = "<hr>";
    filters_body += '<label for="disableAll">Disable All Filters</label><input type="checkbox" id="disableAll"><br>';
    filters_body += "<hr>";
    filters_body += '<label for="hideTeam">Hide Team Games</label><input type="checkbox" id="hideTeam"><br>';
    filters_body += '<label for="hideFFA">Hide FFA Games</label><input type="checkbox" id="hideFFA"><br>';
    filters_body += '<label for="hide1v1">Hide 1 v 1 Games</label><input type="checkbox" id="hide1v1"><hr>';
    filters_body += '<label for="hideManualDistribution">Hide Manual Distribution Games</label><input type="checkbox" id="hideManualDistribution"><br>';
    filters_body += '<label for="hideAutoDistribution">Hide Auto Distribution Games</label><input type="checkbox" id="hideAutoDistribution"><hr>';
    filters_body += '<label for="hideCustomScenario">Hide Custom Scenario Games</label><input type="checkbox" id="hideCustomScenario"><br>';
    filters_body += '<label for="hidePractice">Hide Practice Games</label><input type="checkbox" id="hidePractice"><hr>';
    filters_body += '<label for="hideLuck" style="width:169px">Hide Luck greater than</label><input type="text" id="hideLuck" class="number"><hr>';
    filters_body += '<label for="hideKeyword" style="width:115px">Hide Keywords</label><br><span class="info"><span class="info-preview">More information about Keyword Filtering...<br></span>Separate multiple Keywords (3+ letters) with a comma. <br>The Keyword Filter searches for matches in the complete Gametitle. (Case Insensitive)<br>Example: Keyword "Rop" removes the Game "Europe 3v3"</span><input type="text" id="hideKeyword" style="width: 95%;margin-left: 6px;"><hr>';
    filters_body += '<label>Hide Boot Time lower than</label><br>';
    filters_body += '<label for="hideRealTimeBootTime" style="width:100px">Realtime:  </label><input class="number" type="text" id="hideRealTimeBootTime">minute(s)<br>';
    filters_body += '<label for="hideMultiDayBootTimeDays" style="width:100px">Multiday: </label><input class="number" type="text" id="hideMultiDayBootTimeDays"> day(s) and <input class="number" type="text" id="hideMultiDayBootTimeHours"> hour(s)<hr>';
    filters_body += '<div class="close-userscript">Close and Apply</div>';
    $("body").append("<div class='popup filters-show' style='display: none'><div class='head'>Change Filter Settings<img class='close-popup-img' src='https://i.imgur.com/RItbpDS.png' height='25' width='25'></div>" + filters_body + "</div>");

    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('hr', 'height: 1px;border: none;background-color: gray;opacity:0.5;');
    createSelector('.number', 'width: 31px');
    createSelector('.info', 'font-size: 12px;color: gray;border: 1px gray solid;padding: 5px;display: block;margin: 8px 0 8px 0;line-height: 20px;overflow: hidden; max-height:18px;transition:max-height 2s;-webkit-transition:max-height 2s;');
    createSelector('.info:hover', 'max-height:500px');
    createSelector('#hideKeyword', 'text-align: left;');

    $("#hideLuck").after("%");

    createSelector('.ui-button-text-only .ui-button-text', 'padding: .4em 0.6em;');
    createSelector('#editFilters:hover', 'cursor:pointer');

    $(".filters-show").on("change", function () {
        storeFilterVariables();
    });

    $("#editFilters").on("click", function () {
        $(".filters-show").fadeIn();
        $(".overlay").fadeIn();
    });

    $(".close-userscript").on("click", function () {
        $(".filters-show").fadeOut();
        $(".overlay").fadeOut();
        refreshAllGames(true);
    });

    $(".close-popup-img").on("click", function () {
        $(".overlay").fadeOut();
        $(".popup").fadeOut();
    });

    updateFilterSettings();   
}

function hightlightNewClanForumPosts() {

    var regex1 = /.* commented [\n \t]+/;
    var regex2 = / ago/;
    var regex3 = /.*\/Forum\//;
    var regex4 = /-.*/;
    
    var data = localStorage.getItem('clanForumThreadsTime');
    if (data != null) {
        data = JSON.parse(data);
    } else if (data == null) {
        data = [];
        $.each($('#ClanForumTable tbody tr'), function (index, row) {
            if ($(row).find('td a')[0].href.match(/.*Forum\/[0-9]+/)) {
                var id = $(row).find('td a')[0].href.replace(regex3, "").replace(regex4, "");
                data.push({id: id, date: new Date()});
            }
        });

        localStorage.setItem('clanForumThreadsTime', JSON.stringify(data));
    }

    $.each($('#ClanForumTable tbody tr'), function (index, row) {
        if ($(row).find('td a')[0].href.match(/.*Forum\/[0-9]+/)) {
            var lastComment = $(row).find('td span').text().trim().replace(regex1, "").replace(regex2, "");
            var id = $(row).find('td a')[0].href.replace(regex3, "").replace(regex4, "");
            var found = false;

            $.each(data, function (key, val) {
                if (val.id == id) {
                    found = true;
                    if (getDate(lastComment) > new Date(val.date)) {
                        $(row).css('background', '#4C4C33');
                    }
                }
            });
            if (!found) {
                $(row).css('background', '#4C4C33');
            }
        }
    });
}

function setupBasicDashboardStyles() {
	createSelector(".GameRow a", "font-size:16px !important;");
    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: 1000;position: relative;");
    createSelector(".showGames thead tr", "background: rgb(51, 0, 0) none repeat scroll 0% 0%;z-index: 5000000;position: absolute;padding: 5px;border-bottom: 1px solid rgb(68, 68, 68);border-top-left-radius: 8px;width: calc(100% - 30px);letter-spacing: 1px;");
	createSelector(".showGames table tbody", "display:table;width:100%;");

	$.each($(".TournamentRow td"), function () {
		$(this).find("font:first-of-type").appendTo($(this).find("a")).css("font-size", "10px");
	});
}

function setupFixedWindowStyles() {
    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:100;");
    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", "min-width:535px");
    createSelector(".MainColumn", "width:40.55% !important");
    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:33.55%; min-width:500px;margin-left: 20px;border-top-left-radius:8px;border-top-right-radius:8px");
    createSelector("#refreshAll", "position: absolute;top: 20px;right: 31px");
    createSelector("#fakeOpenGameMenu label", "margin-right:2px");
    createSelector("#RestoreLotteryGamesBtn", "display:none");
}

function setupFixedTitlesInSideColumn() {
    var blogTable = $("#BlogTable");
    var realTimeLadderTable = $("#RealTimeLadderTable");
    var forumTable = $("#ForumTable");
    var clanForumTable = $("#ClanForumTable");
    var mapOfTheWeekTable = $("#MapOfTheWeekTable");
    var leaderboardTable = $("#LeaderboardTable");
    var myTournamentsTable = $("#MyTournamentsTable");

    blogTable.before("<div class='followMeBar'>" + blogTable.find("thead > tr > td").html() + "</div>");
    realTimeLadderTable.before("<div class='followMeBar'>" + realTimeLadderTable.find("thead > tr > td").html() + "</div>");
    forumTable.before("<div class='followMeBar'>" + forumTable.find("thead > tr > td").html() + "</div>");
    clanForumTable.before("<div class='followMeBar'>" + clanForumTable.find("thead > tr > td").html() + "</div>");
    mapOfTheWeekTable.before("<div class='followMeBar'>" + mapOfTheWeekTable.find("thead > tr > td").html() + "</div>");
    leaderboardTable.before("<div class='followMeBar'>" + leaderboardTable.find("thead > tr > td").html() + "</div>");
    myTournamentsTable.before("<div class='followMeBar'>" + myTournamentsTable.find("thead > tr > td").html() + "</div>");
    
    new StickyTitles(jQuery(".followMeBar")).load();
}

function setupFixedWindowWithScrollableGames() {
    var gameButtons = '<div style="margin: 10px;" id="switchGameRadio" class="ui-buttonset">';
    gameButtons += '<input type="radio" id="ShowMyGames" name="switchGames" checked="checked" class="ui-helper-hidden-accessible">';
    gameButtons += '<label for="ShowMyGames" class="ui-state-active ui-button ui-widget ui-state-default ui-button-text-only ui-corner-left" role="button"><span class="ui-button-text">My Games</span></label>';
    if (isEnabled('hidePromotedGames') || isEnabled('hideCoinsGlobally')) {
        gameButtons += '<input type="radio" id="ShowOpenGames" name="switchGames" class="ui-helper-hidden-accessible">';
        gameButtons += '<label for="ShowOpenGames" class="ui-button ui-widget ui-state-default ui-button-text-only ui-corner-right" role="button"><span class="ui-button-text">Open Games</span></label>';
    } else {
        gameButtons += '<input type="radio" id="ShowOpenGames" name="switchGames" class="ui-helper-hidden-accessible">';
        gameButtons += '<label for="ShowOpenGames" class="ui-button ui-widget ui-state-default ui-button-text-only" role="button"><span class="ui-button-text">Open Games</span></label>';
        gameButtons += '<input type="radio" id="ShowCoinGames" name="switchGames" class="ui-helper-hidden-accessible">';
        gameButtons += '<label for="ShowCoinGames" class="ui-button ui-widget ui-state-default ui-button-text-only ui-corner-right" role="button"><span class="ui-button-text">Coin Games</span></label>';
    }

    gameButtons += '</div>';


    var mainColumn = $(".MainColumn ");
    mainColumn.prepend('<div class="showGamesContainer">' + gameButtons + '<div class="showGames"></div></div>');
    myGamesTable.appendTo(".showGames");

    mainColumn.after('<div class="showSide"></div>');
    $(".SideColumn").appendTo(".showSide");

    setupFixedWindowStyles();
    setupFixedTitlesInSideColumn();
    
    refreshSingleColumnSize();

    $("#switchGameRadio").find("label").on("click", function () {
        var newShowGames = $(this).attr("for");
        if (newShowGames != showGamesActive) {
            $.each($("#switchGameRadio").find("label"), function () {
                $(this).removeClass("ui-state-active");
            });
            $(this).addClass("ui-state-active");

            if (newShowGames == "ShowMyGames") {
                showGamesActive = newShowGames;
                promotedGamesTable.appendTo("body");
                openGamesTable.appendTo("body");
                myGamesTable.appendTo(".showGames");
            } else if (newShowGames == "ShowCoinGames") {
                showGamesActive = newShowGames;
                myGamesTable.appendTo("body");
                openGamesTable.appendTo("body");
                promotedGamesTable.appendTo(".showGames");
            } else if (newShowGames == "ShowOpenGames") {
                showGamesActive = newShowGames;
                myGamesTable.appendTo("body");
                promotedGamesTable.appendTo("body");
                openGamesTable.appendTo(".showGames");
            }

            showAllGames.trigger("click");
            refreshSingleColumnSize()
            markJoinedGames();
            applyOpenGameFilters();
        }
    });
}

function hideRightColumn() {
    if (isEnabled('scrollGames')) {
        $(".showSide").css("display", "none");
        createSelector(".MainColumn", "margin: auto;");
        createSelector(".MainColumn", "max-width: 800px;");
        createSelector(".MainColumn", "width: 60%!important;");
        createSelector(".MainColumn", "float: none !important;");
        createSelector(".MainColumn", "min-width: 600px !important;");
    } else {
        $(".SideColumn").css("display", "none");
        $(".MainColumn").css("width", "100%");
        $(".MainColumn").css("max-width", "800px");
    }
}

function registerGameTabClick() {
    if (lastClick - new Date() > 2000) {
        openGamesTable.scrollTop(0);
        lastClick = new Date();
    }
    markJoinedGames();
}

function registerClanThread() {
    var id = location.href.replace(/.*warlight[.]net\/Discussion\/[?]ID=/, "");
	var data = localStorage.getItem('clanForumThreadsTime');
	
	if (data != null) {
		data = JSON.parse(data)
	} else {
		data = [];
	}
	var found = false;
	
	$.each(data, function (key, val) {
		if (val.id == id) {
			data[key] = {id: id, date:new Date()};
			found = true;
		}
	});
	if (!found) {
		data.push({id: id, date: new Date()});
	}
	
	localStorage.setItem('clanForumThreadsTime', JSON.stringify(data))
}

function updateOpenGamesCounter() {
    var visibleGames = $("#OpenGamesTable .GameRow:not('.hidden')").length;
    var active = $("#OpenGamesTable .ui-buttonset .ui-state-active").text();

    if (active.indexOf('Both') > -1) {
        //Both
        $("#OpenGamesTable .ui-buttonset .ui-state-active span").text('Both (' + visibleGames + ')')
    } else if (active.indexOf('Real') > -1) {
        //Real
        $("#OpenGamesTable .ui-buttonset .ui-state-active span").text('Real-Time (' + visibleGames + ')')
    } else {
        //Multi-Day
        $("#OpenGamesTable .ui-buttonset .ui-state-active span").text('Multi-Day (' + visibleGames + ')')
    }
    
    
}