// ==UserScript==
    // @name Everfree Outpost Chat Extensions
    // @description Adds extra chat functionalities to Everfree Outpost.
    // @author "Thorn Rose", "Green", "Script Anon", "haypone"
    // @version 0.5.2
    // @namespace everfree-outpost
    // @match *://play.everfree-outpost.com/*
    // @grant GM_addStyle
    // @connect play.everfree-outpost.com
    // @run-at document-start
    // @require https://gist.github.com/raw/2625891/waitForKeyElements.js
    // ==/UserScript==

    var my_name="haypone"; //Your name on EO so it won't notify your own messages, it can be changed.
    //var audio = new Audio("https://notificationsounds.com/storage/sounds/file-sounds-1127-beyond-doubt.mp3"); //The sound it will play, it can be changed
    //-----------------------------

    var GREEN="#306030";
    var PURPLE="#8844CC";
    var BLUE="#303090";
    var LIGHTBLUE="#306090";
    var RED="#903030";
    var DARKCYAN="#2D5B60";
    var userMap = { //Change these to actual names and other colors
    "True Lime": GREEN,
    "Derpy": "#71797E",
    "C": "#0047AB",
    "Stubenhocker": "#f36044",
    "Z": "#903060",
    "E": PURPLE,
    "F": PURPLE,
    "G": "#686772",
    "H": "#96663B",
    "I": "#606090",
    "J": "#609030",
    "K": DARKCYAN,
    "L": RED,
    "M": "#FFE085",
    "N": "#FDBFFF",
    "O": RED,
    "P": BLUE,
    "Q": LIGHTBLUE
    };

    let lastLine = '';

    var unreadMessages = 0;
    var original_title = document.title; //Do not change
    var blink_interval;
    var is_blinking=false; //Do not change
    addEventListener("mousemove", stop_blinking);

    const config = { attributes: false, childList: true, subtree: false };
    // Callback function to execute when mutations are observed
    const callback = (mutationList, observer) => {
        for (const mutation of mutationList) {
            if (mutation.type === "childList") {
                newChatLine();
            }
        }};
    // Create an observer instance linked to the callback function
    const observer = new MutationObserver(callback);

    let chat;
    //UI is created after the site is loaded, so we need to wait for it to exist
    function init() {
        let chats = document.getElementsByClassName("chat");
        if(chats.length >= 2) {
            chat = chats[1];
            unreadMessages = 0;
            const chatMessages = document.getElementsByClassName("chat-line");
            for(let i = 1; i < chatMessages.length; i++) {
                unreadMessages++;
                modifyChatLine(chatMessages[i]);
            }
            observer.observe(chat, config);
            clearInterval(initTimer);
        }
    }
    const initTimer = setInterval(init, 150);

    window.onfocus = function() {
        unreadMessages = 0;
        stop_blinking();
    }

    function stop_blinking(_) {
        document.title = original_title;
        clearInterval(blink_interval)
        is_blinking = false;
    }

    function blink_title(message) {
        if (document.title===message) {
            document.title=original_title;
        } else {
            document.title=message;
        }
    }

    function formatDate(date) {
        var hours = date.getHours();
        var minutes = date.getMinutes();
        minutes = minutes < 10 ? '0'+minutes : minutes;
        var strTime = hours + ':' + minutes;
        return strTime;
    }

    function urlify(text) {
        var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
        return text.replace(urlRegex, function(url,b,c) {
            var url2 = (c == 'www.') ? 'http://' +url : url;
            return '<a href="' +url2+ '" target="_blank">' + url + '</a>';
        })
    }

    function modifyChatLine(lastChatMessage) {
        const wasScrolled = Math.abs(chat.scrollHeight - chat.scrollTop - chat.clientHeight) <= 5; //how many pixels
        const user = lastChatMessage.children[0];
        const text = lastChatMessage.children[1];
        //lastLine = text;

        const userInnerText = user.innerText;
        if(userInnerText.length == 0) return;
        const username = userInnerText.substr(1, userInnerText.length - 2);

        if(userInnerText[0] == '[') return;
        user.innerText = `[${formatDate(new Date)}] ${userInnerText}`;

        text.innerHTML = urlify(text.innerHTML);
        if (my_name !== username && username !== "*") {
            unreadMessages += 1;
            //audio.play();
            if (!is_blinking && !document.hasFocus()) { //Title blinks only if it is not currently blinking or if the user is not on EO tab
                blink_interval = setInterval(function(){blink_title(`${unreadMessages} New message!`);},1000)
                is_blinking=true
            }
        }

        /*if (username in userMap) {
            user.css("color", userMap[username]);
            user.css("font-weight", "bold");
            user.css("text-shadow", "0px 0px 6px #fff");
        }*/

        if(wasScrolled) chat.scrollTop = chat.scrollHeight - chat.clientHeight;
    }

    function newChatLine () {
        stop_blinking();
        const chatMessages = document.getElementsByClassName("chat-line");
        const lastChatMessage = chatMessages[chatMessages.length-1];
        modifyChatLine(lastChatMessage);
    }