Jz Warlight

Adds extra filters for tournaments and dashboard games, including a fun filter that brings up a strange mix of games. Allows note-taking in games. A couple of easter eggs are also included.

目前为 2021-04-03 提交的版本,查看 最新版本

// ==UserScript==
// @name        Jz Warlight
// @namespace   https://greasyfork.org/en/users/44200-jz
// @version     1.3.3
// @grant       none
// @match https://www.warlight.net/*
// @match https://www.warzone.com/*
// @description Adds extra filters for tournaments and dashboard games, including a fun filter that brings up a strange mix of games. Allows note-taking in games. A couple of easter eggs are also included.
// ==/UserScript==

main();
function main() {
    try{
        setupSettings();

        var filter_setting = localStorage.getItem('setting_extra_filters');
        if(pageIsDashboard()) {
            if(filter_setting == 'true') {
                //$("#MyGamesFilter").append('<option value="0">Games that are active</option>');
                $("#MyGamesFilter").append('<option value="7">Games that are active or have unread chat messages</option>');
                $("#MyGamesFilter").append('<option value="3">Weird Filter (Non-Archived Games)</option>');
            }
        }
        if(pageIsTournaments()) {
            var muli_setting = localStorage.getItem('setting_enhance_muli');
            if(muli_setting == 'true') {
                // Add filters for tournaments, to expand the functionality Muli provided
                var filter = $('<select id="tournamentFilter" title="After updating the tournament data using Muli\'s script, pick a filter." style="float: right;margin: 0 10px;"/>');
                filter.append($('<option value="showAll">Show all</option>'));
                filter.append($('<option value="showGamesLeft">Tournaments with games left</option>'));
                filter.append($('<option value="showInProgress">Tournaments with games in progress</option>'));
                filter.append($('<option value="showNotEliminated">Tournaments that I am not eliminated from</option>'));
                filter.append($('<option value="showAlmostDone">Tournaments that are almost done</option>'));
                filter.append($('<option value="showCoin">Coin Tournaments</option>'));
                filter.on("change", function () {
                    var selected = $( this ).val();

                    var tds = $("td .tournamentData");
                    for(var i = 0; i < tds.length; i++) {
                        var td = tds[i];
                        var parentTr = $(td).parent('tr');
                        if(selected == "showAll") {
                            parentTr.show();
                        } else if(selected == "showGamesLeft") {
                            if(td.innerHTML.indexOf('<font color="#858585">Games left:</font> None  <br>') > 0) {
                                parentTr.hide();
                            } else {
                                parentTr.show();
                            }
                        } else if(selected == "showInProgress") {
                            if(td.innerHTML.indexOf('<font color="#858585">Playing:</font> 0  <br>') > 0) {
                                parentTr.hide();
                            } else if(td.innerHTML.indexOf('<font color="#858585">Playing:</font>') > 0) {
                                parentTr.show();
                            } else {
                                parentTr.hide();
                            }
                        } else if(selected == "showNotEliminated") {
                            // Show round robins, tournaments with games in progress, and tournaments with games left
                            if(parentTr.html().indexOf('Round robin tournament') >= 0) {
                                parentTr.show();
                            } else if(td.innerHTML.indexOf('<font color="#858585">Playing:</font>') > 0
                                      && td.innerHTML.indexOf('<font color="#858585">Playing:</font> 0  <br>') == -1) {
                                parentTr.show();
                            } else if(td.innerHTML.indexOf('<font color="#858585">Games left:</font> None  <br>') == -1) {
                                parentTr.show();
                            } else {
                                parentTr.hide();
                            }
                        }  else if(selected == "showAlmostDone") {
                            if(td.innerHTML.indexOf('Almost done') > 0) {
                                parentTr.show();
                            } else {
                                parentTr.hide();
                            }
                        } else if(selected == "showCoin") {
                            if(parentTr.html().indexOf('SmallCoins.png') != -1) {
                                parentTr.show();
                            } else {
                                parentTr.hide();
                            }
                        }
                    }
                });
                $("#MyTournamentsTable h2").after(filter);
            }
        }
        if(pageIsPastTournaments()) {
            if(filter_setting == 'true') {
                //$("#Filter").append('<option value="4">Actionable</option>');
                $("#Filter").append('<option value="5">Tournaments with unread chat</option>');
                //$("#Filter").append('<option value="6">Actionable or unread chat</option>');
                //$("#Filter").append('<option value="8">Not Complete that I joined</option>');
            }
        }
        if(pageIsGame()) {
           var note_setting = localStorage.getItem('setting_enable_notes');
            if(note_setting == 'true') {
               setupNotes();
            }
        }
		// Reimplement Alt tagging
                    /*// Tag alts (alts retrieved from the library)
                    for(var main_count = 0; main_count < mains.length; main_count++) {
                        var main = mains[main_count];
                        for(var alt_count = 0; alt_count < main.alts.length; alt_count++) {
                            var alt = main.alts[alt_count];
                            if(poster_id == alt) {
                                var username = poster_cell.html();
                                poster_cell.html(username + " (" + main.name + ")");
                            }
                        }
                    }*/

        var extra_features = localStorage.getItem('setting_extra_features');
		var today = new Date();
		var april_fools = today.getDate() == 1 && today.getMonth() == 3;
        if((april_fools && extra_features == 'true')) {
            aprilFools();
        }
    } catch(err) {
        console.log(err);
    }
}

function getPosterAnchor(tdCell) {
    var posterCell = tdCell.find('a[href*="/Profile?p="]').first();
    return posterCell;
}

function getPosterId(posterCell) {
    if(posterCell !== undefined && posterCell != null){
        var postAuthor = posterCell.attr("href");
        if(postAuthor != null && postAuthor.length > 11) {
            return postAuthor.substring(11);
        }
    }
    return null;
}

function flipLevel(level) {
	if(level.length == 1) {
		return level + "0";
	} else {
		return level.substring(1) + level.substring(0,1);
	}
}

function setupSettings() {
    $("#AccountDropDown").parent().find("div .dropdown-divider").before('<div class="dropdown-item" id="jz-userscript-menu" style="cursor:pointer" data-toggle="modal" data-target="#settingsdialog">Jz\'s Userscript</div>');

    var modalhtml = ''
    modalhtml += '<div class="modal" tabindex="-1" role="dialog" id="settingsdialog">'
    modalhtml += '  <div class="modal-dialog" role="document">'
    modalhtml += '    <div class="modal-content">'
    modalhtml += '      <div class="modal-header" style="color:#b3b081;background-color:#330000;height:40px">'
    modalhtml += '        <h5 class="modal-title">Settings (Automatically Saved)</h5>'
    modalhtml += '        <button type="button" class="close" data-dismiss="modal" aria-label="Close">'
    modalhtml += '          <span aria-hidden="true" style="color:#b3b081">&times;</span>'
    modalhtml += '        </button>'
    modalhtml += '      </div>'
    modalhtml += '      <div class="modal-body" id="settingsbody" style="color:#b3b081;background-color:#171717">'
    modalhtml += '      </div>'
    modalhtml += '    </div>'
    modalhtml += '  </div>'
    modalhtml += '</div>'
    var settings_modal=$(modalhtml)
    $('body').append(settings_modal)

    var settings_body = $("#settingsbody")
    addSetting(settings_body, "Enable Note Taking", "setting_enable_notes", "true", "Allow note taking in games");
    addSetting(settings_body, "Add extra filters", "setting_extra_filters", "true", "Add extra filters to the dashboard and past tournaments pages");
    addSetting(settings_body, "Add features to enhance Muli's userscript", "setting_enhance_muli", "true", "If muli's script is installed, add features to enhance it.");
    addSetting(settings_body, "Enable Special Features (fun feature)", "setting_extra_features", "false", "Enable the secret easter egg/april fools features");
    addSetting(settings_body, "Allow Audio Features (fun feature)", "setting_audio_features", "false", "Enable the secret easter egg features that use audio");
}

function addSetting(settings_dialog, label, id, default_val, title) {

    var setting_header = $('<label for="setting_' + id + '" title="' + title + '">' + label + '</label>');
    var setting = $('<input type="checkbox" id="setting_' + id + '"/>');
    settings_dialog.append(setting);
    settings_dialog.append(setting_header);
    settings_dialog.append($('<br/>'));
    var stored_value = localStorage.getItem(id);
    if(stored_value == null) {
        stored_value = default_val;
        localStorage.setItem(id, default_val);
    }
    if(stored_value == 'true') {
        setting.prop('checked', true);
    }
    setting.on('change', function() {
        if(setting.prop('checked')) {
            localStorage.setItem(id, 'true');
        } else {
            localStorage.setItem(id, 'false');
        }
    });
}

/**
 * Create a CSS selector
 * Taken from Muli's Userscript and renamed from createSelector (to avoid conflict): https://greasyfork.org/en/scripts/8936-tidy-up-your-dashboard
 * @param name The name of the object, which the rules are applied to
 * @param rules The CSS rules
 */
function addStyle(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);
    }
}

function setupNotes() {
    // Create the minimized notes
    var modalhtml = ''
    modalhtml += '<div class="panel" tabindex="-1" id="notesdialogmini">'
    modalhtml += '  <div class="modal-dialog" role="document" style="border: 2px solid;border-radius: 5px;max-width:100px;position:fixed;bottom:0px;right:0px;margin:0px;padding:0px">'
    modalhtml += '    <div class="modal-content" style="color:#b3b081">'
    modalhtml += '      <div class="modal-header" id="notesheadermini" style="border:0px;color:#b3b081;background-color:#330000;padding:5px;height:15px">'
    modalhtml += '        <span aria-hidden="true" id="notesopen" style="cursor:pointer;font-size:x-small">Notes</span>'
    modalhtml += '      </div>'
    modalhtml += '    </div>'
    modalhtml += '  </div>'
    modalhtml += '</div>'
    var notes_modal2=$(modalhtml)
    $('body').append(notes_modal2)

    // Create the popup for the notes
    var modalhtml = ''
    modalhtml += '<div class="panel" tabindex="-1" id="notesdialog">'
    modalhtml += '  <div class="modal-dialog" role="document" style="max-width:340px;position:fixed;bottom:0px;right:0px;margin:0px">'
    modalhtml += '    <div class="modal-content">'
    modalhtml += '      <div class="modal-header" id="notesheader" style="color:#b3b081;background-color:#330000;height:35px">'
    modalhtml += '        <h5 class="modal-title">Notes</h5>'
    modalhtml += '        <button type="button" class="close" id="notesminimize" aria-label="Minimize">'
    modalhtml += '          <span aria-hidden="true" style="color:#b3b081">-</span>'
    modalhtml += '        </button>'
    modalhtml += '      </div>'
    modalhtml += '      <div class="modal-body" id="notesbody" style="color:#b3b081;background-color:#171717">'
    modalhtml += '          <textarea id="GameNotes" rows="4" cols="30"/>'
    modalhtml += '      </div>'
    modalhtml += '    </div>'
    modalhtml += '  </div>'
    modalhtml += '</div>'
    var notes_modal=$(modalhtml)
    notes_modal.hide();
    $('body').append(notes_modal)

    // Add the notes header to the Multi-Player Menu
    var notesHeader = $('<div class="dropdown-item" id="NotesHeader" style="cursor:pointer">Notes</div>');
    $("#CreateGameLink").after(notesHeader);

    // Setup note display events
    notesHeader.on('click', function() {
        notes_modal.show();
        notes_modal2.hide();
    });

    var notes_minimize=$("#notesminimize")
    notes_minimize.on('click', function() {
        notes_modal.hide();
        notes_modal2.show();
    });

    var notes_open=$("#notesopen")
    notes_open.on('click', function() {
        notes_modal.show();
        notes_modal2.hide();
    });

    // Parse the gameid
    var gameid = getGameID();

    // Create the events
    // Save the note automatically
    var gameNotes = $("#GameNotes")
    gameNotes.on('change', function() {
        saveNote(gameNotes, gameid);
    });

    // Populate the notes field and set the background color for the notes
    var notes = getNotesFromStorage();
    var note = notes[gameid];
    if(note != null && note.value != null && note.value.length > 0) {
        gameNotes.val(note.value);
        notes_modal.show();

        // Resaving it updates the timestamp
        saveNote(gameNotes, gameid);
    }
    colorNotesHeader(gameNotes);
}

function getGameID() {
    var gameid = location.href.substring(location.href.indexOf('GameID=') + 7)
    if(gameid.indexOf('&') > 0) {
        gameid = gameid.substring(0, gameid.indexOf('&'));
    }
    return gameid;
}

function getNotesFromStorage() {
    var notesString = localStorage.getItem("notes");
    if(notesString != null) {
        return JSON.parse(notesString);
    } else {
        return {};
    }
}

function saveNotesToStorage(notes) {
    localStorage.setItem("notes", JSON.stringify(notes));
}

function saveNote(gameNotes, gameid) {
    var notes = getNotesFromStorage();
    var note = notes[gameid];
    if(note == null) {
        note = {};
    }
    note.date = new Date();
    note.value = gameNotes.val();
    notes[gameid] = note;
    if(note.value == null || note.value.length == 0) {
        delete notes[gameid];
    }
    //alert(JSON.stringify(notes));
    saveNotesToStorage(notes);
    colorNotesHeader(gameNotes);
}

function colorNotesHeader(gameNotes) {
    var notesHeader = $("#NotesHeader")
    var miniNotesHeader = $("#notesheadermini")
    miniNotesHeader.css('font-style','normal');
    var color = "";
    if(gameNotes.val() != null && gameNotes.val().length > 0) {
        color = '#FFAA00';
        miniNotesHeader.css('font-style','italic');
    }
    notesHeader.css('color',color);
}

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

function pageIsTournaments() {
    return location.href.match(/.*warzone[.]com\/MultiPlayer\/Tournaments\/$/i);
}

function pageIsPastTournaments() {
    return location.href.match(/.*warzone[.]com\/MultiPlayer\/Tournaments\/Past/i);
}

function pageIsGame() {
    return location.href.match(/.*warzone[.]com\/MultiPlayer\?GameID=/i);
}

function pageIsForum() {
    return location.href.match(/.*warzone[.]com\/Forum/i);
}

// "Troll" content below
function aprilFools() {
    var level = $('#LevelLink i').html().substring(1);
    var newlevel = flipLevel(level)
    if(level != null) {
        $('#LevelLink i').html("L" + newlevel);
    }
    var headers = $("#navbarSupportedContent ul li");
    if(headers) {
        headers.each(function(i, header) {
            var anchor = $(header).find("a").first();
            anchor.text(anslatetray(anchor.text()));
        });
    }
    if(pageIsForum()) {
        var firstpost = $($("#PostTbl_0").find("td")[1]).find("div");
        var postcontent = firstpost.html();
        var translation = anslatetray(postcontent);

        firstpost.html("<div id='piglatin_text'>" + translation + "</div>");
        firstpost.append($("<div id='english_text' style='display:none'>" + postcontent + "</div>"));
        firstpost.append("<br/>");

        var untranslate = $("<div id='english_button' class='btn btn-primary' style='float:right'>Translate to English</div>");
        firstpost.append(untranslate);
        untranslate.on("click", function () {
            $('#piglatin_text').hide();
            $('#english_text').show();
            $('#piglatin_button').show();
            $('#english_button').hide();
        });

        var piglatin = $("<div id='piglatin_button' class='btn btn-primary' style='float:right;display:none'>Back to Pig Latin</div>");
        firstpost.append(piglatin);
        piglatin.on("click", function () {
            $('#piglatin_text').show();
            $('#english_text').hide();
            $('#piglatin_button').hide();
            $('#english_button').show();
        });

        var forumPosts = $("[id^=PostTbl]");
        for(var i = 0; i < forumPosts.length; i++) {
            var post = forumPosts[i];
            var tds = $(post).find("td");
            var tdCell = $(post).find("td:first");
            var poster_cell = getPosterAnchor(tdCell);
            var poster_id = getPosterId(poster_cell);
            if(poster_id != null) {
                if(tdCell.html() != null && poster_id != null) {
                    var levelstart = tdCell.html().indexOf('Level');
                    if(levelstart > 0) {
                        var level = tdCell.html().substring(levelstart+6, levelstart + 8).trim();
                        var newlevel = flipLevel(level);
                        tdCell.html(tdCell.html().replace('Level ' + level, 'Level ' + newlevel));
                    }
                }
            }
        };
    }
    var date = new Date();
    if(date.getMilliseconds() <= 50) {
        $("#MailImgNormal").hide();
        $("#MailImgFlashing").show();
        $("#MailLink").attr("href", "https://www.warlight.net/Forum/154263-troll-awards-war-begins");
        return true;
    }
}

function anslatetray(post) {
    var new_post = "";
    var suffix = "";
    var suffix_end = false;
    var chars = post.split('');
    var open_br = false;
    var capital = false;
    for(var i = 0; i < chars.length; i++) {
        var character = chars[i];
        if(character == ">") {
            open_br = false;
            new_post += character;
        } else if(character == "<") {
            open_br = true;
            if(suffix != "") {
                new_post += suffix + "ay";
                suffix = "";
                suffix_end = false;
            }
            new_post += character;
        } else if(open_br) {
            new_post += character;
        } else if(character.match(/[a-zA-Z]/g) == null) {
            if(suffix != "") {
                new_post += suffix + "ay";
                suffix = "";
            }
            suffix_end = false;
            new_post += character;
        } else if(suffix_end) {
            new_post += character;
        } else if(character.match(/[aeiouAEIOU]/g) != null) {
            suffix_end = true;
            if(capital) {
                new_post += character.toUpperCase();
            } else {
                new_post += character;
            }
            if(suffix == '') {
                suffix += 'w'
            }
        } else {
            if(suffix == "") {
                if(character.match(/[A-Z]/g) != null) {
                    capital = true;
                    suffix += character.toLowerCase();
                } else {
                    capital = false;
                    suffix += character;
                }
            } else {
                suffix += character;
            }
        }
    }
    if(suffix != "") {
        new_post += suffix + "ay";
        suffix = "";
    }
    return new_post;
}