Neopets - Custom Active Pet Sayings

Make your active pet occasionally talk, just like in the old layout.

// ==UserScript==
// @name           Neopets - Custom Active Pet Sayings
// @version        3
// @namespace      http://www.neopets.com/
// @match          *.neopets.com/*
// @description    Make your active pet occasionally talk, just like in the old layout.
// @copyright      Lendri Mujina
// @license        MIT
// @icon           https://www.google.com/s2/favicons?sz=64&domain=neopets.com
// @grant          none
// ==/UserScript==
//================================NEW - Function definitions
	function id(el,id) {return el.getElementById(id);}
	function did(id) {return document.getElementById(id);}
	function cl(el,cls) {return el.getElementsByClassName(cls)[0];}
	function dcl(cls) {return document.getElementsByClassName(cls)[0];}
	function tg(el,tag) {return el.getElementsByTagName(tag)[0];}
	function dtg(tag) {return document.getElementsByTagName(tag)[0];}
	function at(el,att) {return el.getAttribute(att);}
	function rnd(limit) {return Math.ceil(Math.random() * limit);}
	function rndbetween(min,max){return Math.floor(Math.random()*(max - min + 1)+min)}; // min and max included
	function fastSelect(selector){return [...document.querySelectorAll(selector)][0]};
	function hide(el){el.style.display="none";}
//=====================
	function randomlyActivate(){ //The rest of the script gets ignored unless this function returns True (the amount which is set below)
/////////////////////////////////////////////////
		//CONFIGURATION - FREQUENCY
/////////////////////////////////////////////////
		var phraseFrequency = 7.5;//% of page refreshes will have the pet speak. Decimal supported up to two places.
//The default is 7.5%; roughly the amount the site generated a phrase on its own.
/////////////////////////////////////////////////
		var check = rnd(10000);
		if (check <= (phraseFrequency*100)) {
			return true;
		}
		else {
			return false;
		}
	}
//=====Variable declarations
	var activePetInfo;
	var insertionPoint;
	var actpetname;
    var HTMLPhrase;
//=====Page Type Detector
	var pageContent;
    console.log("pageContent: " + pageContent);
	var pageType;
const isBeta = (document.querySelector('#container__2020') !== null);
const isClassic = (document.querySelector('td.sidebar') !== null);

if (isBeta) {
  pageContent = document.querySelector('#container__2020');
  pageType = 0;
  console.log(pageContent);
}

if (isClassic) {
  pageContent = document.querySelectorAll('div.content > td.content')[0];
  pageType = 1;
}
//==========
function mainScript() { //Separate function so that it can be ignored if randomlyActivate returns false.
//==========

	function randomWords(list){ //Allows randomized words to be part of phrases
		var selection = rnd(list.length-1);
		return list[selection];
	}

	function selectPhrases(list,currentName){ //Hunts through pet list and grabs phrase, along with error trap.
    		var finalPhrase = "";
		var errorTrap = "You haven\'t set any phrases for me yet!"; //If pet is not found, they'll say this by default
   		var i; //i Forgot what this was...
   		var limit = list.length - 1;
		for (i = 0, limit = list.length - 1; i < limit; ++i){ //Look for the active pet's name until the end of the list
			var result = i;
			if (list[result][0] == currentName) {
				var newLimit = list[result].length-1;
				finalPhrase = grabFromList(list[result],newLimit);
				break;
			}
			else {
				finalPhrase = errorTrap;
			}
		}
		return finalPhrase;
	}

var defaultPhrases = ["Is it time for training yet?","A Tiki Tour sounds good right about now!","Why don't you just paint me grey if you're gonna leave me like this?","Seen any good concerts lately?","I think some strength training is in order, don't you?","Do you think you could buy me a toy? Please?","Destruct-O-Match sounds like fun right about now.","AH! BEHIND YOU! Just kidding!","*yawn* Is it nap time, yet?","* ho hum *","My puny arms can't even hold an Attack Pea!","* sigh *","Know anyone who's up for a fight?!","How can I show my face in the Battledome like this?","When's the last time we visited the Techo Master?","Today doesn't seem to be a very good day."];
//After the pet's been chosen and the phrases have been narrowed down, this picks the specific one.
function grabFromList(list,limit){
    var phrID = Math.ceil(Math.random() * limit);
    if (phrID == null || phrID == 0 || phrID == undefined){ //If no custom phrases have been set, it'll use one of the old phrases.
        return randomWords(defaultPhrases);
    }
    else {
        return list[phrID];
    }
}

//==================================================
//If you have any special functions for phrases (e.g. arrays of changeable words), put them here.
//Some basic ones have been included to demonstrate.
//==================================================
var petSpecies=["Acara","Aisha","Blumaroo","Bori","Bruce","Buzz","Chia","Chomby","Cybunny","Draik","Elephante","Eyrie","Flotsam","Gelert","Gnorbu","Grarrl","Grundo","Hissi","Ixi","Jetsam","Jubjub","Kacheek","Kau","Kiko","Koi","Korbat","Kougra","Krawk","Kyrii","Lenny","Lupe","Lutari","Meerca","Moehog","Mynci","Nimmo","Ogrin","Peophin","Poogle","Pteri","Quiggle","Ruki","Scorchio","Shoyru","Skeith","Techo","Tonu","Tuskaninny","Uni","Usul","Vandagyre","Wocky","Xweetok","Yurble","Zafara"];
var neopianPlaces=["Altador","Brightvale","Darigan Citadel","Faerieland","Haunted Woods","Kiko Lake","Krawk Island","Kreludor","Lutari Island","Maraqua","Meridell","Moltara","Mystery Island","Neopia Central","Roo Island","Shenkuu","Terror Mountain","Lost Desert","Tyrannia","Virtupets Space Station","Dacardia"];




//==================================================


var petList = [//Creates array with all pets and their phrases
/////////////////////////////////////////////////
	//CONFIGURATION - YOUR PETS
/////////////////////////////////////////////////
//Type all of your pets' names,
//followed by the phrases you want them to say, with a comma after each until the end of the list.\
//If you want the old phrases to be a part of their vocabulary, type "randomWords(defaultPhrases)", without the quotes.
//Don't forget to put a "\" before apostrophes or quote marks if you want them to appear.
//See the following example for what I mean.

//["Your_First_Main_Account_Pet",
//		"A Tiki Tour sounds good right about now!",
//		"Why don\'t you just paint me grey if you're gonna leave me like this?",
//	],
//["Your_Second_Main_Account_Pet",
//		"Seen any good concerts lately?",
//		"I think some strength training is in order, don\'t you?",
//	],
//["Your_Third_Main_Account_Pet",
//		"Destruct-O-Match sounds like fun right about now.",
//		"AH! BEHIND YOU!<br>Just kidding!"
//["Your_First_Side_Account_Pet",
//		"When\'s the last time we visited the Techo Master?",
//		"Today doesn\'t seem to be a very good day."
//	]

["PETNAMEHERE",
 		randomWords(defaultPhrases),
	],

/////////////////////////////////////////////////];
[""]];//To ease syntax.
var thePhrase = selectPhrases(petList,actpetname);
function insertPhrase(pageType,insertPoint,petName,currentPhrase){ //Injects the chosen phrase into the page.
		if (isClassic){
			HTMLPhrase = "<tr><td class=\"neopetPhrase sf myPhrase\" align=\"center\"><b>" + petName + " says:</b><br>" + currentPhrase + "</td></tr>";
			insertPoint.insertAdjacentHTML('beforebegin',HTMLPhrase);
		}
		else if (isBeta){
			HTMLPhrase = "<div class=\"gQ_sprite\" style=\"position: absolute; overflow-y:auto;display: block; height: 66px; width: 300px; left: 60px; top: 0px; padding-right: 22px; background-position: 0px 0px; background-image: url(\'http://images.neopets.com/bd2/ui/comment.png\'); background-repeat: no-repeat;\" id=\"p1chat\"><p style=\"position:absolute;left:25px;width:280px;font-family:sans-serif;color:#000;font-size:0.55em;word-wrap:break-word;\">" + currentPhrase + "</p></div>";
//Right now there's nothing to insert the thang ding...
            console.log("insertPoint: " + insertPoint);
            insertPoint.innerHTML = HTMLPhrase;

        }
        else{
         console.log("Not a page where pet is visible");
        };
    }

	if (isClassic){
        console.log("isClassic");
		actpetname = dcl("sidebartable").getElementsByTagName("b")[0].textContent;
			console.log("actpetname = " + actpetname);
		activePetInfo = [...document.querySelectorAll(".sidebarModule > .sidebarTable > tbody > tr")]; //Grabs the module where the active pet's information is stored
		insertionPoint = activePetInfo[2];
        console.log("The insertionPoint = " + insertionPoint);
	}
	if (isBeta){
        console.log("isBeta");
		actpetname = dcl("profile-dropdown-link").textContent;
			console.log("actpetname = " + actpetname);
		insertionPoint = [...document.querySelectorAll(".nav-top__2020 > a")][0];
			console.log("The insertionPoint = " + insertionPoint);
	}
	thePhrase = selectPhrases(petList,actpetname);
		insertPhrase(pageType,insertionPoint,actpetname,thePhrase);
}//end of mainscript
var runFlag = randomlyActivate();

var existingPhrase = cl(document,"neopetPhrase");//Check if a phrase is already being generated site-side on a classic page; if it is, then removes it
    if (existingPhrase != undefined) {//If the site hasn't generated a phrase, do nothing
	console.log("Serverside phrase removed");
        existingPhrase[0].remove();
    }

   if (runFlag == true){
       mainScript();}