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.

As of 2017-04-01. See the latest version.

// ==UserScript==
// @name        Jz Warlight
// @namespace   https://greasyfork.org/en/users/44200-jz
// @version     1.2.7
// @grant       none
// @match https://www.warlight.net/*
// @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.
// @require https://greasyfork.org/scripts/28001-jz-warlight-library/code/Jz%20Warlight%20Library.js
// ==/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">Super-awesome filter of weirdness!</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();   
            }
        }
        if(pageIsForum()) {
            // The following code was taken from Master of the Dead's blacklist script and modified to allow me to personally troll him
            var troll_setting = localStorage.getItem('setting_troll_motd');
            var forumPosts = $("#MainSiteContent").find("table:first").find("table");
            forumPosts.find("tr").each(function(i, post){
                var tdCell = $(post).find("td:first");
                var poster_cell = getPosterAnchor(tdCell);
                var poster_id = getPosterId(poster_cell);
                if(troll_setting == 'true' && poster_id == '2428496679') {
                    changeAvatar(tdCell, "http://icons.iconarchive.com/icons/giannis-zographos/english-football-club/256/Liverpool-FC-icon.png");
                }
                if(troll_setting == 'true' && (poster_id == '1552135718' || poster_id == '397429597')) {
                    changeAvatar(tdCell, "https://lh3.googleusercontent.com/-iDzlv7IG4rY/AAAAAAAAAAI/AAAAAAACsik/FnDXDKxLt5I/s0-c-k-no-ns/photo.jpg");
                }

                if(troll_setting == 'true') {
                    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 = "";
							if(level.length == 1) {
								newlevel = level + "0";
							} else {
								newlevel = level.substring(1) + level.substring(0,1);
							}
                        	tdCell.html(tdCell.html().replace('Level ' + level, 'Level ' + newlevel));
						}
                    }
				}
                
                // 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');
        if(extra_features == 'true' && testDate()) {
            console.log(new Date());
        }
    } 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 setupSettings() {
    // Menu item is a modification from Muli's userscript: https://greasyfork.org/en/scripts/8936-tidy-up-your-dashboard
    $("#TopRightDropDown .dropdown-divider").before('<li><div class="jz-userscript-menu">Jz\'s Userscript</div></li>');
    addStyle(".jz-userscript-menu", "display: block;color: #555;text-decoration: none;line-height: 18px;padding: 3px 15px;margin: 0;white-space: nowrap;");
    addStyle(".jz-userscript-menu:hover", "cursor:pointer;background-color: #08C;color: #FFF;cursor: pointer;");
    
    var settings_dialog = $('<div id="settingsdialog" title="Settings (Automatically Saved)"></div>');
    addSetting(settings_dialog, "Enable Special Features", "setting_extra_features", "false", "Enable the secret easter egg features");
    addSetting(settings_dialog, "Allow Audio Features", "setting_audio_features", "false", "Enable the secret easter egg features");
    addSetting(settings_dialog, "Enable Note Taking", "setting_enable_notes", "true", "Allow note taking in games");
    addSetting(settings_dialog, "Add extra filters", "setting_extra_filters", "true", "Add extra filters to the dashboard and past tournaments pages");
    addSetting(settings_dialog, "Add features to enhance Muli's userscript", "setting_enhance_muli", "true", "If muli's script is installed, add features to enhance it.");
    addSetting(settings_dialog, "Master of the Dead deserves to be trolled", "setting_troll_motd", "true", "He insulted my trollhood, and so he deserves to be trolled.");
    //addStyle(".jz-userscript-menu img", "height: 18px;display: inline-block;position: relative;margin-bottom: -5px;margin-right: 7px;");
    
    $(".jz-userscript-menu").on("click", function () {
        settings_dialog.dialog();
    });
}

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_header);
    settings_dialog.append(setting);
    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 {
            if(id == 'setting_troll_motd') {
            	alert('Fool, change your settings, Master of the Dead DOES need to be trolled.');
            }
            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() {
    // Add the notes header
    var notesHeader = $('<td data-subtabcell="Notes" class="SubTabCell" nowrap="nowrap"><a style="cursor:pointer">Notes</a></td>');
    $("#SubTabRow").append(notesHeader);

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

    // Create the popup for the notes
    var gameNotes = $('<textarea id="GameNotes" rows="4" cols="30"/>');
    var notesdialog = $('<div id="notesdialog" title="Notes"></div>');
    // Set the position of the dialog and then close it
    notesdialog.append(gameNotes);
    var position = { my: "left top", at: "right bottom", of: window};
    notesdialog.dialog({
        position: position
    });
    notesdialog.dialog('close');

    // Create the events
    // Save the note automatically
    gameNotes.on('change', function() {
        saveNote(gameNotes, gameid, notesHeader);
    });
    // Open the notes dialog when the Notes header is clicked
    notesHeader.on('click', function() {
        openCloseNotesDialog(notesdialog);
    });

    // 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);
        notesdialog.dialog();

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

function openCloseNotesDialog(notesdialog) {
    if(notesdialog.dialog('isOpen') == true) {
        notesdialog.dialog('close');
    } else {
        notesdialog.dialog();
    }
}

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, notesHeader) {
    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, notesHeader);
}

function colorNotesHeader(gameNotes, notesHeader) {
    var color = "";
    if(gameNotes.val() != null && gameNotes.val().length > 0) {
        color = '#FFAA00';
    }
    notesHeader.find('a').first().css('color',color);
    
}

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

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


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

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

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

function testDate() {
    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');
        }
        //return true;
    } 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/L16toHuQFc4?autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1");
                player2.width = 5;
                player2.height = 5;
                document.body.appendChild(player2);
                return true;
            }
        }
        //return true;
    } 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);
        }
        //return true;
    } else if(profid == '9911415828') {
        if(day == 2) {
            changeProfile('Master Sephiroth', 'L1', '180479');
        }
        //return true;
    } else if(profid == '4439722815') {
        //return true;
    }
    
    if(date.getMilliseconds() == 0) {
        $("#MailImgNormal").hide();
        $("#MailImgFlashing").show();
        //$("#MailLink").attr("href", "https://www.youtube.com/watch?v=xDwlUZLTRbs");
        $("#MailLink").attr("href", "https://www.warlight.net/Forum/154263-troll-awards-war-begins");

		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/fQVANVSZ2T8?autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1");
	        player2.width = 5;
	        player2.height = 5;
	        document.body.appendChild(player2);
        }

        return true;
    }
    return false;
}

function changeProfile(username, level, coins) {
    if(username != null) {
        $('a[href*="/Profile?p="]').first().html(username);
    }
    if(level != null) {
       $('#LevelLink').html(level);
    }
    if(coins != null) {
       var coinsobj = $('#CoinsText');
       //coins.html(coins.html() * 100);
       coinsobj.html(coins);
    }
}

function changeAvatar(tdCell, src) {
    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" />');
    }
}