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.

目前为 2017-11-14 提交的版本。查看 最新版本

// ==UserScript==
// @name        Jz Warlight
// @namespace   https://greasyfork.org/en/users/44200-jz
// @version     1.3.1
// @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('https://d2wcw7vp66n8b3.cloudfront.net/Images/Coins/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 today = new Date();
		var april_fools = today.getDate() == 1 && today.getMonth() == 3;
        if(april_fools) {
            aprilFools();
        }
        
        var troll_setting = localStorage.getItem('setting_troll_players');
        if(april_fools || troll_setting == 'true') {
            playerTrolls();
        }
        
        var extra_features = localStorage.getItem('setting_extra_features');
        if((april_fools || extra_features == 'true')) {
            extraFeatures();
        }
    } 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 features");
    addSetting(settings_body, "Allow Audio Features (fun feature)", "setting_audio_features", "false", "Enable the secret easter egg features that use audio");
    addSetting(settings_body, "Player Trolls (fun feature)", "setting_troll_players", "false", "Enable features that troll certain players (including yourself, if relevant).");
}

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();
        firstpost.html(anslatetray(postcontent))
        
        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));
                    }
                }
            }
        };
        
        //MOTD
        changeAvatar('2428496679', "http://icons.iconarchive.com/icons/giannis-zographos/english-football-club/256/Liverpool-FC-icon.png");
        
        // Styx
        changeAvatar('1552135718', "https://lh3.googleusercontent.com/-iDzlv7IG4rY/AAAAAAAAAAI/AAAAAAACsik/FnDXDKxLt5I/s0-c-k-no-ns/photo.jpg");
    }
    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;
    }
}

// Change avatars and give profile theme songs
function playerTrolls() {
	var today = new Date();
    if(pageIsForum()) {
        if(today.getMonth() == 6 && today.getFullYear() == 2017) {
            // MOTD
            changeAvatar('2428496679', "https://hdlogo.files.wordpress.com/2011/11/real-salt-lake-city-hd-logo.png");
            // Styx
            changeAvatar('1552135718', "https://hdlogo.files.wordpress.com/2011/11/real-salt-lake-city-hd-logo.png");
        }
        
        // Nero
        changeAvatar('397429597', "https://lh3.googleusercontent.com/-iDzlv7IG4rY/AAAAAAAAAAI/AAAAAAACsik/FnDXDKxLt5I/s0-c-k-no-ns/photo.jpg");
    }
	var audio_features = localStorage.getItem('setting_audio_features');
    // Platinum
    if(location.href.match(/.*warzone[.]com\/Profile\?p=6559504553/i)
          || location.href.match(/.*warzone[.]com\/Profile\?p=5550827655/i)) { 
        addThemeSongToProfile(audio_features, "8Gv0H-vPoDc");
    }
    //After Dark
    replaceClanIcon("155", "http://static.skaip.org/img/emoticons/180x180/f6fcff/poop.gif", 18, 18);
}

// Other extra features, such as changed titles.
function extraFeatures() {
	var audio_features = localStorage.getItem('setting_audio_features');
    try{
        var hiddenThreads = $('tr#HiddenThreadsRow').first().find("font:first");
        if(hiddenThreads!= null && hiddenThreads.text().match(/[54]\d hidden threads/i) != null) {
            lotsOfHiddenThreads(hiddenThreads);
        }
    } catch (e) {
        alert(e);
    }
    
    var profilelink = $('a[href*="/Profile?p="]').first();
    var linkhref = profilelink.attr("href");
    var profid = linkhref.substring(linkhref.indexOf("=")+1);
    var date = new Date();
    var day = date.getDay();
    
    if(date.getHours() >= 0 && date.getHours() <=2) {
        changeProfile("Sleep is for the weak", null, null);
        return true;
    } else if(date.getHours() > 2 && date.getHours() <= 5) {
        changeProfile("Seriously, why are you awake at this hour?", null, null);
        return true;
    }

    if(profid == '2214950915') {
        if(day = 2) {
            changeProfile('Master of Disaster', null, '0');
        } else if(day == 3) {
            changeProfile('Elitist', 'L99', '999999');
        }
    } else if(profid == '6319040229') {
        if(day == 2) {
            changeProfile('Jefferspoon', null, '-35');
        }
        if((day == 6)) {
            if(date.getMilliseconds() < 50) {
                var player2 = document.createElement("iframe");
                player2.setAttribute("src", "https://www.youtube.com/embed/jsduOOI_EGE?autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1");
                player2.width = 5;
                player2.height = 5;
                document.body.appendChild(player2);
            }
        }
    } else if(profid == '2428496679') {
        if(day == 2) {
            changeProfile('Miles Edgeworth', 'L59', null);
        } else if(day == 3) {
            changeProfile('Mercer', 'L31', null);
        } else if(day == 1) {
            changeProfile(null, 'L61', null);
        }
    } else if(profid == '9911415828') {
        if(day == 2) {
            changeProfile('Master Sephiroth', 'L1', '180479');
        }
    }
    return false;

}

function changeProfile(username, level, coins) {
    if(username != null) {
        $('#AccountDropDown').first().html(username);
    }
    if(level != null) {
       $('#LevelLink i').html(level);
    }
    if(coins != null) {
       var coinsobj = $('#CoinsText');
       //coins.html(coins.html() * 100);
       coinsobj.html(coins);
    }
}

function changeAvatar(player, src) {
    var selector = 'a[href*="/Profile?p=' + player + '"]';
    var player_as = $(selector);
    for(var i = 0; i < player_as.length; i++) {
        var link = $(player_as[i]);
        var tdCell = link.parent();
        if(tdCell.is('TD')) {
            var image1 = $(tdCell).find("img:first");
            if(image1 != null && image1.attr('src').indexOf('https://s3.amazonaws.com/data.warlight.net/Data/Players') == 0) {
                image1.attr('src', src);
            } else {
                tdCell.prepend('<br/><img src="' + src + '" border="0" width="50" height="50" />');
            }
        }
    }
}

function replaceClanIcon(clanId, url, width, height) {
    var selector = 'a[href*="/Clans/?ID=' + clanId + '"]';
    var icon_as = $(selector);
    for(var i = 0; i < icon_as.length; i++) {
        var icon_a = $(icon_as[i]);
        var img = icon_a.find("img")[0];
        img.src = url;
        img.width = width;
        img.height = height;
    }
}

function lotsOfHiddenThreads(hiddenThreads) {
    var hiddenrow = $('tr#HiddenThreadsRow').first();
    var audio_features = localStorage.getItem('setting_audio_features');
    if(audio_features == 'true') {
        var player2 = document.createElement("iframe");
        player2.setAttribute("src", "https://www.youtube.com/embed/zq7Eki5EZ8o?autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1");
        player2.width = 60;
        player2.height = 40;
        hiddenThreads.append(player2);
    } else {
        var player2 = document.createElement("div");
        $(player2).html("<a href=\"https://www.youtube.com/watch?v=zq7Eki5EZ8o\">Can't nothin bring me shame</a>");
        hiddenThreads.append(player2);
    }
}

function addThemeSongToProfile(audio_features, youtube_link) {
    if(audio_features == 'true') {
        var player2 = document.createElement("iframe");
        player2.setAttribute("src", "https://www.youtube.com/embed/" + youtube_link + "?autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1");
        player2.width = 5;
        player2.height = 5;
        document.body.append(player2);
    }
    var theme = document.createElement("small");
    $(theme).html("<br/><span>Theme Song: </span><a href=\"https://www.youtube.com/watch?v=" + youtube_link + "\">https://www.youtube.com/watch?v=" + youtube_link + "</a><span></span>");
    $("big").append(theme);
}

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