Tidy up your Dashboard

Customizable Userscript which tidies up your Dashboard!

Versión del día 24/05/2016. Echa un vistazo a la versión más reciente.

Tendrás que instalar una extensión para tu navegador como Tampermonkey, Greasemonkey o Violentmonkey si quieres utilizar este script.

Necesitarás instalar una extensión como Tampermonkey o Violentmonkey para instalar este script.

Necesitarás instalar una extensión como Tampermonkey o Violentmonkey para instalar este script.

Necesitarás instalar una extensión como Tampermonkey o Userscripts para instalar este script.

Necesitará instalar una extensión como Tampermonkey para instalar este script.

Necesitarás instalar una extensión para administrar scripts de usuario si quieres instalar este script.

(Ya tengo un administrador de scripts de usuario, déjame instalarlo)

Necesitará instalar una extensión como Stylus para instalar este estilo.

Necesitará instalar una extensión como Stylus para instalar este estilo.

Necesitará instalar una extensión como Stylus para instalar este estilo.

Necesitará instalar una extensión del gestor de estilos de usuario para instalar este estilo.

Necesitará instalar una extensión del gestor de estilos de usuario para instalar este estilo.

Necesitará instalar una extensión del gestor de estilos de usuario para instalar este estilo.

(Ya tengo un administrador de estilos de usuario, déjame instalarlo)

// ==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.12.6
// @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
// ==/UserScript==

var version = "1.12.6";
this.$$$ = jQuery.noConflict(true);

if(pageIsDashboard()) {
    createSelector("#MainSiteWrapper", "display: none")
    createSelector("body", "overflow: hidden")
}

document.addEventListener ("DOMContentLoaded", DOM_ContentReady);


function checkVersion() {
    Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "version", function(v) {
        var currentVersion = v != undefined ? v.value: undefined
        if (currentVersion == version) {
        //Script Up to date

        } else if (currentVersion == undefined) {
            //Script new installed
            addDefaultBookmark();
            setupSettingsDatabase();
        } else {
            setUserInvalid()
            //Script Updated

            //$("label[for='showPrivateNotesOnProfile']").addClass('newSetting');

            //showPopup(".userscript-show");

            window.setTimeout(function() {
                warlight_shared_viewmodels_AlertVM.DoPopup("Tidy up Your Dashboard was sucessfully updated to version " + version + "! Check out the forum thread to see what changed.");
            }, 1000)
                 
        }

        addVersionLabel()
        if(sessionStorage.getItem("showUserscriptMenu")) {
            showUserscriptMenu();
            sessionStorage.removeItem("showUserscriptMenu")
        }
    })
    Database.update(Database.Table.Settings, {name: "version", value: version}, undefined, function() {
        
    })
    
}

setupImages();
window.userscriptSettings = [
    {
        id: 'scrollGames',
        text: 'Fixed Window with scrollable Games',
        selected: true,
        title: 'Dashboard',
        addBreak: false,
        help: 'This Option displays My-, Open-, Coin-Games in a scrollable box, which removes lots of unesessary scrolling. You can find tabs to switch between the different type of games. '
    },
    {
        id: 'hideMyGamesIcons',
        text: 'Hide Icons in "My Games"',
        selected: false,
        title: '',
        addBreak: false,
        help: 'This Option hides Game-Icons like ( <img src="https://d2wcw7vp66n8b3.cloudfront.net/Images/GameInfoIcons/Teams.png">,<img src="https://d2wcw7vp66n8b3.cloudfront.net/Images/GameInfoIcons/ManualDistribution.png"> , etc) in "My Games"'
    },
    {
        id: 'autoRefreshOnFocus',
        text: 'Automatically refresh Games on Tab-Focus',
        selected: true,
        title: '',
        addBreak: false,
        help: 'This Option automatically refreshes your Games after switching back to Warlight from a different tab / program. This only applies if Warlight was idle for 30 or more seconds.'
    },
    {
        id: 'highlightTournaments',
        text: 'Highlight Tournament invites',
        selected: false,
        title: '',
        addBreak: false,
    },
    {
        id: 'hideRightColumn',
        text: 'Hide Right Column',
        selected: false,
        title: '',
        addBreak: false,
        help: 'This Option hides the right column completely and leaves you alone with My-, Open- and Coin-Games.'
    },
    {
        id: 'hidePromotedGames',
        text: 'Hide Promoted Games',
        selected: false,
        title: '',
        addBreak: false,
        help: 'This Option hides the Promoted Games on the Dashboard'
    },
    {
        id: 'showOpenGamesTab',
        text: 'Show Open Games Tab in Menu Bar',
        selected: false,
        title: 'Global',
        addBreak: false,
        help: 'This Option displays a link to the "Open Games" site right next to the "Past Games" Link.'
    },
    {
        id: 'hideCoinsGlobally',
        text: 'Hide Coins Globally',
        selected: false,
        title: '',
        addBreak: false,
        help: 'This Option removes everything from Warlight related to Coins'
    },
    {
        id: 'showPrivateNotesOnProfile',
        text: 'Show Private Notes on Profile',
        selected: true,
        title: '',
        addBreak: false,
        help: 'This Option will show you your Private Notes which you made on a player directly on their Profile page. You can find them on the left side under the profile picture.'
    },
    {
        id: 'unlinkDashboard',
        text: 'Link Dashboard to "old" My-Games Site',
        selected: false,
        title: '',
        addBreak: false,
        help: 'This Option links the Dashboard to the "old" My-Games Site'
    },
    {
        id: 'useDefaultBootLabel',
        text: 'Use the Default Boot Time Label',
        selected: false,
        title: 'Advanced',
        addBreak: false
    },
    {
        id: 'hideRefreshButton',
        text: 'Hide Refresh Button',
        selected: false,
        title: '',
        addBreak: false,
        help: 'Hide the Refresh Button. You can still refresh with R'
    },
    {
        id: 'hideOffTopic',
        text: 'Automatically hide Off-topic threads',
        selected: false,
        title: '',
        addBreak: false,
        help: 'This Option automatically hides all Off-topic threads everytime you visit the "All Forum Posts"-Page'
    },
    {
        id: 'disableHideThreadOnDashboard',
        text: 'Disable right-click on the Forum Table',
        selected: false,
        title: '',
        addBreak: false,
        help: 'This Option will allow you right-click Forum Thread on the Dashboard and use the Default Options.'
    },
    {
        id: 'hideCreateRandomGameForm',
        text: 'Hide Randomized Bonuses Game Form',
        selected: false,
        title: '',
        addBreak: false,
        help: 'This Option will hide the Randomized Bonuses Game Form which is located on the Profile Page.'
    },
    {
        id: 'showSnow',
        text: 'Show Snow',
        selected: false,
        title: '',
        addBreak: false,
        help: 'Shows the snow animation on all sites'
    }, 
    {
        id: 'snowLight',
        text: 'Reduce the number of Snowflakes',
        selected: false,
        title: '',
        addBreak: false,
        help: 'Reduce the number of Snowflakes for a better performance'
    }
];

window.filters = [
    {
        id: "disableAll",
        text: "Disable All Filters",
        selected: false,
        type: "checkbox"
    },
    {
        id: "",
        text: "<div style='display:inline-block;height:30px; width: 10px'> </div>",
        selected: false,
        type: "custom"
    },
    {
        id: "hideTeam",
        text: "Hide Team Games",
        selected: false,
        type: "checkbox"
    }, 
    {
        id: "hideCommanderGames",
        text: "Hide Games with Commanders",
        selected: false,
        type: "checkbox"
    }, 
    {
        id: "hideFFA",
        text: "Hide FFA Games",
        selected: false,
        type: "checkbox"
    },
    {
        id: "hideNoneCommanderGames",
        text: "Hide Games without Commanders",
        selected: false,
        type: "checkbox"
    },
    {
        id: "hide1v1",
        text: "Hide 1 v 1 Games",
        selected: false,
        type: "checkbox"
    },
    {
        id: "hideManualDistribution",
        text: "Hide Manual Distribution Games",
        selected: false,
        type: "checkbox"
    },
    {
        id: "hideNoSplit",
        text: "Hide No-Split Games",
        selected: false,
        type: "checkbox"
    },
    {
        id: "hideAutoDistribution",
        text: "Hide Auto Distribution Games",
        selected: false,
        type: "checkbox"
    },
     {
        id: "hideLocalDeployments",
        text: "Hide Local Deployment Games",
        selected: false,
        type: "checkbox"
    },
    {
        id: "hideCustomScenario",
        text: "Hide Custom Scenario Games",
        selected: false,
        type: "checkbox"
    },
    {
        id: "hideLuck",
        text: "<label for='hideLuck' style='width:169px'>Hide Luck greater than</label><input type='text' id='hideLuck' class='number'>",
        selected: false,
        type: "custom"
    },
    {
        id: "hideNonCustomScenario",
        text: "Hide Non-Custom Scenario Games",
        selected: false,
        type: "checkbox"
    },
    {
        id: "hideKeyword",
        text: '<label for="hideKeyword" style="width:115px">Hide Keywords<img src="' + IMAGES.QUESTION + '" class="help-icon" onclick="showFilterHelp(\'You can separate multiple Keywords with a comma. Each keyword must have 3 or more letters. The Keyword-Filter searches for case insensitive matches in the complete game title.<br>Example: The keyword ´Rop´ removes the game ´Europe 3v3´\', this)"></label><br><input type="text" id="hideKeyword" style="width: 95%;margin-left: 6px;"><hr>',
        selected: false,
        type: "custom",
    },
    {
        id: "hidePractice",
        text: "Hide Practice Games",
        selected: false,
        type: "checkbox"
    },
    {
        id: "hideNonPractice",
        text: "Hide Non-Practice Games",
        selected: false,
        type: "checkbox"
    },
    {
        id: "limitPlayers",
        text: '<label>Limit Amount of Players</label><br><div class="filter-small"><label for="hideMinPlayers" style="width:25px">Min </label><input class="number" type="text" id="hideMinPlayers">Players<br><label for="hideMaxPlayers" style="width:25px">Max </label><input class="number" type="text" id="hideMaxPlayers">Players</div>',
        selected: false,
        type: "custom"
    },
    {
        id: "hideBootTime",
        text: '<label>Hide Boot Time lower than</label><br><div class="filter-small"><label for="hideRealTimeBootTime" style="width:100px">Realtime:  </label><input class="number" type="text" id="hideRealTimeBootTime">minute(s)<br><label for="hideMinPlayers" style="width:100px">Multiday: </label><input class="number" type="text" id="hideMultiDayBootTimeDays"> day(s) and <input class="number" type="text" id="hideMultiDayBootTimeHours"> hour(s)</div>',
        selected: false,
        type: "custom"
    }
];



window.showGamesActive = "ShowMyGames";

setupDatabase()
window.openGames = [];

function DOM_ContentReady() {
    $.fn.outerHTML = function (s) {
        return s ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html();
    };
    
    $.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 < openGamesFilters["hideRealTimeBootTime"]) return true;
            if (openGamesFilters["hideMultiDayBootTimeInMs"] > 0 && !game.RealTimeGame && game.DirectBoot < 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;
            }
        } );
    } catch(e) {
    }
    
    $("#MyGamesFilter").on("change", function() {
        var customFilter = $(this).val()
        Database.update(Database.Table.Settings, {name: "customFilter", value: customFilter}, undefined, function() {
        })
    })

    if(pageIsDashboard()) {
        $("body").append("<div class='loader' style='    background: black;position: fixed;left: 0;right: 0;top: 75px;bottom: 0;z-index: 100;'></div>")
        $("#MainSiteWrapper").show();
    }
    
    if(pageIsThread()) {
        setupTextarea()
    }

    if (pageIsForumThread() || pageIsClanForumThread()) {
        //Show Open Games Link
        $("[href='#Reply']").after(" | <a style='cursor:pointer' onclick='bookmarkForumThread()'>Bookmark</a>")
        $("#PostReply").after(" | <a style='cursor:pointer' onclick='bookmarkForumThread()'>Bookmark</a>")
    }

    if (pageIsTournament()) {
        window.setTimeout(function() {
            setupTournamentFindMe()
            setupPlayerDataTable()
        }, 50)
        $("#HostLabel").after(" | <a style='cursor:pointer' onclick='bookmarkTournament()'>Bookmark</a>");
        $("#HostLabel").css("display", "inline-block")
        $("#LeftToStartMessage").text(" | " + $("#LeftToStartMessage").text())
        createSelector("#LeftToStartMessage:before", "content: ' | '")
        createSelector("#ChatContainer", "clear:both")

    }

    if (pageIsCommonGames()) {
        setupCommonGamesDataTable()
    }

    if(pageIsTournamentOverview()) {
        setupTournamentDecline()
    }

    if(pageIsLadderOverview()) {
        setupLadderClotOverview()
    }

    if(pageIsMapsPage()) {
        setupMapSearch()
    }



    if(pageIsRealTimeLadder()) {
        setupRealTimeLadderPageTimer()
    }

    if(pageIsDashboard() || pageIsRealTimeLadder()) {
        window.setInterval(setRTLadderTime, 1000)
        window.setInterval(setMyGamesTimeLeft, 1000)
        $(window).on("mousewheel", function() {
            $(".ui-tooltip").hide()
        })
    }

    if(pageIsProfile()) {
        createSelector(".profileBox", "background-image: url(\'https://d2wcw7vp66n8b3.cloudfront.net/Images/ProfileSpeedBackground.png\'); background-repeat: no-repeat; text-align: left; padding:10px;margin-top: 12px;")

    //    setupManagerLeague();
    }
    
    window.lastRefresh;
    window.myGamesTable = $("#MyGamesTable");
    window.openGamesTable = $("#OpenGamesTable");
    window.promotedGamesTable = $("#PromotedGamesTable");
    window.lastClick = new Date();
    
    Database.init(function() {
        if(pageIsDashboard()) {
            warlight_shared_viewmodels_WaitDialogVM.Start("Tidying Up...")
        }
        
        setIsMember();
        setGlobalStyles();
        setupUserscriptMenu();
        setupBookmarkMenu();
        checkVersion();
        main();
        setupSnowflakes()
    })

}


function main() {
    if(pageIsForumOverview()) {
        ifSettingIsEnabled("hideOffTopic", function() {
            hideOffTopicThreads()
        })
        
    }  

    if(pageIsForumOverview() || pageIsSubForum()) {
        setupSpammersBeGone()
    }
    
    ifSettingIsEnabled("unlinkDashboard", function() {
        $("#MultiPlayerBtn").attr('href', 'https://www.warlight.net/MultiPlayer?MyGames=1');
        $("#SubTabRow td > a[href='/MultiPlayer/']").attr('href', 'https://www.warlight.net/MultiPlayer?MyGames=1');
    })
    
    if (pageIsMultiplayer()) {
        //Show Open Games Link
        ifSettingIsEnabled('showOpenGamesTab', function() {
            showOpenGamesLink();
        })
    }
    
    if(pageIsProfile() && $("#BlackListImage").length > 0) {
        ifSettingIsEnabled('showPrivateNotesOnProfile', function() {
            loadPrivateNotes();
        })
    }
    
    setupRandomizedBonuses();
    
    if (pageIsDashboard()) {
        window.StringTools.htmlEscape = function (a) {
            if (a.indexOf("##joined##") >= 0) {
                a = a.replace("##joined##", "");
                return htmlEscape(a) + '<img style="display:inline-block;height:16px;width:16px;margin-left:10px;z-index:10;cursor:default" src="https://i.imgur.com/6akgXa7.png" title="You already joined this game">';
            } else {
                return htmlEscape(a);
            }

        }
        setupPlayerSearch();
        hideBlacklistedThreads();
        setupBasicDashboardStyles();
        
        setupCustomSort(function() {
            Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "customFilter", function(f) {
                var filter = (f && f.value) ? f.value : 4;
                $("#MyGamesFilter").val(filter)
                refreshMyGames();
            })
            
        });
        refreshOpenGames();        
        setupOpenGamesFilter();
        
        ifSettingIsEnabled('hideCoinsGlobally', function() {
            hideCoinsGlobally()
        })
        
        ifSettingIsEnabled('useDefaultBootLabel', function() {
            createSelector(".BootTimeLabel", "z-index:50;");
        }, function() {
            createSelector(".BootTimeLabel", "color:white !important;font-weight:normal!important;font-style:italic;font-size:13px!important;z-index:50;");
        })

        ifSettingIsEnabled("hideRefreshButton", function() {
            createSelector("#refreshAll", "display: none");
        })

        ifSettingIsEnabled("highlightTournaments", function() {
            createSelector("#MyTournamentsTable tbody", "background:#4C4C33;");
        })

        ifOneOrMoreIsEnabled(["hidePromotedGames", "hideCoinsGlobally"], function() {
            createSelector("#PromotedGamesTable", "display:none");
        })

        ifSettingIsEnabled("hideMyGamesIcons", function() {
            createSelector("#MyGamesTable td div img, #MyGamesTable td div a img", "display:none;");
        })

        ifSettingIsEnabled("scrollGames", function() {
            setupFixedWindowWithScrollableGames();
        }, function() {
            createSelector(".SideColumn", "padding-top: 22px;")
            createSelector("body", "overflow: auto")
            createSelector("#MainSiteContent > table", "width: 70%;min-width: 1200px;")
        }, function() {
            setupRightColumn(true);
        })

        ifSettingIsEnabled("hideRightColumn", function() {
            hideRightColumn();
        })

        $("label[for='MultiDayRadio']").on("click", function () {
            registerGameTabClick()

        });

        $("label[for='RealTimeRadio']").on("click", function () {
            registerGameTabClick()
        });

        $("label[for='BothRadio']").on("click", function () {
            registerGameTabClick()
        });

        $(window).resize(function () {
            ifSettingIsEnabled("scrollGames", function() {
                refreshSingleColumnSize();
            }, undefined, function() {
                makePopupVisible()
            })            
        });

        window.setTimeout(setupRefreshFunction, 00);

    } else {
        ifSettingIsEnabled('hideCoinsGlobally', function() {
            hideCoinsGlobally();
        })
    }
}

function setupSettingsDatabase() {
    if(WLJSDefined()){
        warlight_shared_viewmodels_WaitDialogVM.Start("Setting up Muli's Userscript...")
    }
    
    var promises = [];
    $.each(userscriptSettings, function(key, set) {
        promises[key] = $.Deferred();
        var setting = {
            name: set.id,
            value: set.selected
        }
        Database.update(Database.Table.Settings, setting, undefined, function() {
            promises[key].resolve();
        })
    })
    $.when.apply($, promises).done(function () {
        sessionStorage.setItem("showUserscriptMenu", true)
        window.setTimeout(window.location.reload(), 2000)
    })
}

function 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');
}

/**
 * Creates the Userscript-Menu
 */
function setupUserscriptMenu() {

    var inputs = '';

    $.each(userscriptSettings, function (key, setting) {
        if (setting.title != '') {
            inputs += '<span class="title">' + setting.title + '</span><br>';
        }
        var help = setting.help != undefined ? '<img src="' + IMAGES.QUESTION + '" class="help-icon" onclick=\'showSettingHelp("' + setting.id + '", this)\'>' : ''
        inputs += '<label for="_' + setting.id + '">' + setting.text + help + '</label>' + '<input type="checkbox" id="' + setting.id + '"><br>';
        if (setting.addBreak) {
            inputs += '<hr>';
        }
    });

    inputs += '<div class="close-userscript">Close and Refresh</div>';
    $("body").append('<ul class="custom-menu"><div class="content"></div></ul>');
    $("body").append("<div class='overlay' style='display: none'></div><div class='popup popup600 userscript-show' style='display: none'><div class='head'>Change Userscript Settings " + GM_info.script.version + "<img class='close-popup-img' src='" + IMAGES.CROSS + "' height='25' width='25'></div>" + inputs + "</div>");
    $(".userscript-show").on("change", function () {
        storeSettingsVariables();
    });
    $("#TopRightDropDown .dropdown-divider").before('<li><div class="userscript-menu">Muli\'s Userscript</div></li>');

    $(".userscript-menu").on("click", function () {
        showUserscriptMenu()
    });

    $(".close-userscript").on("click", function () {
        $(".userscript-show").fadeOut();
        $(".overlay").fadeOut();
        location.reload();
    });

    $(".close-popup-img").on("click", function () {
        $(".userscript-show").fadeOut();
        $(".overlay").fadeOut();
        $("embed#main").css('opacity', '1');
    });
    
    $("#hideRightColumn").after('<button id="sortTables">Sort Right Column Tables</button><br>')
    createSelector("#sortTables","margin-top: 5px")
    $("#sortTables").on("click", function() {
        showSortTables()
    })
    
    $("#snowLight").after('<button id="resetHiddenThreads" style="float: left; margin: 10px 5px">Reset Hidden Threads</button>')
    $("#snowLight").after('<button id="exportSettings" style="float: left; margin: 10px 5px">Export Settings</button><br>')
    $("#snowLight").after('<button id="showImportSettings" style="float: left; margin: 10px 5px">Import Settings</button>')
    $("body").append("<div class='popup popup600 exportSettings-show' style='display: none'><div class='head'>Export Settings <img class='close-popup-img' src='" + IMAGES.CROSS + "' height='25' width='25'></div>Copy or download this text and save it somwhere on your computer!<br><br><textarea id='exportSettingsBox'></textarea><a id='downloadExportSettingsFile' href='' download='tuyd_settings.txt'>Download Text-File</a></div>");
    $("body").append("<div class='popup popup600 importSettings-show' style='display: none'><div class='head'>Export Settings <img class='close-popup-img' src='" + IMAGES.CROSS + "' height='25' width='25'></div><textarea id='importSettingsBox' placeholder='Copy settings here'></textarea><button id='importSettings'>Import Settings</button></div>");
    
    createSelector("#exportSettingsBox, #importSettingsBox", "width:100%; height: 300px") 
    $("#exportSettings").on("click", function() {
        exportSettings();
    })
    $("#showImportSettings").on("click", function() {
        showPopup('.importSettings-show');
    }) 
    
    $("#importSettings").on("click", function() {
        importSettings();
    })
    $("#resetHiddenThreads").on("click", function() {
        window.undoIgnore();
    })
    
    
    getSortTables(function(tables){
        var tableCode = ''
        $.each(tables, function(key, table) {
            tableCode += '<div class="sortableLadder ' + (table.hidden ? 'tableSortHidden' : '') +'" data-name="' + table.name + '" data-tableId="' + table.id + '">' + table.name + '<div class="tableSortNavigation"><span class="tableSortUp">▲</span><span class="tableSortDown">▼</span><span class="tableSortHideShow"><img src="' + IMAGES.EYE + '"></span></div></div>'
        })
        
        createSelector(".sortableLadder", "border: 1px gray solid;margin: 5px;padding: 5px;background-color:rgb(25, 25, 25);")
        createSelector(".tableSortNavigation", "display: inline-block;float: right;margin-top: -2px;")
        createSelector(".tableSortNavigation span", "padding: 3px 10px; cursor: pointer")
        createSelector(".tableSortNavigation span:hover", "color: #C0D0FF")
        createSelector(".sortTableHighlight", "background-color: rgb(60, 60, 60)")
        createSelector(".tableSortHideShow img", "height: 10px")

        createSelector(".tableSortHidden", "opacity: 0.2;") 



        $("body").append(' <div class="popup popup600" id="sortTablePopup" style="display:none;margin-top: 150px; width: 500px; margin-left: -282px;"><div class="head" style=" margin-top: 152px;width:560px;">Sort Tables<img class="close-popup-img" src="' + IMAGES.CROSS + '" height="25" width="25"></div>' + tableCode +' <div class="close-userscript" onclick="window.saveTableSort()">Save & Refresh</div></div>')
        
        
         $(".close-popup-img").unbind();
         $(".close-popup-img").on("click", function () {
            $(".popup").fadeOut();
            $(".overlay").fadeOut();
        });

        $(".tableSortUp").on("click", function() {
            $(".sortTableHighlight").removeClass("sortTableHighlight")
            var table = $(this).closest(".sortableLadder")
            table.addClass("sortTableHighlight")

            var prev = table.prev()
            table = table.detach()
            prev.before(table)
        })

        $(".tableSortDown").on("click", function() {
            $(".sortTableHighlight").removeClass("sortTableHighlight")
            var table = $(this).closest(".sortableLadder")
            table.addClass("sortTableHighlight")

            var next = table.next()
            table = table.detach()
            next.after(table)
        })

        $(".tableSortHideShow").on("click", function() {
            $(".sortTableHighlight").removeClass("sortTableHighlight")
            var table = $(this).closest(".sortableLadder")
            table.addClass("sortTableHighlight")
            table.toggleClass("tableSortHidden")
        })

        checkUserscriptMenuButtons();
    })

}

function importSettings() {
    var deferredCount = 0;
    var resolvedCount = 0;
    var clearPromises = [];
    $.each(Database.Table, function(key, table) {
        clearPromises[deferredCount++] = $.Deferred();
        Database.clear(table, function() {
            clearPromises[resolvedCount++].resolve();
        })
    })
    warlight_shared_viewmodels_WaitDialogVM.Start("Importing Settings...")
    $(".popup").fadeOut();
    var settings = $("#importSettingsBox").val().trim();
//    try  {
//        settings = JSON.parse((atob(settings)))
//        for (x in settings) {
//            localStorage.setItem(settings[x].id, decodeURI(settings[x].value))
//        }
//        window.location.reload();
//    } catch (e) {
//        console.log(e)
//        warlight_shared_viewmodels_WaitDialogVM.Stop();
//        $(".overlay").fadeOut();
//        warlight_shared_viewmodels_AlertVM.DoPopup("There was an error importing the settings.");
//    }   
    $.when.apply($, clearPromises).done(function () {
        var deferredCount = 0;
        var resolvedCount = 0;
        var promises = [];
        try  {
            settings = JSON.parse(atob(settings))
            $.each(settings, function(key, data) {
                var table = data.table
                var content = data.data
                $.each(content, function(key, value){
                    promises[deferredCount++] = $.Deferred();
                    Database.add(table, value, function() {
                        promises[resolvedCount++].resolve();
                    })
                })
            })
            $.when.apply($, promises).done(function () {
                window.location.reload();
            })
           
            } catch (e) {
                console.log(e)
                warlight_shared_viewmodels_WaitDialogVM.Stop();
                $(".overlay").fadeOut();
                warlight_shared_viewmodels_AlertVM.DoPopup("There was an error importing the settings.");
            }    
    });
       
}

function exportSettings() {
    var settings = [];
    var deferredCount = 0;
    var resolvedCount = 0;
    var promises = [];
    $.each(Database.Table, function (key, table) {
        promises[deferredCount++] = $.Deferred();
        Database.readAll(table, function(data) {
            settings.push({table: table, data: data})
            promises[resolvedCount++].resolve();
        })
        
        
    })
    $.when.apply($, promises).done(function () {
        var settingsString = btoa(JSON.stringify(settings))
        $("#exportSettingsBox").html(settingsString)
        showPopup(".exportSettings-show");
        $("#exportSettingsBox").focus();
        $("#exportSettingsBox").select();
        $("#downloadExportSettingsFile").click(function(){
            this.href = "data:text/plain;charset=UTF-8,"  + settingsString;
        });
    });
}


function showUserscriptMenu() {
    showPopup(".userscript-show")
    $("#TopRightDropDown").fadeOut();
    $("embed#main").attr('wmode', 'transparent');
    $("embed#main").css('opacity', '0');
    $("embed#main").attr('align', 'left');
}

function showPopup(selector) {
    if($(selector).length > 0) {
        $(".popup").fadeOut();
        $(selector).fadeIn();
        $(".overlay").fadeIn();
        makePopupVisible();
    }
}

function makePopupVisible() {
    if($(".popup600:visible").offset() && $(".popup600:visible").offset().top + $(".popup600:visible").height() + 150 > $(window).height() || ($(".popup600:visible").offset() && $(".popup600:visible").offset().top < 100)) {
        $(".popup600:visible").css("margin-top", $(window).height() - 250 - $(".popup600:visible").height())
        $(".popup600:visible .head").css("margin-top", $(window).height() - 250 - $(".popup600:visible").height() + 2)
    }
}

function getSortTables(callback) {
      var defaultTables = 
        [
            {id: "#BookmarkTable", name: "Bookmarks", hidden: false, order: 0}, 
            {id: "#ClotTable", name: "CLOTs", hidden: false, order: 1}, 
            {id: "#MyTournamentsTable", name: "Tournaments", hidden: false, order: 2}, 
            {id: "#RealTimeLadderTable", name: "Real-Time Ladder", hidden: false, order: 3}, 
            {id: "#MapOfTheWeekTable", name: "Map of the Week", hidden: false, order: 4}, 
            {id: "#ForumTable", name: "Forum Posts", hidden: false, order: 5}, 
            {id: "#ClanForumTable", name: "Clan Forum Posts", hidden: false, order: 6}, 
            {id: "#BlogTable", name: "Recent Blog Posts", hidden: false, order: 7}, 
            {id: "#LeaderboardTable", name: "Coin Leaderboard", hidden: false, order: 8}
        ]
      
    if($("#ShopTable").length > 0) {
        defaultTables.push({id: "#ShopTable", name: "WarLight Shop", hidden: false, order: -1})
    }
    Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "tableSort", function(tableData) {
        if(tableData && tableData.value.length > 3) {
            var tables = tableData.value;
            if($("#ShopTable").length > 0 && !arrayHasObjWithId(tables, "#ShopTable")) {
                tables.push({id: "#ShopTable", name: "WarLight Shop", hidden: false, order: -1})
            }
            callback($(tables).sort(compareTable));
        } else {
            callback($(defaultTables).sort(compareTable))
        } 
    })
    
}

function arrayHasObjWithId(arr, id) {
    var found = false;
    $.each(arr, function(key, val) {
        if(val.id == id) {
            found = true;
        }
    })
    return found;
}

window.saveTableSort = function() {
    var tables = []
    $.each($("#sortTablePopup > div.sortableLadder"), function(key, table) {
        var order = key
        var id = $(table).attr('data-tableId')
        var hidden = $(table).hasClass("tableSortHidden")
        var name = $(table).attr('data-name')
        tables.push({id: id, name: name, hidden: hidden, order: order})
    })
    var tableSort = {
        name: "tableSort",
        value: tables
    }
    Database.update(Database.Table.Settings, tableSort, undefined, function() {
        $("#sortTablePopup").fadeOut();
        $(".overlay").fadeOut();
        refreshOpenGames();
    })
    
    
}

function showSortTables() {
    $(".popup").fadeOut();
    showPopup("#sortTablePopup")
}

function compareTable(a,b) {
  if (a.order < b.order)
    return -1;
  if (a.order > b.order)
    return 1;
  return 0;
}

function showInfo(text, x, y) {
    window.setTimeout(function () {
        if (!$(".custom-menu").is(':visible')) {
            $(".custom-menu .content").html(text);
            $(".custom-menu").finish().toggle(100).

            // In the right position (the mouse)
            css({
                top: x + "px",
                left: y + "px"
            });
        }

    }, 10);
}

window.showSettingHelp = function (id, obj) {
    var help = '';
    $.each(userscriptSettings, function (key, setting) {
        if (setting.id == id) {
            help = setting.help;
        }
    });
    var x = $(obj).offset().top;
    var y = $(obj).offset().left;
    showInfo(help, x, y);


}

function checkUserscriptMenuButtons() {
    $.each(userscriptSettings, function (key, set) {
        Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, set.id, function(setting) {
            if(setting){
                $("#" + setting.name).prop("checked", setting.value);
            } else {
                $("#" + set.id).prop("checked", set.selected);
            }
            
        })
    });
}

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

/**
 * Stores User-Settings to local Storage
 */
function storeSettingsVariables() {
    $.each(userscriptSettings, function (key, set) {
        var isEnabled = $("#" + set.id).prop("checked");
        var setting = {
            name: set.id,
            value: isEnabled
        }
        Database.update(Database.Table.Settings, setting, undefined, function() {
            
        })
    });

}

/**
 * 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").width($(".showGames thead tr").closest("table").width()-30)
    $(".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) {
    console.log("Reloading Games")
    if ($(".popup").is(":visible") && !force) {
        return;
    }
    ifSettingIsEnabled('scrollGames', function() {
        openGamesTable.scrollTop(0);
        myGamesTable.scrollTop(0);
        promotedGamesTable.scrollTop(0);
    })

    $('table').css('overflow-y', 'hidden')
    refreshMyGames();
    refreshOpenGames();
    refreshPromotedGames();
}

function setupCustomSort(cb) {
    Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "customSort", function(sort) {
        sortType = (sort != undefined && sort.value != undefined) ? sort.value : 1;
        $("#myGamesSortContainer").remove();
        var target;
        ifSettingIsEnabled("scrollGames", function() {
            target = $($("#MyGamesTable thead tr").find("*")[0]);
        }, function() {
            target = $($("#MyGamesTable thead tr td").find("*")[0]);
        }, function() {
            target.after('<div id="myGamesSortContainer" style="display:inline-block;float:right">Sort: <select id="myGamesSort" style="letter-spacing: 0px;margin-top: 5px;"> <option value="1" ' + (sortType == 1 ? 'selected' : '') + '>Default</option><option value="4" ' + (sortType == 4 ? 'selected' : '') + '>Default - Show time left</option> <option value="3" ' + (sortType == 3 ? 'selected' : '') +'>By time left</option><option value="2"' + (sortType == 2 ? 'selected' : '') +'>By time left - Ignore chat</option> </select></div>')
        
            sessionStorage.setItem("customSort", sortType)

            $("#myGamesSort").on("change", function() {
                var sortType = $(this).val();
                sessionStorage.setItem("customSort", sortType)
                var sort = {
                    name: "customSort",
                    value: sortType
                }
                Database.update(Database.Table.Settings, sort, undefined, function() {

                })
                refreshMyGames();
            })
            cb();
            })
        
    })
}

function refreshMyGames(data) {
    
    myGamesTable.find("tbody").fadeTo('fast', 0.15);
    var filter = $("#MyGamesFilter").val() || 4;
    wljs_Jsutil.Post("?", "FilterChange=" + filter, function (a) {
        var myGames = wljs_Jsutil.GamesFromDump(a);
        renderMyGames(myGames)
    });
}

Array.prototype.diff = function(a) {
    return this.filter(function(i) {return a.indexOf(i) < 0;});
};

function renderMyGames(myGames) {
    removeMyGames()
    
    var sortType = sessionStorage.getItem("customSort")
    if(sortType != 1 && sortType != 4) {
        myGames.sort(gameSort)
    }
    
    var dueGames = myGames.filter(function(a) {
        var game = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, a, warlight_shared_viewmodels_SignIn.get_CurrentPlayer())
        return !game.UsOpt.HasCommittedOrders && (game.Game.State == 3 || game.Game.State == 5) && game.UsOpt.State == 2
    })
    
    if (myGames.length == 0) {
        d.append('<tr><td colspan="2" style="color: #C1C1C1">' + warlight_shared_viewmodels_main_MultiPlayerDashboardVM.NoGamesHtml(0) + "</td></tr>");
    } else {
        
        //Render MyGames
        for (var f = 0; f < myGames.length;) {
            var g = myGames[f];
            ++f;
            g = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, g, warlight_shared_viewmodels_SignIn.get_CurrentPlayer());
            d.append(warlight_shared_viewmodels_main_MultiPlayerDashboardVM.RenderGameHtml(warlight_shared_viewmodels_ConfigurationVM.Settings, g, null) + "<div>Hallo</div>")                
        }
        
        //Setup time left in GameRow
        if(sortType != 1) {
            $.each(dueGames, function(key, game) {
                var id = game.GameID
                var timeLeft = Math.min(game.AutoBoot, game.VoteToBoot, game.DirectBoot) - game.WaitingFor
                var bootTime = new Date().getTime() + parseInt(timeLeft)
                $("[gameid='" + id + "']").find("td div + span").append(`<span data-boottime="${bootTime}" data-inline> (${getTimeLeft(timeLeft)} left)</span>`)

            })
        }
        
        //Setup time left tooltip
        $.each(myGames, function(key, game) {
            var id = game.GameID
            var timeLeft = Math.min(game.AutoBoot, game.VoteToBoot, game.DirectBoot) - game.WaitingFor;
            var bootTime = new Date().getTime() + parseInt(timeLeft)
            var label = $("[gameid='" + id + "']").find(".BootTimeLabel")

            label.attr("title", getTimeLeft(timeLeft, true) + " left")
            label.tooltip({ show: {delay: 100}, hide: 100 });
            label.attr("data-boottime", bootTime)
        })
        
        //Setup NextGameId
        var nextGameIds = [];
        $.each(myGames, function(key, game) {
            var id = game.GameID
            if(gameCanBeNextGame(game)){
                nextGameIds.push(id)
            }
        })
        
        $.each(myGames, function(key, game) {
            var id = game.GameID
            if(nextGameIds.length > 0 && nextGameIds[0]) {
                var ids = [];
                var url = "https://www.warlight.net/MultiPlayer?GameID=" + id + (nextGameIds.length > 1 ? ("&NextGameIDs=" + nextGameIds.slice(1, nextGameIds.length).join()) : "");
                $("[gameid='" + id + "'] td > a").attr("href", url)
                nextGameIds.push(nextGameIds.shift())
            }
        })
        
    }
    myGamesTable.find("tbody").fadeTo('fast', 1, function () {
        myGamesTable.css('overflow-y', 'scroll');
    });
    $(window).trigger('resize');
}

function removeMyGames() {
    d = $("#MyGamesTable").children("tbody");
    d.children().remove();
}

function setMyGamesTimeLeft() {
    $.each($("[data-boottime]"), function(key, target) {
        var timeLeft = $(target).attr("data-boottime") - new Date().getTime()
        if($(target).is("[data-inline]")) {
            $(target).text(` (${getTimeLeft(timeLeft)} left)`)
        } else {
            $(target).tooltip( "option", "content",  getTimeLeft(timeLeft, true) + " left")
        }
        
    })
}

function getTimeLeft(time, detailed) {
    
    var hours1 = 1 * 60 * 60 * 1000
    var hours5 = 5 * 60 * 60 * 1000
    var days5 = 5 * 25 * 60 * 60 * 1000
    var secs = time / 1000
    var mins = secs / 60
    var hours = mins / 60
    var days = hours / 24
    
    if(time < 0) {
        return "Hurry up! No time"
    } else if(time < hours1) {
        var m = Math.round(Math.floor(mins) % 60);
        var s = Math.round(Math.floor(secs) % 60);
        return m > 0 ? (m + (m == 1 ? " minute " : " minutes ")) : "" + s + (s == 1 ? " second" : " seconds")
    } else if(time < hours5) {
        var m = Math.round(Math.floor(mins) % 60)
        var h = Math.floor(hours);
        return h + (h == 1 ? " hour " : " hours ") + m + (m == 1 ? " minute" : " minutes")
    } else if(time < days5 && !detailed) {
        var d = Math.floor(days)
        var h = Math.round(Math.floor(hours) % 24)
        return (d > 0 ? d + (d == 1 ? " day " : " days ") : "") + h + (h == 1 ? " hour" : " hours")
    } else if(time >= days5 && !detailed) {
        return Math.round(days) + " days "
    } else if(detailed) {
        var d = Math.floor(days)
        var h = Math.round(Math.floor(hours) % 24)
        var m = Math.round(Math.floor(mins) % 60)
        return (d > 0 ? d + (d == 1 ? " day " : " days ") : "") + h + (h == 1 ? " hour " : " hours ") + m + (m == 1 ? " minute" : " minutes")
    } else {
        return "undefined left " + time
    }
}

function gameSort(a,b){
    
    var sortType = sessionStorage.getItem("customSort")
    var gameA = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, a, warlight_shared_viewmodels_SignIn.get_CurrentPlayer())
    var gameB = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, b, warlight_shared_viewmodels_SignIn.get_CurrentPlayer())
    
    var aRealTime = gameA.Game.RealTimeGame
    var aPlaying = (gameA.Game.State == 3 || gameA.Game.State == 5) && gameA.UsOpt.State == 2
    var aPrio0 = gameA.Game.PrivateMessagesWaiting || gameA.Game.PublicChatWaiting || gameA.Game.TeamChatWaiting
    var aPrio1 = gameA.Game.State == 2 && gameA.UsOpt.State == 1 //Waiting to join
    var aPrio4 = gameA.Game.State == 2 && gameA.Game.WaitingForYouToStart //Waiting for you to start
    var aPrio3 = aPlaying && !gameA.UsOpt.HasCommittedOrders //Your turn 3 = turn, 5 = picking
    var aBootTime = Math.min(a.AutoBoot, a.VoteToBoot, a.DirectBoot) - a.WaitingFor

    var bRealTime = gameB.Game.RealTimeGame
    var bPlaying = (gameB.Game.State == 3 || gameB.Game.State == 5) && gameB.UsOpt.State == 2
    var bPrio0 = gameB.Game.PrivateMessagesWaiting || gameB.Game.PublicChatWaiting || gameB.Game.TeamChatWaiting
    var bPrio1 = gameB.Game.State == 2 && gameB.UsOpt.State == 1
    var bPrio4 = gameB.Game.State == 2 && gameB.Game.WaitingForYouToStart
    var bPrio3 = bPlaying && !gameB.UsOpt.HasCommittedOrders
    var bBootTime = Math.min(b.AutoBoot, b.VoteToBoot, b.DirectBoot) - b.WaitingFor

    if(aRealTime && !bRealTime) return -1;
    if(bRealTime && !aRealTime) return 1;
    
    if(sortType == 3) {
        if(aPrio0 && !bPrio0) return -1;
        if(bPrio0 && !aPrio0) return 1;
    }

    if(aPrio1 && !bPrio1) return -1;
    if(bPrio1 && !aPrio1) return 1;

    if(aPrio3 && !bPrio3) return -1;
    if(bPrio3 && !aPrio3) return 1;
    
    if(aPlaying && !bPlaying) return -1;
    if(bPlaying && !aPlaying) return 1;

    if(aPrio3 && bPrio3) return aBootTime - bBootTime;
    
    if(aPrio4 && !bPrio4) return -1;
    if(bPrio4 && !aPrio4) return 1;
    
    return a.WaitingFor - b.WaitingFor
}

function gameCanBeNextGame(g) {
    var game = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 0, g, warlight_shared_viewmodels_SignIn.get_CurrentPlayer())
    
    
    var playing = (game.Game.State == 3 || game.Game.State == 5) && game.UsOpt.State == 2
    var prio0 = game.Game.PrivateMessagesWaiting || game.Game.PublicChatWaiting || game.Game.TeamChatWaiting
    var prio1 = game.Game.State == 2 && game.UsOpt.State == 1 //Waiting to join
    var prio3 = playing && !game.UsOpt.HasCommittedOrders //Your turn 3 = turn, 5 = picking
    var prio4 = game.Game.State == 2 && game.Game.WaitingForYouToStart //Waiting for you to start
    
    return prio0 || prio1 || prio3 || prio4
}


function refreshOpenGames() {
    deletedMD = deletedRT = 0;
    openGamesTable.find("tbody").fadeTo('fast', 0.15);
    var page = $('<div />').load('https://www.warlight.net/MultiPlayer/ ', function () {
        var data = page.find('#AllOpenGamesData').html();
        $('#AllOpenGamesData').html(data);
        WL_MPDash.OpenGamesCtrl.AllOpenGamesData = data
        Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "openGamesFilters", function(filters) {
            var openGamesFilters;
            if(filters) {
                openGamesFilters = filters.value;
            }
            var games;
            if (openGamesFilters && openGamesFilters["disableAll"] != true) {
                games = filterGames(wljs_Jsutil.GamesFromDump(data), openGamesFilters);
            } else {
                games = wljs_Jsutil.GamesFromDump(data);
            }
            $.each(games, function (key, game) {
                if ($(game).playerJoined()) {
                    games[key] = $(game).markJoined();
                }
            });


            wljs_AllOpenGames = WL_MPDash.OpenGamesCtrl.AllOpenGames = games;

            var RealTimeLadderTable = page.find("#RealTimeLadderTable tbody tr:first-of-type").outerHTML();
            $("#RealTimeLadderTable tbody tr:first-of-type")
            $("#RealTimeLadderTable tbody tr:first-of-type").replaceWith(RealTimeLadderTable)

            replaceAndFilterForumTable(page.find("#ForumTable").outerHTML());
            $("#ClanForumTable").replaceWith(page.find("#ClanForumTable").outerHTML())
            setupRightColumn()

            updateOpenGamesCounter();

            wljs_AllOpenGamesData = wljs_multiplayer_Ctrl_AllOpenGamesData = data;
            var player = warlight_shared_viewmodels_SignIn.get_CurrentPlayer();
            if ((new js.JQuery(this.BothRadio)).is(":checked")) {
                player.OpenGamePreference = 1;
            } else if ((new js.JQuery(this.MultiDayRadio)).is(":checked")) {
                player.OpenGamePreference = 2;
            } else if ((new js.JQuery(this.RealTimeRadio)).is(":checked")) {
                player.OpenGamePreference = 3;
            }
            wljs_Jsutil.Post("/MultiPlayer/", "ChangePace=" + player.OpenGamePreference, function (a) {});


            var a = $("#OpenGamesTable").children("tbody");
            a.children().remove();

            var gamesToShow = warlight_shared_viewmodels_main_MultiPlayerDashboardVM.GamesToShow(wljs_AllOpenGames, player.OpenGamePreference, 0 == this.ShowingAllOpenGames)
            for (var b = 0; b < gamesToShow.length;) {
                var game = gamesToShow[b];
                b++;
                game.get_IsLottery() && warlight_shared_viewmodels_main_MultiPlayerDashboardVM.get_HideLotteryGames() ||
                    (game = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 2, game, warlight_shared_viewmodels_SignIn.get_CurrentPlayer()), a.append(warlight_shared_viewmodels_main_MultiPlayerDashboardVM.RenderGameHtml(warlight_shared_viewmodels_ConfigurationVM.Settings, game, null)))
            }
            openGamesTable.find("tbody").fadeTo('fast', 1, function () {
                openGamesTable.css('overflow-y', 'scroll');
            });
            addOpenGamesSuffix();
            domRefresh();
        })
    });
}

function refreshPromotedGames() {
    promotedGamesTable.find("tbody").fadeTo('fast', 0.15);
    var page = $('<div />').load('https://www.warlight.net/MultiPlayer/ ', function () {
        var data = page.find('#MorePromotedGamesData').html();
        $('#MorePromotedGamesData').html(data);
        wljs_PromotedGames = wljs_Jsutil.GamesFromDump(data);

        var a = $("#PromotedGamesTable").children("tbody");
        a.children().remove();
        for (var b = 0; b < wljs_PromotedGames.length;) {
            var game = wljs_PromotedGames[b];
            b++;
            (game = (new warlight_shared_viewmodels_main_MyGamesGameVM).Init(warlight_shared_viewmodels_ConfigurationVM.Settings, 2, game, warlight_shared_viewmodels_SignIn.get_CurrentPlayer()), a.append(warlight_shared_viewmodels_main_MultiPlayerDashboardVM.RenderGameHtml(warlight_shared_viewmodels_ConfigurationVM.Settings, game, null)))
        }
        domRefresh();
        promotedGamesTable.find("tbody").fadeTo('fast', 1, function () {
            promotedGamesTable.css('overflow-y', 'scroll');
        });

    });
}


/**
 * 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();
            }
        });
    }

    $(".MainColumn").prepend($('#refreshAll'))

    ifSettingIsEnabled('autoRefreshOnFocus', function() {
		$(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();
            }
        }
    });
}


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()
    }

}

if(pageIsNewThread()) {
    $("[onclick='undoIgnore()']").closest("th").remove();
    $(".checkbox").closest("td").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))
    });

}

function setGlobalStyles() {
    $("[src='https://d2wcw7vp66n8b3.cloudfront.net/Images/MembershipGiftIcon.gif']").closest(".dataTable").attr("id", "ShopTable");
    createSelector('.help-icon', 'display:inline-block;position:absolute; margin-left:10px;margin-top: 2px;cursor:pointer; height: 15px; width: 15px;')
    var winHeight = $(window).height();
    createSelector(".userscript-menu", "display: block;color: #555;text-decoration: none;line-height: 18px;padding: 3px 15px;margin: 0;white-space: nowrap;");
    createSelector(".userscript-menu:hover", "cursor:pointer;background-color: #08C;color: #FFF;cursor: pointer;");
    createSelector(".popup", "position: fixed;;left: 50%;background: #171717;top: 100px;z-index: 99; color:white;padding:60px 30px 30px 30px;border: 2px solid gray;border-radius:8px;max-height:" + (winHeight - 200) + "px;overflow-y:auto");
    createSelector(".close-userscript", "margin: 40px 0;width: 100%;text-align: center;font-size: 15px;cursor: pointer;background: gray;line-height: 30px;border-radius: 8px;clear: both");
    createSelector(".close-popup-img", "float:right;margin:5px;cursor:pointer;margin-right: 20px");
    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: 98;opacity: 0.5;width: 100%;height: 100%;position: fixed;");
    createSelector(".popup .head", "position: fixed;height: 40px;background: #330000;width: 660px;left: 0;right: 0;top: 100px;color: white;font-size: 15px;text-align: center;line-height: 40px;border-top-left-radius:8px;border-top-right-radius:8px;margin:auto;z-index:10000;");
    createSelector(".userscript-show", "display:none");
    createSelector("#MorePromotedGamesHorizontalRow", "display:none");
    createSelector(".newSetting", "color: gold;font-weight: bold;");
    createSelector(".userscript-menu img", "height: 18px;display: inline-block;position: relative;margin-bottom: -5px;margin-right: 7px;");
    createSelector(".custom-menu", "display: none;z-index: 98;position: absolute;overflow: hidden;border: 1px solid #CCC;white-space: nowrap;font-family: sans-serif;background: #FFF;color: #333;border-radius:5px;padding: 10px;z-index:100000000; cursor:pointer");
    createSelector(".custom-menu .content", "width: 300px;white-space: pre-wrap;");
    createSelector('.popup input[type="text"]', 'display: inline-block;background: none;border-top: none;border-left: none;border-right: none;color: green;font-size: 15px;border-bottom: 1px white dashed;font-family: Verdana;padding: 0 5px 0 5px;text-align: center;margin-right: 5px');

    createSelector(".popup840", "width: 840px;margin-left: -452px");
    createSelector(".popup600", "width: 600px;margin-left: -332px");

    createSelector(".popup840 .head", "width: 900px");
    createSelector(".popup600 .head", "width: 660px");
        
    createSelector(".context-menu", "display: none;z-index: 100;position: absolute;overflow: hidden;border: 1px solid #CCC;white-space: nowrap;font-family: sans-serif;background: #FFF;color: #333;border-radius: 5px;padding: 0;");
    createSelector(".context-menu li", "padding: 8px 12px;cursor: pointer;list-style-type: none;");
    createSelector(".context-menu li:hover", "background-color: #DEF;");
    createSelector("#MyGamesTable select","margin: 0 10px 0 5px; width: 125px")
    createSelector("#MyGamesFilter", "float:right")
    createSelector("#MyGamesTable thead tr", "text-align: right")

    $("body").on("click", function (e) {
        if ($(".custom-menu").is(':visible')) {
            $(".custom-menu").hide(100);
        }
    });
}

window.deletedRT = 0;
window.deletedMD = 0;

function filterGames(games, openGamesFilters) {
    var filteredGames = [];
    var deletedGames = [];

    $.each(games, function (key, game) {
        if (!$(game).getsFiltered(openGamesFilters)) {
            filteredGames.push(game);
        } else {
            if (game.RealTimeGame) {
                deletedRT++;
            } else {
                deletedMD++;
            }
        }
    });

    return filteredGames;
}


function storeFilterVariables() {
    openGamesFilters = {};

    $.each(filters, function (key, filter) {
        if (filter.type == "checkbox") {
            openGamesFilters[filter.id] = $("#" + filter.id).prop("checked");
        }
    });
    openGamesFilters["hideKeyword"] = $("#hideKeyword").val()
    openGamesFilters["hideRealTimeBootTime"] = $("#hideRealTimeBootTime").val()
    openGamesFilters["hideMultiDayBootTimeDays"] = $("#hideMultiDayBootTimeDays").val()
    openGamesFilters["hideMultiDayBootTimeHours"] = $("#hideMultiDayBootTimeHours").val()

    var luck = $("#hideLuck").val();
    openGamesFilters["hideLuck"] = ($.isNumeric(luck) && luck <= 100 && luck >= 0) ? luck : 100;

    var minPlayers = $("#hideMinPlayers").val();
    openGamesFilters["hideMinPlayers"] = ($.isNumeric(minPlayers) && minPlayers <= 100 && minPlayers >= 2) ? minPlayers : 2;

    var maxPlayers = $("#hideMaxPlayers").val();
    openGamesFilters["hideMaxPlayers"] = ($.isNumeric(maxPlayers) && maxPlayers <= 100 && maxPlayers >= 2) ? maxPlayers : 100;

    if (parseFloat(openGamesFilters["hideMinPlayers"]) > parseFloat(openGamesFilters["hideMaxPlayers"])) {
        openGamesFilters["hideMaxPlayers"] = openGamesFilters["hideMinPlayers"]
    }

    var rtBoot = $("#hideRealTimeBootTime").val();
    openGamesFilters["hideRealTimeBootTime"] = $.isNumeric(rtBoot) ? rtBoot * 60 * 1000 : 0;

    var mdBoot = calculateMDBoot($("#hideMultiDayBootTimeHours").val(), $("#hideMultiDayBootTimeDays").val());

    openGamesFilters["hideMultiDayBootTimeDays"] = mdBoot.days;
    openGamesFilters["hideMultiDayBootTimeHours"] = mdBoot.hours;

    openGamesFilters["hideMultiDayBootTimeInMs"] = (parseInt(mdBoot.days) * 24 + parseInt(mdBoot.hours)) * 60 * 60 * 1000;

    var gameFilters = {
        name: "openGamesFilters",
        value: openGamesFilters
    }
    Database.update(Database.Table.Settings, gameFilters, undefined, function() {
        updateFilterSettings()
    })
    
}

function calculateMDBoot(hours, days) {
    hours = $.isNumeric(hours) ? hours : 0;
    days = $.isNumeric(days) ? days : 0;

    if (hours >= 24) {
        days = parseFloat(days) + parseInt(hours / 24);
        hours -= parseInt(hours / 24) * 24
    }

    return {
        hours: hours,
        days: days
    }

}

function updateFilterSettings() {
    Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, "openGamesFilters", function(gameFilters) {
        if(!gameFilters || !gameFilters.value) {
            return;
        }
        var openGamesFilters = gameFilters.value;
        $.each(filters, function (key, filter) {
            if (filter.type == "checkbox") {
                $("#" + filter.id).prop("checked", openGamesFilters[filter.id]);
            }
        });
        $("#hideLuck").val(openGamesFilters["hideLuck"] || 100);
        $("#hideMinPlayers").val(openGamesFilters["hideMinPlayers"] || 0);
        $("#hideMaxPlayers").val(openGamesFilters["hideMaxPlayers"] || 100);
        $("#hideKeyword").val(openGamesFilters["hideKeyword"] || "");
        $("#hideRealTimeBootTime").val(openGamesFilters["hideRealTimeBootTime"] / 1000 / 60 || 0);
        $("#hideMultiDayBootTimeDays").val(openGamesFilters["hideMultiDayBootTimeDays"] || 0);
        $("#hideMultiDayBootTimeHours").val(openGamesFilters["hideMultiDayBootTimeHours"] || 0);
    })
}

function ifSettingIsEnabled(setting, positive, negative, cb) {
    Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, setting, function(setting) {
        if(setting && setting.value) {
            positive();
            if(typeof cb == "function") {
                cb();
            }
        } else {
            if(typeof negative == 'function') {
                negative();
            }
            if(typeof cb == 'function') {
                cb();
            }
        }
    })
}

function ifSettingIsNotEnabled(setting, callback) {
    Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, setting, function(setting) {
        if(!setting.value) {
            callback();
        }
    })
}

function ifAllAreEnabled(settings, positive, negative) {
    var promises = [];
    var allAreEnabled = true;
    $.each(settings, function (key, setting) {
	
		promises[key] = $.Deferred();
		Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, setting, function(set) {
			if(!set || !set.value) {
				 allAreEnabled = false;
			 }
			promises[key].resolve();
		})
    })
    $.when.apply($, promises).done(function () {
        if(allAreEnabled){
            positive()
        } else {
            if(typeof negative == "function") {
                negative();
            }
        }
    })
}

function ifOneOrMoreIsEnabled(settings, positive, negative) {
    var promises = [];
    var isEnabled = false;
    $.each(settings, function (key, setting) {
        
		promises[key] = $.Deferred();
		Database.readIndex(Database.Table.Settings, Database.Row.Settings.Name, setting, function(set) {
			if(set && set.value) {
				 isEnabled = true;
			 }
			promises[key].resolve();
		})
    })
    $.when.apply($, promises).done(function () {
        if(isEnabled){
            positive()
        } else {
            if(typeof negative == "function") {
                negative();
            }
        }
    })
}

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

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

function pageIsRealTimeLadder() {
    return location.href.match(/.*warlight[.]net\/LadderSeason\?ID=3.*$/i);
}

function pageIsProfile() {
    return location.href.match(/.*warlight[.]net\/profile\?p=[0-9]+$/i);
}

function pageIsMapsPage() {
    return location.href.match(/.*warlight[.]net\/maps/i);
}

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

function pageIsNewThread() {
    return location.href.match(/.*warlight[.]net\/Forum\/NewThread.*/i);
}

function pageIsForumThread() {
    return location.href.match(/.*warlight[.]net\/Forum\/[0-9]+.*/i);
}

function pageIsForumOverview() {
    return location.href.match(/.*warlight[.]net\/Forum\/Forum.*/i);
}

function pageIsThread() {
    return location.href.match(/.*warlight[.]net\/(Forum|Discussion).*/i);
}

function pageIsSubForum() {
    return location.href.match(/.*warlight[.]net\/Forum\/[A-Z]+.*/i);
}

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

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

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

function pageIsClanForumThread() {
    return location.href.match(/.*warlight[.]net\/Discussion\/\?ID=[0-9]+.*/);
}

function pageIsTournament() {
    return location.href.match(/.*warlight[.]net\/MultiPlayer\/Tournament\?ID=[0-9]+/i);
}

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

function pageIsGame() {
    return location.href.match(/.*warlight[.]net\/MultiPlayer\?GameID=[0-9]+/i);
}

function pageIsCommonGames() {
    return location.href.match(/.*warlight[.]net\/CommonGames\?p=[0-9]+$/i);
}

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 filtersHTML = "<hr>";
    $.each(filters, function (key, filter) {
        if (filter.type == "checkbox") {
            filtersHTML += '<div class="filterOption"><label for="' + filter.id + '">' + filter.text + '</label><input type="checkbox" id="' + filter.id + '"></div>';
        } else if (filter.type == "custom") {
            filtersHTML += '<div class="filterOption">' + filter.text + '</div>';
        }
    });

    $("body").append("<div class='popup popup840 filters-show' style='display: none'><div class='head'>Change Filter Settings<img class='close-popup-img' src='" + IMAGES.CROSS + "' height='25' width='25'></div>" + filtersHTML + '<div class="close-userscript">Close and Apply</div></div>');

    createSelector('hr', 'height: 1px;border: none;background-color: gray;opacity:0.5;');
    createSelector('.number', 'width: 31px');
    createSelector('.filterOption', 'width: 400px;float: left;margin: 5px;');
    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;');
    createSelector('.filter-small, .filter-small label', 'font-size: 12px!important;color: #aaa;');

    $("#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 () {
        window.showFilterOptions();
    });

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

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

    updateFilterSettings();
}

function setupBasicDashboardStyles() {
    createSelector(".GameRow a", "font-size:16px !important;");
    createSelector("a", "outline: none");
    createSelector('#PromotedGamesTable td:last-of-type a img', 'display:none');
    createSelector("#MyGamesTable td > a > img", 'display:none');
    createSelector(".GameRow td:last-of-type span,#OpenGamesTable .GameRow td:last-of-type span:first-child, #PromotedGamesTable .GameRow td:last-of-type span:first-child", "margin:5px 0px;position:relative !important;z-index:10;");
    createSelector("#MyGamesTable td span a img, #MyGamesTable td span a img", "display:inherit;");
    createSelector(".GameRow:hover", "background-color:rgb(50, 50, 50);cursor:pointer;");
    createSelector(".GameRow a:hover", "text-decoration:none;");
    createSelector(".TournamentRow a:hover", "text-decoration:none;");
    createSelector(".TournamentRow:hover", "background-color:rgb(50, 50, 50);cursor:pointer;");
    createSelector(".ui-buttonset label", "font-size:11px;");
    createSelector("#OpenGamesTable label:hover", " border: 1px solid #59b4d4;background: #0078a3 50% 50% repeat-x;font-weight: bold;color: #ffffff;");
    createSelector("#OpenGamesTable td:last-child,#MyGamesTable td:last-child, #PromotedGamesTable td:last-child", "position: relative;");
    createSelector("#OpenGamesTable td:nth-child(2) > a,#MyGamesTable td:nth-child(2) > a, #PromotedGamesTable td:nth-child(2) > a", " display: block;width: 100%;height: 100%;float: left;position: absolute;margin-top: -5px;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;");
    createSelector(".loading", "position: absolute;height: 100%;width:  100%;background-color: rgba(255, 255, 255, 0.2);text-align: center;z-index: 12;margin-top: 34px;display:none;");
    createSelector(".loading img", "position: absolute;top: 50%;left: 50%;margin-left: -16px;margin-top: -16px;");
    createSelector("img", "position: relative;z-index:50;");
    createSelector("input", "z-index: 98;position: relative;");
    createSelector(".showGames thead tr", "background: rgb(51, 0, 0) none repeat scroll 0% 0%;z-index: 98;position: fixed;padding: 5px;border-bottom: 1px solid rgb(68, 68, 68);border-top-left-radius: 8px;letter-spacing: 1px;");
    createSelector(".showGames table tbody", "display:table;width:100%;");
    createSelector(".showGames table thead", "position:inherit;");
    createSelector(".ui-tooltip", "background: #EBEBEB;padding: 4px;font-style: italic;");

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

function setupFixedWindowStyles() {
    createSelector('html', 'width: 100%; position:fixed')
    createSelector(".followMeBar", "background: #330000;padding: 5px 0px;position: relative;z-index: 1;color: #fff;border-top-right-radius:8px;border-top-left-radius:8px;border: 1px solid gray;border-bottom:none");
    var top = parseInt($(".showSide").offset().top) + parseInt(43);
    createSelector(".followMeBar.fixed", "position: fixed;top: " + top + "px;z-index: 0;z-index:98;");
    createSelector(".followMeBar.fixed.absolute", "position: absolute;");

    createSelector(".showSide", "overflow-y:scroll;float: left;margin-top: 43px;padding-right: 6px;");
    createSelector(".showSide thead", "display:none");
    createSelector(".showSide table", "border-top-right-radius:0;border-top-left-radius:0");

    createSelector("#switchGameRadio label", "margin-left: 6px !important");
    createSelector(".showGames table", "display:block !important");
    createSelector("#switchGameRadio label:hover", "border: 1px solid rgb(89, 180, 212);border-image-source: initial;border-image-slice: initial;border-image-width: initial;border-image-outset: initial;border-image-repeat: initial;background:rgb(0, 120, 163);font-weight: bold;color: rgb(255, 255, 255);");
    createSelector("#MyGamesTable, #PromotedGamesTable, #OpenGamesTable", "display:none");
    createSelector("#MainSiteContent > table > tbody > tr > td", "width:100%");
    createSelector(".MainColumn", "width: calc(60% - 98px)!important;max-width: 800px;min-width:535px");
    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", "width: 140px;float: right;margin-top: 10px;");
    createSelector("#fakeOpenGameMenu label", "margin-right:2px");
    createSelector("#RestoreLotteryGamesBtn", "display:none");

    createSelector('#ForumTable tbody tr td, #ClanForumTable tbody tr td', 'overflow:hidden;position:relative');
    createSelector('#ForumTable tbody tr td > a, #ClanForumTable tbody tr td > a', 'width: 100%;display: block;height: 100%;float: left;position: absolute;overflow: hidden;z-index: 1;');
    createSelector('#ForumTable tbody tr td span, #ClanForumTable tbody tr td span', 'display: inline-block;z-index: 1;float: left;position: relative;');
    createSelector('#ForumTable tbody tr:hover, #ClanForumTable tbody tr:hover', 'background-color:rgb(50, 50, 50)');

    createSelector('#ForumTable tbody tr td a[href="/Forum/Forum"]', 'position: relative;');
    createSelector('#ClanForumTable tbody tr td a[href="/Clans/Forum"]', 'position: relative;');

$("body").scrollTop(0)
}

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

    var shopTable = $("#ShopTable")
   

    blogTable.before("<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>");
    
    ifSettingIsEnabled("hideCoinsGlobally", function() {
        
    }, function() {
        leaderboardTable.before("<div class='followMeBar'>" + leaderboardTable.find("thead > tr > td").html() + "</div>");
    }, function() {
        myTournamentsTable.before("<div class='followMeBar'>" + myTournamentsTable.find("thead > tr > td").html() + "</div>");
        bookmarkTable.before("<div class='followMeBar'>" + bookmarkTable.find("thead > tr > td").html() + "</div>");

        shopTable.before("<div class='followMeBar'>" + shopTable.find("thead > tr > td").html() + "</div>");


        var clotTable = $("#ClotTable");   
        clotTable.before("<div class='followMeBar'>" + clotTable.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>';
    
    ifOneOrMoreIsEnabled(["hidePromotedGames", "hideCoinsGlobally"], function() {
        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>';
        gameButtons += '</div>';
        setupMainColumn(gameButtons)
    }, function() {
        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>';
        setupMainColumn(gameButtons)
    })

    
}

function setupMainColumn(gameButtons) {
    var mainColumn = $(".MainColumn ");
    mainColumn.prepend('<div class="showGamesContainer">' + gameButtons + '<div class="showGames"></div></div>');
    mainColumn.prepend($('#refreshAll').detach())
    myGamesTable.appendTo(".showGames");

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

    setupFixedWindowStyles();

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

            refreshSingleColumnSize()
        }
    });
}

function hideRightColumn() {
    ifSettingIsEnabled('scrollGames', function() {
        $(".showSide").css("display", "none");
        createSelector(".MainColumn", "margin: auto;max-width: 800px;width: 60%!important;float: none !important;min-width: 600px !important;");
	}, function() {
        $(".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();
    }
    window.setTimeout(function () {
        domRefresh();
        addOpenGamesSuffix();
    }, 1);
}

function updateOpenGamesCounter() {
    var numMD = countGames(wljs_AllOpenGames, 1);
    var numRT = countGames(wljs_AllOpenGames, 2);
    var numBoth = parseInt(numMD) + parseInt(numRT)
    //Both
    $("#OpenGamesTable [for='BothRadio'] span").text('Both (' + numBoth + ')')
        //Real
    $("#OpenGamesTable [for='RealTimeRadio'] span").text('Real-Time (' + numRT + ')')
        //Multi-Day
    $("#OpenGamesTable [for='MultiDayRadio'] span").text('Multi-Day (' + numMD + ')')
}

// Type 1 : Multiday
// Type 2 : Realtime
function countGames(games, type) {
    games = system_linq_Enumerable.Where(games, function (a) {
        if (type == 1) return !a.RealTimeGame;
        if (type == 2) return a.RealTimeGame;
    });
    return system_linq_Enumerable.ToArray(games).length
}

function addOpenGamesSuffix() {
    var deletedBoth = parseInt(deletedMD) + parseInt(deletedRT);
    $("#OpenGamesTable tbody tr:not(.GameRow)").remove();
    var active = $("#OpenGamesTable .ui-buttonset .ui-state-active").text();

    if (active.indexOf('Both') > -1 && deletedBoth > 0) {
        //Both
        $("#OpenGamesTable tbody").append("<tr id='gamesAreHidden' style='color: gray;font-style: italic;'><td colspan='2'>" + getNumHiddenLabelText(deletedBoth) + " <span style='float: right;cursor: pointer;font-size: 11px;margin-left: 10px;display: inline-block;margin-top: 2px;margin-right: 20px;' onclick='showFilterOptions()'>Change Filter Options</span</td></tr>");
    } else if (active.indexOf('Real') > -1 && deletedRT > 0) {
        //Real
        $("#OpenGamesTable tbody").append("<tr id='gamesAreHidden' style='color: gray;font-style: italic;'><td colspan='2'>" + getNumHiddenLabelText(deletedRT) + " <span style='float: right;cursor: pointer;font-size: 11px;margin-left: 10px;display: inline-block;margin-top: 2px;margin-right: 20px;' onclick='showFilterOptions()'>Change Filter Options</span</td></tr>");
    } else if (active.indexOf('Multi') > -1 && deletedMD > 0) {
        //Multi-Day
        $("#OpenGamesTable tbody").append("<tr id='gamesAreHidden' style='color: gray;font-style: italic;'><td colspan='2'>" + getNumHiddenLabelText(deletedMD) + " <span style='float: right;cursor: pointer;font-size: 11px;margin-left: 10px;display: inline-block;margin-top: 2px;margin-right: 20px;' onclick='showFilterOptions()'>Change Filter Options</span</td></tr>");
    }

}

function getNumHiddenLabelText(num) {
    return num == 1 ? "1 Game is hidden" : (num + " Games are hidden");
}


function loadPrivateNotes() {
    console.log("Loading private notes")
    $("#FeedbackMsg").after('<div class="profileBox" id="privateNotes"><h3>Private Notes</h3><p style="width: 285px;overflow:hidden" class="content">Loading Privates Notes..</p></div>');
    var url = $("img[alt='Private Notes']").parent()[0].href;
    var page = $('<div />').load(url, function () {
        var notes = page.find('#PostForDisplay_0').html().trim();
        if (notes) {
            $('#privateNotes .content').html(notes);
        } else {
            $('#privateNotes .content').html('You don\'t have any Private Notes.');
        }

    });
}

window.showFilterOptions = function () {
    showPopup(".filters-show")
}

function domRefresh() {
    $("body").hide(0).show(0);
    $(window).trigger('resize')
}

window.showFilterHelp = function (text, obj) {
    window.setTimeout(function () {
        if (!$(".custom-menu").is(':visible')) {
            $(".custom-menu .content").html(text);
            $(".custom-menu").finish().toggle(100).

            // In the right position (the mouse)
            css({
                top: $(obj).offset().top + "px",
                left: $(obj).offset().left + "px"
            });
        }

    }, 10);
}

function setupBookmarkMenu() {
    bookmarkBody = "<label for='bookmarkName'>Name</label><input style='width:100%;color: lightgray;text-align: left;' type='text' id='bookmarkName'><br><br><label for='bookmarkURL'>Url</label><input style='width:100%; text-align: left; color: lightgray' id='bookmarkURL' type='text'><br><br><label for='bookmarkNewWindow'>Open in new Window</label><input style='float:left;' id='bookmarkNewWindow' type='checkbox'>";

    $("body").append("<div class='popup popup600' id='bookmarkMenu' style='display: none; margin-top: 150px;width:500px; margin-left:-282px'><div class='head' style=' margin-top: 152px;width:560px;'>Add Bookmark<img class='close-popup-img' src='" + IMAGES.CROSS + "' height='25' width='25'></div>" + bookmarkBody + "<div class='close-userscript' onclick='saveBookmark()'>Add Bookmark</div></div>");

    $("bookmarkMenu").append('<div id="bookmarkMenu"></div>');

    $(".close-popup-img").on("click", function () {
        $(".popup").fadeOut();
        $(".overlay").fadeOut();
    });
    createSelector(".highlightedBookmark", "background-color:rgb(50, 50, 50);cursor:pointer;");
    $("body").append("<ul class='context-menu bookmark-context'><li onclick='editBookmark()'>Edit</li><li onclick='moveBookmarkUp()'>Move up</li><li onclick='moveBookmarkDown()'>Move Down</li></ul>")
    $("body").append("<ul class='context-menu thread-context'><li onclick='hideThread()'>Hide</li></ul>")
    $("body").append("<ul class='context-menu playersearch-context'><li onclick='findMostCommonGames()'>Most Common Games (Friends)</li></ul>")
    bindCustomContextMenu()

}

function setupBookmarkTable() {
    $(".SideColumn").prepend('<table class="dataTable" cellspacing="0" width="100%" id="BookmarkTable" style="text-align: left;"><thead><tr><td style="text-align: center">Bookmarks<img src="' + IMAGES.PLUS + '" width="15" height="15" onclick="showAddBookmark()"style="display:inline-block;float:right; opacity: 0.6; margin-right:15px; cursor: pointer"></td></tr></thead></table><br>');

    refreshBookmarks();
    bindBookmarkTable();
}

function refreshBookmarks() {
    Database.readAll(Database.Table.Bookmarks, function(bookmarks) {
        $("#BookmarkTable tbody tr").remove();
        bookmarks.sort(function(a, b) {return a.order - b.order})
        var data = "<tbody>";
        $.each(bookmarks, function (key, bookmark) {
            data += '<tr data-bookmarkId="' + bookmark.id + '" data-order="' + bookmark.order + '"><td><a ' + (bookmark.newWindow ? 'target="blank"' : "") + ' href="' + bookmark.url + '">' + bookmark.name + '</a>';
            data += '<a onclick="deleteBookmark(' + bookmark.id + ')" style="display:inline-block;float:right; opacity: 0.6;cursor: pointer;margin-right:5px">';
            data += '<img src="' + IMAGES.TRASH + '" width="15" height="15" ></a></td></tr>';
        })

        $("#BookmarkTable").prepend(data + '</tbody>');
        warlight_shared_viewmodels_WaitDialogVM.Stop()
        $(".loader").fadeOut("fast", function() {
            $(".loader").remove();
        })
    })
   

}

window.bookmarkOrder;
window.bookmarkId;
window.showAddBookmark = function () {
    showPopup("#bookmarkMenu")
    bookmarkId = undefined
    bookmarkOrder = undefined
}

window.editBookmark = function () {
    Database.read(Database.Table.Bookmarks, bookmarkId, function(bookmark) {
        $("#bookmarkURL").val(bookmark.url);
        $("#bookmarkName").val(bookmark.name);
        $("#bookmarkNewWindow").prop("checked", bookmark.newWindow);
        showPopup("#bookmarkMenu");
    })
   
}

window.moveBookmarkUp = function() {
    Database.readAll(Database.Table.Bookmarks, function(bookmarks) {
        var bookmark;
        var newIdx = -1
        $.each(bookmarks, function (key, bm) {
            if (bookmarkId == bm.id) {
                bookmark = bm
            }
        })
        bookmarks.sort(function(a,b){return a.order - b.order});
        var previousBookmark1 = bookmarks[bookmarks.indexOf(bookmark) - 1]
        var previousBookmark2 = bookmarks[bookmarks.indexOf(bookmark) - 2] || {order: 0}
        if(previousBookmark1) {
            bookmark.order = (previousBookmark1.order + previousBookmark2.order) / 2

            Database.update(Database.Table.Bookmarks, bookmark, bookmark.id, function() {
                $("#bookmarkURL").val('');
                $("#bookmarkName").val('');
                $("#bookmarkNewWindow").prop('checked', false);
                $(".overlay").fadeOut();
                refreshBookmarks();
            })
        } 
    })
}

window.moveBookmarkDown = function() {
        Database.readAll(Database.Table.Bookmarks, function(bookmarks) {
        var bookmark;
        var newIdx = -1
        $.each(bookmarks, function (key, bm) {
            if (bookmarkId == bm.id) {
                bookmark = bm
            }
        })
        bookmarks.sort(function(a,b){return a.order - b.order});
        var nextBookmark1 = bookmarks[bookmarks.indexOf(bookmark) + 1]
        var nextBookmark2 = bookmarks[bookmarks.indexOf(bookmark) + 2] || {order: 100000}
        if(nextBookmark1) {
            bookmark.order = (nextBookmark1.order + nextBookmark2.order) / 2
            Database.update(Database.Table.Bookmarks, bookmark, bookmark.id, function() {
                $("#bookmarkURL").val('');
                $("#bookmarkName").val('');
                $("#bookmarkNewWindow").prop('checked', false);
                $(".overlay").fadeOut();
                refreshBookmarks();
            })
        } 
    })
}


window.deleteBookmark = function (id) {
    Database.delete(Database.Table.Bookmarks, id, function() {
        refreshBookmarks();
    })
}

window.saveBookmark = function () {
    $("#bookmarkMenu").hide();
    var url = $("#bookmarkURL").val().trim();
    url = (url.lastIndexOf('http', 0) != 0) && (url.lastIndexOf('javascript', 0) != 0) ? "http://" + url : url;
    var name = $("#bookmarkName").val().trim();
    var newWindow = $("#bookmarkNewWindow").prop("checked");
    
    if(bookmarkId == undefined) {
        Database.readAll(Database.Table.Bookmarks, function(bookmarks) {
            bookmarks.sort(function(a, b) {return a.order - b.order})
            var bookmark = {
                name: name, 
                url: url, 
                newWindow: newWindow, 
                order: (bookmarks.length > 0) ? bookmarks[bookmarks.length - 1].order + 1 : 1
            }
            Database.add(Database.Table.Bookmarks, bookmark, function() {
                showBookmarkTable();
                refreshBookmarks();
            })         
        })
    } else {
       var bookmark = {
           name: name, 
           url: url, 
           newWindow: newWindow,
           order: bookmarkOrder
        }
        Database.update(Database.Table.Bookmarks, bookmark, bookmarkId, function() {
            showBookmarkTable();
            refreshBookmarks();
        })         
    }
        
    $("#bookmarkURL").val('');
    $("#bookmarkName").val('');
    $("#bookmarkNewWindow").prop('checked', false);
    $(".overlay").fadeOut();
}

function hideBookmarkTable() {
    $("#BookmarkTable").hide();
    if ($("#BookmarkTable").prev().hasClass("followWrap")) {
        $("#BookmarkTable").prev().hide();
    }
    if ($("#BookmarkTable").next().is('br')) {
        $("#BookmarkTable").next().hide();
    }
}

function showBookmarkTable() {
    $("#BookmarkTable").show();
    if ($("#BookmarkTable").prev().hasClass("followWrap")) {
        $("#BookmarkTable").prev().show();
    }
    if ($("#BookmarkTable").next().is('br')) {
        $("#BookmarkTable").next().show();
    }
}

window.bookmarkForumThread = function () {
    var title = $("title").text().replace(' - Play Risk Online Free - WarLight', '');
    var url = window.location.href;

    $("#bookmarkURL").val(url);
    $("#bookmarkName").val(title);
    showAddBookmark();

}
window.bookmarkTournament = function () {
    var title = $("#TournamentName").text().replace("Tournament: ", "").trim();
    var url = window.location.href;

    $("#bookmarkURL").val(url);
    $("#bookmarkName").val(title);
    showAddBookmark();

}

function addDefaultBookmark() {
    var bookmark = {
        name: "Muli's userscript (Tidy up Your Dashboard)",
        url: "https://www.warlight.net/Forum/106092-tidy-up-dashboard-2",
        newWindow: false,
        order: 0
    }
    Database.add(Database.Table.Bookmarks, bookmark, function() {
        showBookmarkTable();
        refreshBookmarks();
    })
}

function setupTournamentDecline() {
    $.each($(".TournamentRow"), function(key, val) {
        //Waiting for accept / decline
        if($(val).find("[style='color: red']:not(.BootTimeLabel)").length > 0) {
            $(val).find("td:last-of-type").append('<input type="button" class="DeclineBtn" style="width: 100px; height: 25px;float: right" value="Decline">')
        }
    })
    
    $(".DeclineBtn").on("click", function(e) {
        var id = $(e.target).closest(".TournamentRow").attr("data-tournamentid")
        warlight_shared_messages_Message.DeclineTournamentAsync(null,
            warlight_shared_viewmodels_SignIn.Auth, id, null,
            function (b, c) {
                warlight_shared_viewmodels_WaitDialogVM.Stop();
                if (null != c && 129 != c.ErrorType) {
                    if (135 == c.ErrorType)  {
                        warlight_shared_viewmodels_AlertVM.DoPopup("The tournament has been deleted");
                    } else {
                        throw c;
                    }
                }
                $(e.target).attr("disabled", true)
                $(e.target).attr("value", "Declined")
                $(e.target).closest(".TournamentRow").find("[style='color: red']:not(.BootTimeLabel)").remove()
            }
        )
    })
}

window.findMeIndex = -1;
window.findNextInTournament = function() {
    var boxes = getPlayerBoxes();
    var max = boxes.length - 1;
    findMeIndex = findMeIndex == max ? 0 : findMeIndex + 1;
    panzoomMatrix = undefined;
    findInTournament();
}

function setupPlayerDataTable() {
    var dataTable = $$$("#PlayersContainer > table").DataTable({
        "order": [],
        paging: false,
        sDom: 't',
        columnDefs: [ {
            targets: [ 0 ],
            orderData: [ 0, 3 ]
        },{
            targets: [ 1 ],
            orderData: [ 1, 0 ]
        },{
            targets: [ 2 ],
            orderData: [ 2, 1, 0 ],
            type: "rank"
        },{
            targets: [ 3 ],
            orderData: [ 3, 1, 0 ]
        },{
            targets: [ 4 ],
            orderData: [ 4, 1, 0 ]
        },{
            targets: [ 5 ],
            orderData: [ 5, 1, 0 ]
        } ], 
        "aoColumns": [
            { "orderSequence": [ "asc", "desc" ] },
            { "orderSequence": [ "asc", "desc" ] },
            { "orderSequence": [ "asc", "desc" ] },
            { "orderSequence": [ "desc", "asc" ] },
            { "orderSequence": [ "desc", "asc" ] },
            { "orderSequence": [ "desc", "asc" ] },
        ]
    });
    
    var styles = document.createElement("style");
    styles.type = "text/css";
    styles.innerHTML = getDataTableCSS();
    document.body.appendChild(styles);
}

function setupCommonGamesDataTable() {
    var $$$$$ = jQuery.noConflict(true);
    var dataTable = $$$("#MainSiteContent > table").DataTable({
        "order": [],
        paging: false,
        sDom: 't',
        columnDefs: [ {
            targets: [ 0 ],
            orderData: [ 0, 3 ]
        },{
            targets: [ 1 ],
            orderData: [ 1, 2, 3, 0 ]
        },{
            targets: [ 2 ],
            orderData: [ 2, 3, 0 ]
        },{
            targets: [ 3 ],
            orderData: [ 3, 2, 0 ]
        } ], 
        "aoColumns": [
            { "orderSequence": [ "asc", "desc" ] },
            { "orderSequence": [ "asc", "desc" ] },
            { "orderSequence": [ "asc", "desc" ] },
            { "orderSequence": [ "asc", "desc" ] },
        ]
    });
    
    var styles = document.createElement("style");
    styles.type = "text/css";
    styles.innerHTML = getDataTableCSS();
    document.body.appendChild(styles);
}

window.setCurrentplayer = function (player, noSearch) {
    window.currentPlayer = {
        id: player.id,
        name: player.name,
        fullID: player.fullID,
        team: player.team
    };
    $("#selectContainer").toggle(100);
    $("#activePlayer").html(htmlEscape(player.name == self.name ? "Me" : player.name));
    $("#playerSelectInput").val("");
    panzoomMatrix = undefined;
    findMeIndex = 0;
    $(".gold").removeClass("gold")
    $("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").addClass("gold")
    $("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "'] a").addClass("gold")
    
    
    if(window.WL_Tournament.Tourn.Type == 2 ) { //Robin Round
        $(".TeamTip_" + (window.currentPlayer.team == "" ? window.currentPlayer.id : window.currentPlayer.team.replace("Team ", "").charCodeAt(0)-65)).addClass("gold")
    } else { //Elimination Tournament
        getPlayerBoxes().find("a").addClass("gold")
    }
    if(noSearch != true) {
        window.findInTournament();
    }

}

function setupTournamentFindMe() {
    $("body").keyup(function (event) {
        // "Left" is pressed
        var boxes = getPlayerBoxes();
        var max = boxes.length - 1;
        if(event.which == 37) {
            findMeIndex = findMeIndex == 0 ? max : findMeIndex - 1;
            panzoomMatrix = undefined;
            findInTournament();
        } 
        // "Right" is pressed
        else if(event.which == 39) {
            findMeIndex = findMeIndex == max ? 0 : findMeIndex + 1;
            panzoomMatrix = undefined;
            findInTournament();
        }
        // "Home" is pressed
        else if(event.which == 36) {
            findMeIndex = 0;
            panzoomMatrix = undefined;
            findInTournament();
        }
        // "End" is pressed
        else if(event.which == 35) {
            findMeIndex = boxes.length - 1;
            panzoomMatrix = undefined;
            findInTournament();
        }
    });
    window.players = []
    $("[href='#SettingsTab']").parent().after('<li id="findMe" class="ui-state-default ui-corner-top"><div style="cursor: pointer" class="ui-tabs-anchor" onclick="window.findNextInTournament()">Find <label id="activePlayer"></labal></div><a id="showPlayerSelect">▼</a></li>');
    createSelector('#findMe:hover', 'border: 1px solid #59b4d4;background: #0078a3 url("https://d2wcw7vp66n8b3.cloudfront.net/jui4/images/ui-bg_glass_40_0078a3_1x400.png") 50% 50% repeat-x;font-weight: bold;color: #ffffff;border-bottom-width: 0')
    createSelector('#findMe', 'border: 1px solid #666666;border-bottom-width: 0')

    var css = '-webkit-keyframes pulsate{ 0% { background-color: rgba(0,0,0,0); } 50% { background-color: olive; } 100% { background-color: rgba(0,0,0,0); }}@keyframes pulsate { 0% { background-color: rgba(0,0,0,0); } 50% { background-color: olive; } 100% { background-color: rgba(0,0,0,0); }}.pulsate { -webkit-animation: pulsate 1s ease-in 1; -moz-animation: pulsate 1s ease-in 1; -ms-animation: pulsate 1s ease-in 1; -o-animation: pulsate 1s ease-in 1; animation: pulsate 1s ease-in 1;}-webkit-keyframes pulsate-border{ 0% { border: 3px solid #c4c2c4; } 25% { border: 3px solid red; } 50% { border: 3px solid red; } 100% { border: 3px solid #c4c2c4; }}@keyframes pulsate-border { 0% { border: 3px solid #c4c2c4; } 25% { border: 3px solid red; }50% { border: 3px solid red; } 100% { border: 3px solid #c4c2c4; }}.pulsate-border { -webkit-animation: pulsate-border 2s ease-in 1; -moz-animation: pulsate-border 2s ease-in 1; -ms-animation: pulsate-border 2s ease-in 1; -o-animation: pulsate-border 2s ease-in 1; animation: pulsate-border 2s ease-in 1;}'
    addCSS(css)
    


    $("#findMe").append('<div id="selectContainer"><div id="playerSelectInputContainer"><input placeholder="Search a Player" type="text" id="playerSelectInput"></input></div><div id="playerContainer"></div></div>');
        self = {
            id: warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID,
            name: warlight_shared_viewmodels_SignIn.get_CurrentPlayer().Name,
            fullID: String(warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ProfileToken).substring(0, 2) + warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID + String(warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ProfileToken).substring(2, 4),
            team: $("[data-playerid='" + warlight_shared_viewmodels_SignIn.get_CurrentPlayer().ID + "'] td:nth-of-type(2)").text()
        };
        window.setCurrentplayer(self, true);
        $.each($("#PlayingPlayers tr"), function (key, playerRow) {
            var id = $(playerRow).attr("data-playerid");
            var fullID = $(playerRow).find("a").get($(playerRow).find("a").length - 1).href.replace(/.*warlight.net\/Profile\?p=/, "");
            var name = $(playerRow).find("td a").text();
            var img = $(playerRow).find("td img").attr("src");
            var team = $("[data-playerid='" + id + "'] td:nth-of-type(2)").text();
            if (img && img.indexOf("MemberIcon") > -1) {
                img = "";
            }
            window.players.push({
                id: id,
                fullID: fullID,
                name: name,
                img: img,
                team: team
            });
        });

        $("#playerSelectInput").on('input', function (data) {
            $(".playerElement").remove();
            var search = $(this).val().toLowerCase();
            $("#playerContainer").append("<div class='playerElement' onclick='setCurrentplayer(self)'>" + self.name + " (Me)</div>")
            $.each(window.players, function (key, player) {
                if (player.name.toLowerCase().indexOf(search) > -1 && self.name != player.name) {
                    var img = player.img ? "<img src='" + player.img + "'>" : "";
                    $("#playerContainer").append("<div onclick='setCurrentplayer(players[" + key + "])' class='playerElement'>" + img + "<span>" + htmlEscape(player.name) + "</span>" + "</div>")
                }
            });

            $("#activePlayer").html(window.currentPlayer.name == self.name ? "Me" : window.currentPlayer.name);
            $("#playerContainer").scrollTop(0)

        });
        $("#playerSelectInput").trigger("input");

        $("#showPlayerSelect").on("click", function () {
            $("#selectContainer").toggle(100);
            $("#playerContainer").scrollTop(0);
            $("#playerSelectInput").trigger("input");
            $("#playerSelectInput").focus();
        });
    
    createSelector("#playerSelectInputContainer", "height: 28px; ");
    createSelector(".border-red", "border: 3px red solid !important; ");
    createSelector(".playerElement span, .playerElement img", "display:inline-block; margin-right: 10px");
    createSelector("#showPlayerSelect", "color: #DDDDDD;font-size: 14px;margin: 5px 5px 0 -3px;cursor: pointer; display: inline-block;margin-right: 10px;");
    createSelector("#playerSelectInput", "display: block;margin: 5px 3%;width: 93%;");
    createSelector("#activePlayer", "cursor:pointer");
    createSelector(".playerElement", "border-bottom: 1px gray solid;padding: 7px;color: white; clear:both; height: 14px; font-weight: normal;");
    createSelector(".playerElement:hover", "background: rgb(102, 102, 102);");
    createSelector("#playerContainer", "border: 2px gray solid; overflow-y: auto; overflow-x: hidden;max-height: 275px; min-width: 175px; ");
    createSelector(".gold", "color: gold")
    createSelector("#selectContainer", "cursor: pointer; background:rgb(23, 23, 23);position: fixed; z-index: 10;border: 2px gray solid;border-radius: 5px;box-shadow: 0 20px 50px 3px black;margin-top: 16px;display: none");
}


window.panzoomMatrix;
window.findInTournament = function () {
    var id;
    $("#selectContainer").hide(100);
    if ($("[href='#PlayersTab']").parent().hasClass("ui-state-active")) {
        id = window.currentPlayer.id;
        if ($("#PlayingPlayers [data-playerid='" + id + "']").length > 0) {
            var player = $("#PlayingPlayers [data-playerid='" + id + "']");
            var box = $("#CenterTabs").parent()
            var offset = player.offset().top - box.offset().top - box.height() / 2

            box.stop().animate({
                scrollTop: offset
            }, '500', 'swing');

            window.setTimeout(function () {
                $("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").addClass("pulsate");
                window.setTimeout(function () {
                    $(".pulsate").removeClass("pulsate");
                }, 1000);
            }, 250);
        } else {
            showInfo("You didn't join this tournament.", $("#findMe").offset().top + 25, $("#findMe").offset().left + 25);
        }

        // Elimination Tournament
    } else if ($("[href='#BracketTab']").parent().hasClass("ui-state-active") && window.WL_Tournament.Tourn.Type != 2) {
        id = window.currentPlayer.fullID;
        //Started
        if (window.WL_Tournament.Tourn.State >= 1 && $("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").length > 0) {

            if (!panzoomMatrix) {
                var currentMatrix = $("#Visualize").panzoom("getMatrix");
                $("#Visualize").panzoom("reset", {
                    animate: false
                });

                VisualizePanzoom.panzoom("zoom", {
                    increment: 0.75,
                    animate: false
                })
               
                var boxes = getPlayerBoxes();
                
                $(".TeamBoxHighlighted").removeClass("TeamBoxHighlighted");
                boxes.addClass("TeamBoxHighlighted");
                var offsetTop = $(boxes.get(findMeIndex)).offset().top - $("#VisualizeContainer").offset().top - $("#VisualizeContainer").height() / 4;
                var offsetLeft = $(boxes.get(findMeIndex)).offset().left - $("#VisualizeContainer").offset().left - $("#VisualizeContainer").width() / 2;

                $(".border-red").removeClass("border-red");
                $(boxes.get(findMeIndex)).addClass("border-red");
                
                $("#Visualize").panzoom("pan", 0 - offsetLeft, 100 - offsetTop, {
                    relative: true,
                    animate: false
                });

                panzoomMatrix = $("#Visualize").panzoom("getMatrix");
                $("#Visualize").panzoom("setMatrix", currentMatrix, {
                    animate: false
                });
            }

            window.setTimeout(function () {
                $("#Visualize").panzoom("setMatrix", panzoomMatrix, {
                    animate: true
                })
                window.setTimeout(function () {
                    //getPlayerBoxes().addClass("pulsate-border");
                    window.setTimeout(function() {
                         $(".pulsate-border").removeClass("pulsate-border");
                    }, 2000)
                }, 400);
            }, 10)

        } else {
            showFindMeError();
        }
        // Robin Round Tournament
    } else if ($("[href='#BracketTab']").parent().hasClass("ui-state-active") && window.WL_Tournament.Tourn.Type == 2) {
        
        //Started
        if ($("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").length > 0) {
            $(".TeamTip_" + (window.WL_Tournament.Tourn.TeamSize == 1 ? window.currentPlayer.id : window.currentPlayer.team.replace("Team ", "").charCodeAt(0)-65)).addClass("pulsate")
            window.setTimeout(function() {
                $(".pulsate").removeClass("pulsate")                    
            }, 2000)
        } else {
            showFindMeError()
        }
        
        
    }
}

function showFindMeError() {
    if ($("#PlayingPlayers [data-playerid='" + window.currentPlayer.id + "']").length == 0) {
        showInfo("You didn't join this tournament.", $("#findMe").offset().top + 25, $("#findMe").offset().left + 25);

    } else {
        showInfo("This tournament didn't start yet.", $("#findMe").offset().top + 25, $("#findMe").offset().left + 25);

    }
}

function getPlayerBoxes() {
    var boxes = $(".GameBox [href='/Profile?p=" + window.currentPlayer.fullID + "']").closest(".TeamBox");
    if(boxes.length == 0) {
        boxes = $("[title='" + window.currentPlayer.team + "']").closest(".TeamBox");
    }
    
    return boxes;
    
}

function htmlEscape(str) {
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

function bindBookmarkTable() {
    $("#BookmarkTable").bind("contextmenu", function (event) {
        $(".highlightedBookmark").removeClass("highlightedBookmark")
        var row = $(event.target).closest("tr");
        
        
        bookmarkId = row.attr("data-bookmarkid")
        bookmarkOrder = row.attr("data-order")
        
        if(bookmarkId && bookmarkOrder) {
            event.preventDefault();
            row.addClass("highlightedBookmark")
            // Show contextmenu
            $(".bookmark-context").finish().toggle(100).
            css({
                top: event.pageY + "px",
                left: event.pageX + "px"
            });
        }
        
    });
}



function bindCustomContextMenu() {
    // If the document is clicked somewhere
    $(document).bind("mousedown", function (e) {

        // If the clicked element is not the menu
        if (!$(e.target).parents(".context-menu").length > 0) {

            // Hide it
            $(".context-menu").hide(100);
            $(".highlightedBookmark").removeClass("highlightedBookmark")
        }
    });


    // If the menu element is clicked
    $(".context-menu li").click(function(){

        // This is the triggered action name
        switch($(this).attr("data-action")) {

            // A case for each action. Your actions here
            case "first": alert("first"); break;
            case "second": alert("second"); break;
            case "third": alert("third"); break;
        }

        // Hide it AFTER the action was triggered
        $(".context-menu").hide(100);
    });

}



function setupRealTimeLadderTable() {
    if($("#RealTimeLadderTable").length == 0) {
        return;
    }
    
    if( $(".extendedRTLadderRow").length == 0) {
        createSelector(".extendedRTLadderRow .rtBox", "width: calc(100%/2);");
        createSelector(".extendedRTLadderRow span", "");
        createSelector(".rtLeft", "float:left");
        createSelector(".rtRight", "float:Right");
        createSelector(".rtRight a", "    padding: 10px 30px;position: absolute;margin-left: -75px;");
        createSelector(".newGamesRT", "display:block");
        createSelector(".rtLabelBig", "font-size: 18px; margin: 5px"); 
    }
    $(".extendedRTLadderRow").remove()
    $("#RealTimeLadderTable tbody").append('<tr class="extendedRTLadderRow"><td colspan="2"><div class="rtLeft rtBox"><span class="newGamesRT">New Games in<br></span><div class="rtLabelBig">' + getRealTimeLadderTimerHTML() + '<a href="https://www.warlight.net/LadderJoin?Ladder=RealTime" class="rtLabelBig">Join!</a></div></td></tr>')
    $("[href='/LadderSeason?ID=3']").text("Ladder Page")
    setRTLadderTime() 
}

function setupRealTimeLadderPageTimer() {
    $("#LadderJoinBtn").after("<div>New Games in " + getRealTimeLadderTimerHTML() +"</div>")
    $("#LeaveLadderBtn").after("<div>New Games in " + getRealTimeLadderTimerHTML() +"</div>")
    setRTLadderTime()
}

function getRealTimeLadderTimerHTML() {
    return '<span class="rtMin">00</span>:<span class="rtSec">00</span></div></div><div class="rtRight rtBox">'
}


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 setupClotTable() {
    if($("#ClotTable").length == 0) {
        $(".SideColumn").append('<table class="dataTable" cellspacing="0" width="100%" id="ClotTable" style="text-align: left"><thead><tr><td style="text-align: center">CLOTs</td></tr></thead><tbody></tbody></table>')
    }
    parseClotTable() 
    loadClots()
    createSelector(".clotLabel", "display: inline-block; width: 70px")
    createSelector(".clotPlayers", "display: inline-block; margin-left: 5px; color:gray; ")
    
}

function setupLadderClotOverview() {
    $("h1").text($("h1").text() + " & CLOTs")
    var clotInfo = getClots()
    if(!clotInfo) {
        return
    }
    var clots = clotInfo
   
    var ladders = clots['ladders'] 
    var md = ""
    var rt = ""
    var counter = 0
    $.each(ladders, function (key, val) {
        if (val.type == "realtime") {
            rt += "<li><big><a target='_blank' href=" + val.url + ">" + val.name + "</a> using Real-Time boot times</big></li><br><br>"
            counter++
        } else if (val.type == "multiday") {
            md += "<li><big><a target='_blank' href = " + val.url + ">" + val.name + "</a> using Multi-Day boot times</big></li><br><br>"
            counter++
        }
    })
    
    $("#MainSiteContent > div").append("Warlight currently has " + toWords(counter) + " <a href='https://www.warlight.net/wiki/CLOT'>CLOTs</a><br><br>")
    
    $("#MainSiteContent > div").append("<ul id='clotInfo'></ul>")
    $("#clotInfo").append(rt)
    $("#clotInfo").append(md)
}

function parseClotTable() {        
    try {
        var clotInfo = getClots()
        if(!clotInfo) {
            return
        }
        var ladders = clots['ladders']
        var md = ""
        var rt = ""
        $.each(ladders, function (key, val) {
            if (val.type == "realtime") {
                rt += "<tr><td><a target='_blank' href=" + val.url + ">" + val.name + " (RT)</a> <span class='clotPlayers'>" + val.players + " Players joined</span></td></tr>"
            } else if (val.type == "multiday") {
                md += "<tr><td><a target='_blank' href = " + val.url + ">" + val.name + " (MD)</a><span class='clotPlayers'>" + val.players + " Players joined</span></td></tr>"
            }
        })
        $("#ClotTable tbody tr").remove()
        $("#ClotTable tbody").append(md)
        $("#ClotTable tbody").append(rt)
        $(window).trigger('resize');
    } catch (e) {
        console.log("Error reading CLOTs")
        console.log(e.message)
        hideTable("#ClotTable")
    }
}
function getClots() {
    try {
        return clots = $.parseJSON(sessionStorage.getItem('clots'))
    } catch (e) {
        console.log("Error reading CLOTs")
        console.log(e.message)
        hideTable("#ClotTable")
    }        
    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));
            parseClotTable()
            var datetime = json.datetime
            console.log("clot update " + datetime)
             
        } catch (e) {
            console.log("Error parsing CLOTs")
            console.log(e)
        }
    }).fail(function(e){
        console.log("Error loading CLOTs")
        console.log(e);
    });
}


                      
function isJson(str) {
    try {
        JSON.parse(str);
    } catch (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
    setupClotTable()
    
    //RT Ladder
    setupRealTimeLadderTable()
    
    //Map of the Week
    
    //Forum Posts
//     hideBlacklistedThreads()
    
    //Blog Posts
    
    //Coin Leaderboard
    
    sortRightColumnTables()
    
    if(isInit) {
        ifSettingIsEnabled('scrollGames', function() {
            setupFixedTitlesInSideColumn();
        })
    }
}

function sortRightColumnTables() {
    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()
    })
    
}

function toWords(num) {
    if(num == 1) {
        return "one"
    } else if(num == 2) {
        return "two"
    } else if(num == 3) {
        return "three"
    } else if(num == 4) {
        return "four"
    } else if(num == 5) {
        return "five"
    } else if(num == 6) {
        return "six"
    } else if(num == 7) {
        return "seven"
    } else if(num == 8) {
        return "eight"
    } else if(num == 9) {
        return "nine"
    } else if(num == 10) {
        return "ten"
    } else if(num == 0) {
        return "zero"
    }  
}

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 setupPlayerSearch() {
      $("body").append("<div class='popup popup600 playersearch-show' style='display: none'><div class='head'>Search Player <img class='close-popup-img' src='" + IMAGES.CROSS + "' height='25' width='25'></div><input placeholder='Player Name' id='playerSearchQuery'><button id='searchPlayerBtn'>Search</button><div class='playerSearchTypeSelect'><label for='playerSearchFriend'>Friends</label><input type='radio' id='playerSearchFriend' name='playerSearchType' value='playerSearchFriend' checked><label for='playerSearchGlobal'>All Players</label><input type='radio' id='playerSearchGlobal' name='playerSearchType' value='playerSearchGlobal'></div><button id='findPlayerExtra'>More ▼</button><div id='foundPlayers'></div></div>");
    $("#SubTabRow").append('<td nowrap="nowrap" id="searchPlayerLink" data-subtabcell="Search Player" class="SubTabCell"><a>Search Player</a></td>');
    
    $("#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", "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("#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")
    
}

function searchPlayer() {    
    $("#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("<span>This query found more than 25 results. Only the first 25 results are shown below.</span>")
            }
            parseFoundGlobalPlayers(players)
            $("#playerSearchQuery").focus()
            $("#playerSearchQuery").select()  
        })
    }   
}

function parseFoundFriendPlayers(players) {
    if(!players || players.length == 0) {
        $("#foundPlayers").append("<span>No Players found.</span>");
        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 = '<a href="/Profile?p=' + id + '">' + player.Name + '</a>'
        var clan = player.ClanOpt != null ? '<a href="https://www.warlight.net/Clans/?ID=' + player.ClanOpt.ClanID + '"><img class="playerSearchClan" src="https://d32kaghj56y4ei.cloudfront.net/Data/Clans/' + player.ClanOpt.ClanID + '/Icon/' + player.ClanOpt.IconIncre + '.png"></a>' : "";
        var member = player.IsMember ? '<img class="playerSearchMember" src="https://d2wcw7vp66n8b3.cloudfront.net/Images/MemberIcon.png">' : "";
        var description = '<div class="playerSearchName">' + nameLink + member + "<span>(Level " + player.Level + ", " + player.TimesPlayedWithYou + " common games)</span></div>";
        $("#foundPlayers").append('<div class="foundPlayer">' + clan + description + '</div>')
    }
}

function parseFoundGlobalPlayers(players) {
    if(!players || players.length == 0) {
        $("#foundPlayers").append("<span>No Players found.</span>");
        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 = '<a href="/Profile?p=' + id + '">' + player.Name + '</a>'
        var clan = player.ClanOpt != null ? '<a href="https://www.warlight.net/Clans/?ID=' + player.ClanOpt.ClanID + '"><img class="playerSearchClan" src="https://d32kaghj56y4ei.cloudfront.net/Data/Clans/' + player.ClanOpt.ClanID + '/Icon/' + player.ClanOpt.IconIncre + '.png"></a>' : "";
        var member = player.IsMember ? '<img class="playerSearchMember" src="https://d2wcw7vp66n8b3.cloudfront.net/Images/MemberIcon.png">' : "";
        var name = '<div class="playerSearchName">' + nameLink + "<span>(" + player.Level + ")</span></div>";
        $("#foundPlayers").append('<div class="foundPlayer">' + clan + name + member + '</div>');
    }
}

window.setTimeout(validateUser, 2000);
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) {
                    console.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('<tr><td></td><td><input id="mapSearchQuery" placeholder="Map Name"><br><button id="mapSearchBtn">Search</button><button style="margin: 4px" id="mapSearchResetBtn">Reset</button></td></tr>')
    
    $('#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) {
        $("<div />").load('Ajax/EnumerateMaps?Filter=' + 1 + '&Sort=' + 1 + "&PerPage=" + 2147483647 + "&Offset=" + 0, function(data) {
            mapData = data;
            filterMaps(this);
        })
    } else {
        var maps = $("<div />").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 <i>" + query +"</i>") : $("#ReceivePager").after("<h2 id='searchResultsTitle'>Searchresults for <i>" + query +"</i></h2>")
    
}


/**************************************

    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() {
        console.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() {
            console.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)]); 
    }
    console.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('<div id="ManagerLeaguePrice" style="width:500px; height:200px;"></div>')
             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])
			  } 
			  console.log(points)
			  var plot1 = $.jqplot('ManagerLeaguePrice', [points], {  
				  series:[{color: '#5FAB78'}],
                  title: 'Manager League Price',
				  axes:{
					xaxis:{
						label:'Time',
						min: 0,
						ticks: ticksx,
                        tickOptions:{
                            formatString:'Week %s'
                        } 
					},
					yaxis:{
						label:'Price',
						min: 0,
						max: Math.ceil(max/25)*25,
                        numberTicks: max / 25 + 1,
                        tickOptions:{
                            formatString:'%d $'
                        } 
					},
					axesDefaults: {
					  labelRenderer: $.jqplot.CanvasAxisLabelRenderer
					},
                    grid: {
                        backgroundColor: '#DEA493'
                    },
				  }
			  });
             
        } catch (e) {
            console.log("Error parsing Manager League")
            console.log(e)
        }
    }).fail(function(e){
        console.log("Error loading Manager League")
        console.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")
                $(event.target).closest("tr").addClass("highlightedBookmark")
                // Avoid the real one
                event.preventDefault();
                threadId = $(event.target).closest("tr").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 setupSpammersBeGone() {
    var path = window.location.pathname;
    if(pageIsForumThread()) {
        // TODO : Ignore posts from blacklisted players
    }

    if(pageIsForumOverview()) {
        // Do nothing
    }

    if(pageIsForumOverview()) {
        newColumnCountOnPage = 5;
        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 = "<th> Ignore</th>";
    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');
            $(this).append("<td> <input type='checkbox' name='"+ postId +"' class='checkbox' value='Yes'/> </td>");
        }
    }); 
}

/**
 * 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();
                 }
            })
        }
    })
    
    
}


/**************************************

    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() {
    /// <summary>
    /// Add a text box(for sample game Id) and a button to create randomized 
    /// game.
    /// </summary>
    /// <param name="levelElement" type="Element">
    /// The parent element if text box and button.
    /// </param>

    $("#FeedbackMsg").after("<div class='randomGameContainer profileBox'><h3>Randomized Bonuses Game</h3></div>")
    var br = document.createElement('br');
    
    $(".randomGameContainer").append('<label for="gameName">Game Name:</label><input id="gameName" type="text" placeholder="Game Name" value="Game - Randomized Bonuses"><br>')
        
    $(".randomGameContainer").append('<label for="gameId">Game ID:</label><input id="gameId" type="text" placeholder="Game ID" value="">')
    
    $(".randomGameContainer").append('<button id="createGame">Create Game</button>')
    $("#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('<button id="bookmarkRandomBonus"><img src="' + IMAGES.BOOKMARK + '"></button>')
    $("#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", "<img src='" + IMAGES.SAVE + "'>");
    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() {
    /// <summary>
    /// Gets the sample game Id and checks if it is a number.
    /// </summary>
    /// <returns type="number">Game Id.</returns>
    var gameIdElement = document.getElementById("gameId");
    if (gameIdElement !== undefined) {
        return parseInt(gameIdElement.value, 10);
    }
}

function extractGameSettings(gameId) {
    /// <summary>
    /// Extract game settings from the sample game using GameFeed API.
    /// </summary>

    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) {
    /// <summary>
    /// From the GameFeed API response, randomize bonuses and create a game 
    /// using the template.
    /// </summary>
    /// <param name="response" type="string">
    /// The GameFeed API response for the provided sample game.
    /// </param>

    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];
                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) {
    /// <summary>
    /// Create a game on Warlight between the two players on given settings.
    /// </summary>
    /// <param name="templateId" type="number">
    /// The game template Id.
    /// </param>
    /// <param name="bonuses" type="array">
    /// All bonuses on the map and the range of values they can take.
    /// </param>

    var template = templateId;
    var postDataObject = {
        "gameName": 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) {
    /// <summary>
    /// Pick a random number in the interval (min, max)
    /// </summary>
    /// <param name="min" type="number">
    /// lower bound of number
    /// </param>
    /// <param name="max" type="number">
    /// upper bound of number
    /// </param>
    /// <returns type="number">
    /// Random number in the interval
    /// </returns>

    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function doAsyncRequest(method, url, data, api) {
    /// <summary>
    /// Perform an asynchronous request to create a game on Warlight.
    /// </summary>
    /// <param name="method" type="string">
    /// GET/POST
    /// </param>
    /// <param name="url" type="string">
    /// The request url.
    /// </param>
    /// <param name="data" type="dictionary">
    /// Request parameters
    /// </param>
    /// <param name="api" type="string">
    /// Warlight api type
    /// </param>
    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\"")
                    } 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 = $('<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() {

    })
}



/**************************************

    Textarea HTML Box

**************************************/


function setupTextarea() {
    var controls_default = [
        {title: "<b>B</b>", class: ["tag"], openClose: true,    tag: "b"},
        {title: "<i>I</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 += `<span class="button ${control.class.join(" ")}" ${(control.openClose ? `open-close` : ``)} data-tag="${control.tag}">${control.title}</span>`
    })                           
    $(".region textarea").before(`<div class="editor">${controls}</div>`)
    $("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: 4;-o-tab-size: 4;tab-size: 4;")

    $(".editor .tag").on("click", 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)
            console.log(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() {
    window.Database = {
        db: null,
        Table: {
            Bookmarks: "Bookmarks",
            Settings: "Settings",
            BlacklistedForumThreads: "BlacklistedForumThreads"
        },
        Row: {
            BlacklistedForumThreads: {
                ThreadId: "threadId",
                Date: "date"
            },
            Bookmarks: {
                Order: "order"
            },
            Settings: {
                Name: "name"
            }
        },
        init: function(callback) {
           if(!"indexedDB" in window) {
                console.log("no IndexedDB found")
                return;
            }
            var openRequest = indexedDB.open("TidyUpYourDashboard_v3", 1);
            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});
                }

            }

            openRequest.onsuccess = function(e) {
                console.log("indexedDB init sucessful");
                db = e.target.result;
                callback()
            }

            openRequest.onerror = function(e) {
                console.log("Error Init IndexedDB")
                console.log(e.target.error)
//                alert("Sorry, Tidy Up Your Dashboard is not supported")
                $("<div>Sorry,<br> Tidy Up Your Dashboard is not supported.</div>").dialog();
            }
        },
        update: function(table, value, key, callback) {
            var transaction = db.transaction([table],"readwrite");
            var store = transaction.objectStore(table);


            //Perform the add
            var request = store.put(value, key != undefined ? Number(key) : undefined);

            request.onerror = function(e) {
                console.log("Error saving in ", table)
                console.log(e.target.error);
                //some type of error handler
            }

            request.onsuccess = function(e) {
                console.log("Saved in ", table)
                callback()
            }
        },
        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) {
            console.log("adding to db")
            var transaction = db.transaction([table],"readwrite");
            var store = transaction.objectStore(table);


            //Perform the add
            var request = store.add(value);

            request.onerror = function(e) {
                console.log("Error saving in ", table)
                console.log(e.target.error);
                //some type of error handler
            }

            request.onsuccess = function(e) {
                console.log("Saved 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) {
                console.log("Error deleting in ", table)
                console.log(e.target.error);
                //some type of error handler
            }

            request.onsuccess = function(e) {
                console.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) {
                console.log("Error clearing ", table)
                console.log(e.target.error);
                //some type of error handler
            }

            request.onsuccess = function(e) {
                console.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()) {
        $("body").append('<div class="versionLabel">' + GM_info.script.version +'</div>')
        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 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}'
}

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',
        TRASH: 'https://i.imgur.com/KrTbICA.png',
        SAVE: 'https://i.imgur.com/Ze4h3NQ.png',
        BOOKMARK: 'https://i.imgur.com/c6IxAql.png'

    }
}