Max's Updated Egg Navigator with more pages (250!), auto switch and egg detection

Full credit to the original author Heasley. The original script can be found here: https://greasyfork.org/en/scripts/463484-heasley-s-egg-navigator

目前為 2025-04-18 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Max's Updated Egg Navigator with more pages (250!), auto switch and egg detection
// @namespace    egg.traverse
// @version      1.5
// @description  Full credit to the original author Heasley. The original script can be found here: https://greasyfork.org/en/scripts/463484-heasley-s-egg-navigator
// @author       Max
// @match        https://www.torn.com/*
// @grant        GM.addStyle
// @grant        GM.registerMenuCommand
// @run-at       document-start
// @license      MIT
// @require      https://www.torn.com/js/script/lib/jquery-1.8.2.js
// ==/UserScript==

// IMPORTANT - The auto-switch feature may potentially violate Torn's scripting policy. Proceed with caution and use at your own risk!
// This script has been tested on desktop browsers only.
// The auto-switch functionality is located at the bottom of the sidebar.
// A button labelled "Run" or "Stop" controls the auto-navigation feature.
// To customize the starting page index for navigation, update the numerical value in the input field next to the button.
// When the input value is changed, the script will immediately update the navigation index and begin switching pages from the specified point.

'use strict';
var ButtonFloat = parseInt(localStorage.getItem('eeh-float')) || 0;
var ButtonFloatPos = parseInt(localStorage.getItem('eeh-float-pos')) || 0; //0 - bottom ; 1 - top
var linkIndex = localStorage.getItem('eeh-index') || 0;
var pressTimer;

// Add global variables for the enhancements
let pagesTraversed = 0; // Tracks the number of pages visited in a session
const maxPages = Math.floor(Math.random() * (30 - 20 + 1)) + 20; // Random page stop range: 20–30 pages
let autoSwitchInterval;

// Detect device type (desktop or mobile)
function isMobile() {
    return /Android|iPhone|iPad|iPod|Windows Phone/i.test(navigator.userAgent);
}

// Simulate interactions based on device type
function simulateInteraction() {
    if (isMobile()) {
        const navigatorButton = document.getElementById("eggTraverse");
        if (navigatorButton) {
            const touchStartEvent = new TouchEvent("touchstart", { bubbles: true });
            const touchEndEvent = new TouchEvent("touchend", { bubbles: true });
            navigatorButton.dispatchEvent(touchStartEvent);
            navigatorButton.dispatchEvent(touchEndEvent);
            console.log("[Max's Egg Navigator] Simulated touch events for mobile.");
        }
    } else {
        const randomX = Math.floor(Math.random() * window.innerWidth);
        const randomY = Math.floor(Math.random() * window.innerHeight);
        const mouseMoveEvent = new MouseEvent("mousemove", {
            bubbles: true,
            clientX: randomX,
            clientY: randomY,
        });
        document.dispatchEvent(mouseMoveEvent);
        console.log(`[Max's Egg Navigator] Simulated mouse movement to (${randomX}, ${randomY}) for desktop.`);
    }
}

window.addEventListener('load', () => {
    const egg = document.getElementById('easter-egg-hunt-root');
    if (egg) {
        if (egg.classList.contains('egg-finder-found')) {
            return; // If the egg was already detected, do nothing
        }

        // Mark the egg as found
        egg.classList.add('egg-finder-found');
        alert('Egg found!');

        // Function to move the egg visually
        function moveEgg() {
            const buttons = egg.querySelectorAll('button');
            if (buttons.length === 0) {
                setTimeout(moveEgg, 50); // Retry after 50ms if no buttons found
                return;
            }

            buttons.forEach(b => {
                b.style.top = '40%';
                b.style.left = '40%';
                b.style.height = '20%';
                b.style.width = '20%';
                b.style.position = 'fixed';
                b.style.border = '5px solid red';

                const children = b.children;

                children[0].style.height = '100%';

                const particles = children[children.length - 1];
                particles.style.left = '0';
                particles.style.width = '100%';
                particles.style.height = '100%';
            });
        }

        moveEgg();

        // Stop auto-switching if it is running
        if (isRunning) {
            clearTimeout(autoSwitchInterval); // Stop any pending navigation
            isRunning = false; // Update the state
            localStorage.setItem("eeh-isRunning", isRunning); // Persist stop state
            document.getElementById("runStopButton").textContent = "Run"; // Update button text
            console.log("[Max's Egg Navigator] Auto-switching halted due to egg detection.");
        }
    }
});



if (typeof GM == 'undefined') {
    window.GM = {};
}

if (typeof GM.addStyle == "undefined") { //Add GM.addStyle for browsers that do not support it (e.g. TornPDA, Firefox+Greasemonkey)
    GM.addStyle = function (aCss) {
        'use strict';
        let head = document.getElementsByTagName('head')[0];
        if (head) {
            let style = document.createElement('style');
            style.setAttribute('type', 'text/css');
            style.textContent = aCss;
            head.appendChild(style);
            return style;
        }
        return null;
    };
}

if (typeof GM.registerMenuCommand != "undefined") {
    GM.registerMenuCommand('Toggle Floating Button', toggleFloatButton,
                           {
        autoClose: false
    }
    );

    GM.registerMenuCommand('Toggle Float Position', toggleFloatPosition,
                           {
        autoClose: false
    }
    );
}

const easteregg_svg = `
<svg xmlns="http://www.w3.org/2000/svg" fill="url(#egg-gradient)" stroke="transparent" stroke-width="0" width="15" height="20" viewBox="0 0 15 20">
    <defs>
        <linearGradient id="egg-gradient" gradientTransform="rotate(90)">
            <stop offset="0%" stop-color="#FFD700" /> <!-- Gold at the top -->
            <stop offset="100%" stop-color="#FF4500" /> <!-- Orange at the bottom -->
        </linearGradient>
        <filter id="egg-shadow" x="0" y="0" width="200%" height="200%">
            <feDropShadow dx="0" dy="2" stdDeviation="3" flood-color="rgba(0, 0, 0, 0.25)" />
        </filter>
    </defs>
    <path style="filter: url(#egg-shadow);" d="M1.68,16a5.6,5.6,0,0,0,.43.41A5.72,5.72,0,0,0,3,17a4.73,4.73,0,0,0,.74.39,5.08,5.08,0,0,0,.8.3,5.35,5.35,0,0,0,.69.17,8.62,8.62,0,0,0,.87.11h.84a8.46,8.46,0,0,0,.88-.11l.69-.17a7.14,7.14,0,0,0,.81-.31q.38-.18.72-.39a6.57,6.57,0,0,0,.9-.67,5.14,5.14,0,0,0,.41-.4A6.3,6.3,0,0,0,13,11.67a8.86,8.86,0,0,0-.09-1.21c0-.31-.1-.64-.17-1s-.2-.85-.33-1.29-.3-.93-.48-1.39-.33-.81-.51-1.2c-.1-.2-.19-.39-.29-.58L11,4.72c-.18-.33-.4-.69-.64-1s-.4-.55-.62-.82A4.41,4.41,0,0,0,6.5,1,4.41,4.41,0,0,0,3.29,2.86a9.15,9.15,0,0,0-.61.82c-.24.34-.44.68-.62,1L1.87,5l-.33.66c-.16.36-.32.72-.46,1.09S.74,7.7.61,8.16a13.14,13.14,0,0,0-.34,1.3,10,10,0,0,0-.18,1A8.47,8.47,0,0,0,0,11.67a6.29,6.29,0,0,0,.89,3.25A6.63,6.63,0,0,0,1.68,16Z">
    </path>
</svg>`;
const EVERY_LINK = [
  // Personal Pages
  "",
  "/index.php",
  "/personalstats.php?ID=1",
  "/preferences.php",
  "/page.php?sid=gallery&XID=1",
  "/page.php?sid=log",
  "/page.php?sid=ammo",
  "/playerreport.php",
  "/page.php?sid=UserList",
  "/page.php?sid=keepsakes",
  "/authenticate.php",
  "/page.php?sid=list&type=friends",
  "/page.php?sid=list&type=enemies",
  "/page.php?sid=list&type=targets",
  "/page.php?sid=events",
  "/page.php?sid=events#onlySaved=true",
  "/events.php#/step=all",
  "/messageinc.php",
  "/messageinc2.php#!p=main",
  "/messageinc2.php#!p=viewall",
  "/messages.php",
  "/messages.php#/p=inbox",
  "/messages.php#/p=compose",
  "/messages.php#/p=outbox",
  "/messages.php#/p=saved",
  "/messages.php#/p=ignorelist",
  "/awards.php",
  "/points.php",
  "/fans.php",
  "/bounties.php",
  "/usersonline.php",
  "/bringafriend.php",
  "/page.php?sid=bunker",
  "/index.php?page=rehab",
  "/index.php?page=people",

  // Item Pages
  "/item.php",
  "/amarket.php",
  "/bigalgunshop.php",
  "/shops.php?step=bitsnbobs",
  "/shops.php?step=cyberforce",
  "/shops.php?step=docks",
  "/shops.php?step=jewelry",
  "/shops.php?step=nikeh",
  "/shops.php?step=pawnshop",
  "/shops.php?step=pharmacy",
  "/pmarket.php",
  "/shops.php?step=postoffice",
  "/shops.php?step=super",
  "/shops.php?step=candy",
  "/shops.php?step=clothes",
  "/shops.php?step=recyclingcenter",
  "/shops.php?step=printstore",
  "/imarket.php",
  "/bazaar.php?userId=1",
  "/bazaar.php#/",
  "/bazaar.php#/add",
  "/bazaar.php#/personalize",
  "/displaycase.php",
  "/displaycase.php#display/",
  "/pc.php",
  "/trade.php",
  "/loader.php?sid=itemsMods",
  "/page.php?sid=ItemMarket",

  // Side Bar Pages
  "/city.php",
  "/jobs.php",
  "/companies.php",
  "/gym.php",
  "/properties.php",
  "/page.php?sid=education",
  "/education.php#/step=main",
  "/crimes.php",
  "/crimes.php#/step=main",
  "/page.php?sid=crimes2", // Moved here
  "/loader.php?sid=crimes#/searchforcash",
  "/loader.php?sid=crimes#/bootlegging",
  "/loader.php?sid=crimes#/graffiti",
  "/loader.php?sid=crimes#/shoplifting",
  "/loader.php?sid=crimes#/pickpocketing",
  "/loader.php?sid=crimes#/cardskimming",
  "/loader.php?sid=crimes#/burglary",
  "/loader.php?sid=crimes#/hustling",
  "/loader.php?sid=crimes#/disposal",
  "/loader.php?sid=crimes#/cracking",
  "/loader.php?sid=crimes#/forgery",
  "/loader.php?sid=crimes#/scamming",
  "/loader.php?sid=missions",
  "/newspaper.php#/",
  "/joblist.php#!p=main",
  "/freebies.php#!p=main",
  "/newspaper_class.php",
  "/personals.php#!p=main",
  "/bounties.php#!p=main",
  "/comics.php#!p=main",
  "/newspaper.php#/archive",
  "/messageinc2.php#!p=viewall",
  "/newspaper.php#/tell_your_story",
  "/archives.php#/TheBirthOfTorn",
  "/jailview.php",
  "/halloffame.php",
  "/hospitalview.php",
  "/page.php?sid=UserList",
  "/calendar.php",
  "/bringafriend.php",
  "/page.php?sid=hof",
  "/page.php?sid=travel",

  // City
  "/bank.php",
  "/donator.php",
  "/dump.php",
  "/loan.php",
  "/estateagents.php",
  "/forums.php",
  "/properties.php?step=rentalmarket",
  "/properties.php?step=sellingmarket",
  "/page.php?sid=ItemMarket#/market/view=category&categoryName=Most%20Popular",
  "/museum.php",
  "/church.php",
  "/church.php?step=proposals",
  "/citystats.php",
  "/committee.php",
  "/page.php?sid=stocks",
  "/archives.php#/",
  "/committee.php#/step=main",
  "/loader.php?sid=racing",
  "/chronicles.php",

  // Casino
  "/casino.php",
  "/page.php?sid=slots",
  "/page.php?sid=slotsLastRolls",
  "/page.php?sid=slotsStats",
  "/page.php?sid=roulette",
  "/page.php?sid=rouletteLastSpins",
  "/page.php?sid=rouletteStatistics",
  "/page.php?sid=highlow",
  "/page.php?sid=highlowLastGames",
  "/page.php?sid=highlowStats",
  "/page.php?sid=keno",
  "/page.php?sid=kenoLastGames",
  "/page.php?sid=kenoStatistics",
  "/page.php?sid=craps",
  "/page.php?sid=crapsLastRolls",
  "/page.php?sid=crapsStats",
  "/page.php?sid=bookie",
  "/page.php?sid=bookie#/your-bets",
  "/page.php?sid=bookie#/stats/",
  "/page.php?sid=lottery",
  "/page.php?sid=lotteryTicketsBought",
  "/page.php?sid=lotteryPreviousWinners",
  "/page.php?sid=blackjack",
  "/page.php?sid=blackjackLastGames",
  "/page.php?sid=blackjackStatistics",
  "/page.php?sid=holdem",
  "/page.php?sid=holdemStats",
  "/page.php?sid=russianRoulette",
  "/loader.php?sid=viewRussianRouletteLastGames",
  "/loader.php?sid=viewRussianRouletteStats",
  "/page.php?sid=spinTheWheel",
  "/page.php?sid=spinTheWheelLastSpins",
  "/loader.php?sid=viewSlotsStats",
  "/loader.php?sid=viewHighLowLastGames",
  "/loader.php?sid=viewCrapsStats",
  "/loader.php?sid=viewLotteryUserStats",
  "/loader.php?sid=viewLotteryStats",
  "/loader.php?sid=viewBlackjackLastGames",

  // NPCS:
  "/profiles.php?XID=1", // Moved to the top
  "/profiles.php?XID=4",
  "/bazaar.php?userId=4",
  "/displaycase.php#display/4",
  "/profiles.php?XID=15",
  "/bazaar.php?userId=15",
  "/displaycase.php#display/15",
  "/profiles.php?XID=19",
  "/bazaar.php?userId=19",
  "/profiles.php?XID=20",
  "/bazaar.php?userId=20",
  "/profiles.php?XID=21",
  "/bazaar.php?userId=21",
  "/profiles.php?XID=10",
  "/bazaar.php?userId=10",
  "/displaycase.php#display/10",
  "/profiles.php?XID=17",
  "/profiles.php?XID=23",
  "/bazaar.php?userId=23",
  "/profiles.php?XID=50",
  "/bazaar.php?userId=50",
  "/profiles.php?XID=7",
  "/bazaar.php?userId=7",
  "/displaycase.php#display/7",
  "/profiles.php?XID=104",
  "/profiles.php?XID=102",
  "/profiles.php?XID=103",
  "/profiles.php?XID=100",
  "/profiles.php?XID=101",
  "/profiles.php?XID=3",

  // Old Mission NPCs
  "/profiles.php?XID=9",
  "/profiles.php?XID=8",

  // Faction Specific
  "/factions.php",
  "/factions.php?step=your",
  "/factions.php?step=your#/tab=info",
  "/factions.php?step=your#/tab=territory",
  "/factions.php?step=your#/tab=rank",
  "/factions.php?step=your#/tab=oc",
  "/factions.php?step=your#/tab=upgrades",
  "/factions.php?step=your#/tab=armoury",
  "/factions.php?step=your#/tab=controls",
  "/page.php?sid=factionWarfare",
  "/page.php?sid=factionWarfare#/ranked",
  "/page.php?sid=factionWarfare#/territory",
  "/page.php?sid=factionWarfare#/raids",
  "/page.php?sid=factionWarfare#/chains",
  "/page.php?sid=factionWarfare#/dirty-bombs",
  "/war.php?step=chainreport&chainID=36587144", // Moved here
  "/war.php?step=warreport&warID=41189", // Moved here
  "/war.php?step=rankreport&rankID=12096", // Moved here

  // Other
  "/joblisting.php",
  "/credits.php",
  "/rules.php",
  "/loader.php?sid=attack&user2ID=1",
  "/forums.php#/p=threads&f=67&t=16326854&b=0&a=0",
  "/old_forums.php",
  "/itemuseparcel.php",
  "/index.php?page=fortune",
  "/personalstats.php?ID=1",
  "/properties.php?step=rentalmarket",
  "/properties.php?step=sellingmarket",
  "/joblist.php#/p=corpinfo&userID=1699485",
  "/crimes.php#/step=main",
  "/newspaper.php#/tell_your_story",
  "/archives.php#/TheBirthOfTorn",
  "/page.php?sid=ItemMarket#/market/view=category&categoryName=Most%20Popular",
  "/properties.php#/p=yourProperties",
  "/properties.php#/p=spousesProperties",
  "/archives.php#/",
  "/archives.php#/Factions",
  "/archives.php#/Employment",
  "/archives.php#/TheMarkets",
  "/archives.php#/RealEstate",
  "/dump.php#/trash",
  "/userimages.php?XID=1",
  "/forums.php#/p=forums&f=1",
  "/forums.php#/p=forums&f=2",
  "/blacklist.php#p=add",
  "/friendlist.php#p=add",
  "/authenticate.php",
  "/staff.php",
  "/profiles.php?XID=1",
  "/joblist.php?step=search#!p=corpinfo&ID=79286",
  "/bazaar.php?userId=1#/",
  "/displaycase.php#display/1",
  "/loader.php?sid=attack&user2ID=17",
  "/forums.php#/p=forums&f=62&b=0&a=0",
  "/displaycase.php#display/50",
  "/loader.php?sid=attackLog&ID=62ffe20613b5b8cc8821c38989873f4b",
  "/christmas_town.php#/",
  "/christmas_town.php#/mymaps",
  "/christmas_town.php#/mapeditor",
  "/christmas_town.php#/parametereditor",
  "/christmas_town.php#/npceditor"
];

const eeeh_observer = new MutationObserver(function(mutations) {
    const url = window.location.href;
    if (url.includes("forums.php") && url.includes("f=67&t=16326854&b=0&a=0") && $('li.parent-post[data-id="23383506"]').length) {
    if (!document.getElementsByClassName("eeh-options").length) {
            insertOptions();
        }
    }
    if (document.getElementById("eggTraverse")) {
        return;
    }

    if (ButtonFloat) {
        if (document.getElementsByTagName('body')[0]) {
            insertFloat();
            return;
        }
    } else {
        // Insert into sidebar
        if (document.querySelector('#sidebar > div:first-of-type')) {
            insertNormal(); // Insert normal sidebar version
            return;
        }
    }
});


eeeh_observer.observe(document, {attributes: false, childList: true, characterData: false, subtree:true});


function insertNormal() {
    console.log("[Max's Egg Navigator] Inserting to sidebar...");
    if (!document.getElementById("eggTraverse")) {
        let href = EVERY_LINK[linkIndex];

        let easterspans = `
            <div class="eeh-link"><a href="${href}" id="eggTraverse"><span class="eeh-icon">${easteregg_svg}</span><span class="eeh-name">Egg Navigator (${linkIndex})</span></a></div>
            `;

        const sidebar = document.getElementById('sidebar');
        if (sidebar.firstChild) {
            // Insert the easterspans HTML string after the first child element of sidebar
            $('#sidebar > *').first().after(easterspans);
            $('#eggTraverse').on('mouseup touchend', function(e){
                clearTimeout(pressTimer);
            }).on('mousedown touchstart', function(e) {
                pressTimer = window.setTimeout(function() {
                    linkIndex = 0;
                    localStorage.setItem("eeh-index", linkIndex);
                    $('#eggTraverse').attr('href', EVERY_LINK[0]);
                    $('#eggTraverse .eeh-name').text('Egg Navigator (0)');
                },2500);
                return true;
            }).contextmenu(function(e) {
                e.preventDefault();
                e.stopPropagation();
                e.stopImmediatePropagation();
                return false;
            }).on('click', function(e) {
                linkIndex++;
                if (linkIndex >= EVERY_LINK.length) linkIndex = 0;
                localStorage.setItem("eeh-index", linkIndex);
                $('#eggTraverse').attr('href', EVERY_LINK[linkIndex]);
                $('#eggTraverse .eeh-name').text(`Egg Navigator (${linkIndex})`);
                return true;
            })



        }
        insertStyle();
    }
}

function insertFloat() {
    console.log("[Max's Egg Navigator] Inserting floating button...");
    if (!document.getElementById("eggTraverse")) {
        let href = EVERY_LINK[linkIndex];
        const eeh_float = `<a href="${href}" id="eggTraverse" class="eeh-float"><span class="eeh-icon">${easteregg_svg}</span><span class="eeh-name"> #${linkIndex}</span></a>`;

        $('body').append(eeh_float);


        if (ButtonFloatPos) {
            document.querySelector("#eggTraverse.eeh-float").classList.toggle("eeh-float-top");
        } else {
            document.querySelector("#eggTraverse.eeh-float").classList.toggle("eeh-float-bottom");
        }


        $('#eggTraverse').on('mouseup touchend', function(e){
            clearTimeout(pressTimer);
        }).on('mousedown touchstart', function(e) {
            pressTimer = window.setTimeout(function() {
                linkIndex = 0;
                localStorage.setItem("eeh-index", linkIndex);
                $('#eggTraverse').attr('href', EVERY_LINK[0]);
                $('#eggTraverse .eeh-name').text(' #0');
            },2500);
            return true;
        }).contextmenu(function(e) {
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();
            return false;
        }).on('click', function(e) {
            linkIndex++;
            if (linkIndex >= EVERY_LINK.length) linkIndex = 0;
            localStorage.setItem("eeh-index", linkIndex);
            $('#eggTraverse').attr('href', EVERY_LINK[linkIndex]);
            $('#eggTraverse .eeh-name').text(` #${linkIndex}`);
            return true;
        });
        insertStyle();
    }
}

function insertOptions() {
    console.log("[Max's Egg Navigator] Inserting options...");
    if (!document.getElementsByClassName("eeh-options").length) {
        const post = $('li.parent-post[data-id="23383506"]').find('div.post-container div.post');
        let enabled_float = ButtonFloat ? "enabled" : "disabled";
        let enabledClass_float = ButtonFloat ? "eeh-green" : "eeh-red";

        let enabled_float_pos = ButtonFloatPos ? "top" : "bottom";

        post.before(`
    <div class="eeh-options"><button id="eeh-float-toggle">Toggle floating button</button>
    <p>Floating button: <span id="eeh-float-toggle-label" class="${enabledClass_float}">${enabled_float}</span></p>
    </div>
    <div class="eeh-options"><button id="eeh-float-pos-toggle">Toggle float position</button>
    <p>Float position: <span id="eeh-float-pos-toggle-label">${enabled_float_pos}</span></p>
    </div>
    `);
        $('#eeh-float-toggle').click(function() {
            if (toggleFloatButton()) {
                $('#eeh-float-toggle-label').text("enabled");
            } else {
                $('#eeh-float-toggle-label').text("disabled");
            }
            $('#eeh-float-toggle-label').toggleClass('eeh-green eeh-red');
        });

        $('#eeh-float-pos-toggle').click(function() {
            if (toggleFloatPosition()) {
                $('#eeh-float-pos-toggle-label').text("top"); //1
            } else {
                $('#eeh-float-pos-toggle-label').text("bottom"); //0
            }
        });
    }
}

function insertStyle() {
    GM.addStyle(`
.eeh-link {
  background-color: var(--default-bg-panel-color);
  cursor: pointer;
  overflow: hidden;
  vertical-align: top;
  border-bottom-right-radius: 5px;
  border-top-right-radius: 5px;
  margin-top: 2px;
  height: 23px;
  margin-bottom: 2px;
}

.eeh-link:hover {
  background-color: var(--default-bg-panel-active-color);
}

.eeh-link a {
  display: flex;
  -ms-align-items: center;
  align-items: center;
  color: var(--default-color);
  text-decoration: none;
  height: 100%;
}

.eeh-link a .eeh-icon {
  float: left;
  width: 34px;
  height: 23px;
  display: flex;
  -ms-align-items: center;
  align-items: center;
  justify-content: center;
  margin-left: 0;
}

.eeh-link a .eeh-icon {
  stroke: transparent;
  stroke-width: 0;
}

.eeh-link a .eeh-name {
  line-height: 22px;
  padding-top: 1px;
  overflow: hidden;
  max-width: 134px;
}

.eeh-float .eeh-name {
  margin-left: 5px;
}

.eeh-float .eeh-icon svg {
  width: 20px !important;
  height: 26px !important;
}

#eggTraverse.eeh-float {
    z-index: 999999;
    height: 40px;
    width: 80px;
    cursor: pointer;
    left: -10px;
    padding: 10px 15px 10px 15px;
    box-sizing: border-box;
    border: 1px solid var(--default-panel-divider-outer-side-color);
    position: fixed;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    text-shadow: var(--default-tabs-text-shadow);
    background: var(--info-msg-bg-gradient);
    box-shadow: var(--default-tabs-box-shadow);
    border-radius: 5px;
    overflow: hidden;
    font-size: 15px;
    font-weight: 700;
    line-height: 18px;
    font-family: arial;
    color: var(--default-color);
    text-decoration: none;
}

#eggTraverse.eeh-float.eeh-float-top {
    top: 80px;
}

#eggTraverse.eeh-float.eeh-float-bottom {
    bottom: 80px;
}

[class*='topSection_'] .eeh-icon-svg-wrap {
    position: absolute;
    -ms-transform: translate(-120%, 10%);
    transform: translate(-120%, 10%);
}

.content-wrapper > #easterrandom .eeh-icon-svg-wrap {
    position: absolute;
    -ms-transform: translate(-140%, 10%);
    transform: translate(-140%, 10%);
}

.eeh-options {
    margin: 20px;
    margin-left: 0px;
}

.eeh-options p {
    margin-top: 5px;
    margin-left: 2px;
    font-size: 15px;
    font-weight: 700;
    line-height: 18px;
    font-family: arial;
}

.eeh-options button {
    background: transparent linear-gradient(180deg ,#CCCCCC 0%,#999999 60%,#666666 100%) 0 0 no-repeat;
    border-radius: 5px;
    font-family: Arial,sans-serif;
    font-size: 14px;
    font-weight: 700;
    text-align: center;
    letter-spacing: 0;
    color: #333;
    text-shadow: 0 1px 0 #ffffff66;
    text-decoration: none;
    text-transform: uppercase;
    margin: 0;
    border: none;
    outline: none;
    overflow: visible;
    box-sizing: border-box;
    line-height: 16px;
    padding: 4px 8px;
    height: auto;
    white-space: nowrap;
    cursor: pointer;
    margin-right: 5px;
}

.eeh-green {
    color: var(--user-status-green-color);
}

.eeh-red {
    color: var(--user-status-red-color);
}


@media screen and (max-width: 1000px) {
    html:not(.html-manual-desktop) [class*='topSection_'] #easterrandom span.eeh-text, .content-wrapper > #easterrandom span.eeh-text {
        display: none;
    }

    [class*='topSection_'] .eeh-icon-svg-wrap {
        -ms-transform: translate(-140%, -110%);
        transform: translate(-140%, -110%);
    }

    html:not(.html-manual-desktop) #eggTraverse.eeh-float.eeh-float-top {
        top: 170px !important;
    }
}

/* SVG Colors */
.eeh-link svg, .eeh-icon-svg svg {
  filter: drop-shadow(0px 0.7px 0.1px #fff);
  width: 13px !important;
  height: 17px !important;
}
.eeh-icon-svg svg path {
  fill: #AFC372 !important;
}
body.dark-mode .eeh-icon svg, body.dark-mode .eeh-icon-svg svg {
  filter: drop-shadow(0px 0px 1.3px #000);
}

/* Torn Edits */
.members-cont>.member-item>a[href="profiles.php?XID=1468764"]>.member>.member-header {
    color: #E0CE00 !important;
}

.members-cont>.member-item>a[href="profiles.php?XID=1468764"]>.member>.member-cont>span::after {
    content: "👑  " url("https://profileimages.torn.com/ad324318-744c-c686-1468764.gif?v=1940629196397");
}
`);
}

function killButton() {
    console.log("[Max's Egg Navigator] Killing button...");
    let eeh_button = document.getElementById("eggTraverse");
    if (eeh_button) {
        let parent = eeh_button.closest(`.eeh-link`);
        if (parent) {
            parent.remove();
        } else {
            eeh_button.remove();
        }
    }
}

function toggleFloatButton() {
    killButton();
    if (ButtonFloat) {
        ButtonFloat = 0;
        insertNormal();
    } else {
        ButtonFloat = 1;
        insertFloat();
    }
    localStorage.setItem("eeh-float", ButtonFloat);
    return ButtonFloat;
}

function toggleFloatPosition() {
    console.log("[Max's Egg Navigator] Changing float position...");
    if (ButtonFloatPos) {
        ButtonFloatPos = 0;
    } else {
        ButtonFloatPos = 1;
    }
    document.querySelector("#eggTraverse.eeh-float").classList.toggle("eeh-float-top");
    document.querySelector("#eggTraverse.eeh-float").classList.toggle("eeh-float-bottom");

    localStorage.setItem("eeh-float-pos", ButtonFloatPos);
    console.log(ButtonFloatPos)
    return ButtonFloatPos;
}

// Create run/stop button variables
let isRunning = false;

// Function to toggle auto-switch
function toggleAutoSwitch() {
    if (isRunning) {
        clearTimeout(autoSwitchInterval); // Immediately stop the timer
        isRunning = false; // Update state to stopped
        localStorage.setItem("eeh-isRunning", isRunning); // Persist stop state
        document.getElementById("runStopButton").textContent = "Run"; // Update button text

        // Clear any queued navigation
        document.getElementById("eggTraverse").href = EVERY_LINK[linkIndex]; // Ensure href doesn't change further
        console.log("[Max's Egg Navigator] Auto-switching stopped.");
    } else {
        isRunning = true; // Update state to running
        localStorage.setItem("eeh-isRunning", isRunning); // Persist start state
        document.getElementById("runStopButton").textContent = "Stop"; // Update button text
        autoSwitch(); // Start auto-switching
        console.log("[Max's Egg Navigator] Auto-switching started.");
    }
}



// Function to handle the auto-switching logic
function autoSwitch() {
    console.log("Attempting to auto-switch...");

    const randomDelay = Math.random() * (6500 - 3500) + 3500; // Random delay between 3.5 and 6.5 seconds

    autoSwitchInterval = setTimeout(() => {
        if (!isRunning) {
            console.log("[Max's Egg Navigator] Auto-switching halted.");
            return; // Exit the function early if stopped
        }

        // Check if page limit is reached
        if (pagesTraversed >= maxPages) {
            clearTimeout(autoSwitchInterval); // Stop any pending timer
            isRunning = false; // Update state to stopped
            localStorage.setItem("eeh-isRunning", isRunning); // Persist stop state
            document.getElementById("runStopButton").textContent = "Run"; // Update button text
            console.log(`[Max's Egg Navigator] Reached page limit (${maxPages}). Stopping script.`);
            return;
        }

        // Increment pages traversed
        pagesTraversed++;
        console.log(`[Max's Egg Navigator] Navigating to page ${pagesTraversed} of ${maxPages}.`);

        // Simulate interaction before switching pages
        simulateInteraction();

        // Switch to the next page
        linkIndex++;
        if (linkIndex >= EVERY_LINK.length) linkIndex = 0; // Loop back to the start
        localStorage.setItem("eeh-index", linkIndex); // Save the current index
        const nextPage = EVERY_LINK[linkIndex];
        document.getElementById("eggTraverse").href = nextPage;
        document.querySelector('#eggTraverse .eeh-name').textContent = `Egg Navigator (${linkIndex})`;

        // Simulate navigation to the next page
        window.location.href = nextPage;

        if (isRunning) {
            autoSwitch(); // Schedule the next switch only if still running
        }
    }, randomDelay);
}

// Insert the "Run/Stop" button and Input Field under the existing Egg Navigator
function insertRunStopButton() {
    console.log("Attempting to add Run/Stop button and input field...");
    const eggTraverseElement = document.getElementById("eggTraverse");
    const sidebar = document.getElementById('sidebar');

    if (sidebar && eggTraverseElement && !document.getElementById("runStopButton")) {
        // Create the "Run/Stop" button
        const runStopButton = document.createElement("button");
        runStopButton.id = "runStopButton";
        runStopButton.textContent = "Run"; // Default state is "Run"
        runStopButton.style.marginRight = "10px";
        runStopButton.style.cursor = "pointer";

        // Button styling
        runStopButton.style.background = "linear-gradient(180deg ,#CCCCCC 0%,#999999 60%,#666666 100%)";
        runStopButton.style.borderRadius = "5px";
        runStopButton.style.fontFamily = "Arial, sans-serif";
        runStopButton.style.fontSize = "14px";
        runStopButton.style.fontWeight = "700";
        runStopButton.style.textAlign = "center";
        runStopButton.style.color = "#333";
        runStopButton.style.textShadow = "0 1px 0 #ffffff66";
        runStopButton.style.padding = "4px 8px";
        runStopButton.style.border = "none";
        runStopButton.style.outline = "none";
        runStopButton.style.height = "auto";

        // Attach event listener to toggle auto-switch
        runStopButton.addEventListener("click", toggleAutoSwitch);

        // Create the input field to set the page index
        const inputField = document.createElement("input");
        inputField.id = "navigatorStartIndex";
        inputField.type = "number";
        inputField.min = "0";
        inputField.max = EVERY_LINK.length - 1;
        inputField.value = linkIndex; // Initialize with the current index
        inputField.style.width = "50px";
        inputField.style.marginLeft = "10px";

        // Attach listener for index changes
        inputField.addEventListener("change", () => {
            const newIndex = parseInt(inputField.value, 10);
            if (!isNaN(newIndex) && newIndex >= 0 && newIndex < EVERY_LINK.length) {
                linkIndex = newIndex; // Update the global index
                localStorage.setItem("eeh-index", linkIndex); // Persist index in localStorage
                document.getElementById("eggTraverse").href = EVERY_LINK[linkIndex]; // Update the link
                document.querySelector('#eggTraverse .eeh-name').textContent = `Egg Navigator (${linkIndex})`; // Update display
                console.log(`[Max's Egg Navigator] Page index updated to ${linkIndex}.`);
            } else {
                inputField.value = linkIndex; // Revert to the last valid index
                console.log("[Max's Egg Navigator] Invalid page index entered.");
            }
        });

        // Create a wrapper div to hold the button and input field
        const buttonWrapper = document.createElement("div");
        buttonWrapper.id = "runStopButtonWrapper";
        buttonWrapper.style.marginTop = "10px";
        buttonWrapper.style.padding = "5px";
        buttonWrapper.style.backgroundColor = "var(--default-bg-panel-color)";
        buttonWrapper.style.borderRadius = "5px";
        buttonWrapper.style.display = "flex";
        buttonWrapper.style.alignItems = "center";

        // Append the button and input field
        buttonWrapper.appendChild(runStopButton);
        buttonWrapper.appendChild(inputField);

        // Insert the wrapper into the sidebar
        sidebar.insertBefore(buttonWrapper, eggTraverseElement.nextSibling);

        console.log("[Max's Egg Navigator] Run/Stop button and page number input added.");
    } else {
        console.log("Run/Stop button and input field already exist or required elements are missing.");
    }
}

// Initialize the script
document.addEventListener("DOMContentLoaded", () => {
    insertRunStopButton(); // Insert the button
    isRunning = localStorage.getItem("eeh-isRunning") === "true"; // Retrieve the state
    console.log("Auto-switch state on load:", isRunning);
    if (isRunning) {
        document.getElementById("runStopButton").textContent = "Stop";
        autoSwitch(); // Start auto-switching if it was running
    } else {
        document.getElementById("runStopButton").textContent = "Run";
    }
});