Guest User

Untitled

a guest
Mar 11th, 2022
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name         Melvor Action Queue
  3. // @version      1.2.0
  4. // @description  Adds an interface to queue up actions based on triggers you set
  5. // @author       8992
  6. // @match        https://*.melvoridle.com/*
  7. // @exclude      https://wiki.melvoridle.com/*
  8. // @grant        none
  9. // @namespace    http://tampermonkey.net/
  10. // @noframes
  11. // ==/UserScript==
  12.  
  13. let isVisible = false;
  14. let currentActionIndex = 0;
  15. let triggerCheckInterval = null;
  16. let nameIncrement = 0;
  17. let queueLoop = false;
  18. let queuePause = false;
  19. let manageMasteryInterval = null;
  20. let masteryConfigChanges = { skill: null };
  21. const lvlIndex = {};
  22. const masteryClone = {};
  23. const masteryConfig = {};
  24. const actionQueueArray = [];
  25. const shop = {};
  26. const tooltips = {};
  27. const validInputs = {
  28.   A: [null, null, null],
  29.   B: [null, null, null, null],
  30.   C: [null, null, null, null],
  31. };
  32. let currentlyEditing = { id: null, type: null };
  33. const pageIndex = {
  34.   Woodcutting: 0,
  35.   Fishing: 7,
  36.   Firemaking: 8,
  37.   Cooking: 9,
  38.   Mining: 10,
  39.   Smithing: 11,
  40.   Combat: 13,
  41.   Thieving: 14,
  42.   Farming: 15,
  43.   Fletching: 16,
  44.   Crafting: 17,
  45.   Runecrafting: 18,
  46.   Herblore: 19,
  47.   Agility: 20,
  48.   Summoning: 28,
  49.   Astrology: 31,
  50. };
  51.  
  52. function checkAmmoQty(id) {
  53.   const set = player.equipmentSets.find((a) => a.slots.Quiver.item.id == id);
  54.   return set ? set.slots.Quiver.quantity : 0;
  55. }
  56.  
  57. function checkFoodQty(id) {
  58.   const food = player.food.slots.find((a) => a.item.id == id);
  59.   return food ? food.quantity : 0;
  60. }
  61.  
  62. function actionTab() {
  63.   if (!isVisible) {
  64.     changePage(3);
  65.     $("#settings-container").attr("class", "content d-none");
  66.     $("#header-title").text("Action Queue");
  67.     $("#header-icon").attr("src", "assets/media/skills/prayer/mystic_lore.svg");
  68.     $("#header-theme").attr("class", "content-header bg-combat");
  69.     $("#page-header").attr("class", "bg-combat");
  70.     document.getElementById("action-queue-container").style.display = "";
  71.     isVisible = true;
  72.   }
  73. }
  74.  
  75. function hideActionTab() {
  76.   if (isVisible) {
  77.     document.getElementById("action-queue-container").style.display = "none";
  78.     isVisible = false;
  79.   }
  80. }
  81.  
  82. const options = {
  83.   //trigger options for dropdown menus
  84.   triggers: {
  85.     Idle: null,
  86.     "Item Quantity": {},
  87.     "Skill Level": {},
  88.     "Skill XP": {},
  89.     "Mastery Level": {
  90.       Agility: {},
  91.       Astrology: {},
  92.       Cooking: {},
  93.       Crafting: {},
  94.       Farming: {},
  95.       Firemaking: {},
  96.       Fishing: {},
  97.       Fletching: {},
  98.       Herblore: {},
  99.       Mining: {},
  100.       Runecrafting: {},
  101.       Smithing: {},
  102.       Summoning: {},
  103.       Thieving: {},
  104.       Woodcutting: {},
  105.     },
  106.     "Mastery Pool %": {},
  107.     "Pet Unlocked": {},
  108.     "Equipped Item Quantity": {},
  109.     "Prayer Points": { "≥": "num", "≤": "num" },
  110.     "Potion Depleted": {
  111.       Agility: null,
  112.       Astrology: null,
  113.       Combat: null,
  114.       Cooking: null,
  115.       Crafting: null,
  116.       Farming: null,
  117.       Firemaking: null,
  118.       Fishing: null,
  119.       Fletching: null,
  120.       Herblore: null,
  121.       Mining: null,
  122.       Runecrafting: null,
  123.       Smithing: null,
  124.       Summoning: null,
  125.       Thieving: null,
  126.       Woodcutting: null,
  127.     },
  128.     "Enemy in Combat": {},
  129.   },
  130.   //action options for dropdown menus
  131.   actions: {
  132.     "Start Skill": {
  133.       Agility: null,
  134.       Astrology: {},
  135.       Cooking: {},
  136.       Crafting: {},
  137.       Firemaking: {},
  138.       Fishing: {},
  139.       Fletching: {},
  140.       Herblore: {},
  141.       Magic: {},
  142.       Mining: {},
  143.       Runecrafting: {},
  144.       Smithing: {},
  145.       Summoning: {},
  146.       Thieving: {},
  147.       Woodcutting: {},
  148.     },
  149.     "Start Combat": {
  150.       "Slayer Task": null,
  151.     },
  152.     "Change Attack Style": { "Select Spell": { Normal: {}, Curse: {}, Aurora: {}, Ancient: {} } },
  153.     "Switch Equipment Set": { 1: null, 2: null, 3: null, 4: null },
  154.     "Equip Item": {},
  155.     "Equip Passive": {},
  156.     "Unequip Item": {},
  157.     "Buy Item": {},
  158.     "Sell Item": {},
  159.     "Use Potion": {},
  160.     "Activate Prayers": {},
  161.     "Build Agility Obstacle": {},
  162.     "Remove Agility Obstacle": {},
  163.   },
  164. };
  165.  
  166. function setTrigger(category, name, greaterThan, masteryItem, number) {
  167.   const itemID = items.findIndex((a) => a.name == name);
  168.   number = parseInt(number, 10);
  169.   switch (category) {
  170.     case "Idle":
  171.       return () => {
  172.         return !combatManager.isInCombat && offline.skill == null;
  173.       };
  174.     case "Item Quantity":
  175.       if (greaterThan == "≥") {
  176.         return () => {
  177.           return getBankQty(itemID) >= number;
  178.         };
  179.       }
  180.       return () => {
  181.         return getBankQty(itemID) <= number;
  182.       };
  183.     case "Prayer Points":
  184.       if (name == "≥") {
  185.         return () => {
  186.           return player.prayerPoints >= number;
  187.         };
  188.       }
  189.       return () => {
  190.         return player.prayerPoints <= number;
  191.       };
  192.     case "Skill Level": {
  193.       const xp = exp.level_to_xp(number);
  194.       return () => {
  195.         return skillXP[CONSTANTS.skill[name]] >= xp;
  196.       };
  197.     }
  198.     case "Skill XP":
  199.       return () => {
  200.         return skillXP[CONSTANTS.skill[name]] >= number;
  201.       };
  202.     case "Equipped Item Quantity":
  203.       if (items.filter((a) => a.canEat).find((a) => a.name == name)) {
  204.         return () => {
  205.           return checkFoodQty(itemID) <= number;
  206.         };
  207.       }
  208.       if (items.filter((a) => a.type == "Familiar").find((a) => a.name == name)) {
  209.         return () => {
  210.           let summonSlots = player.equipment.slotArray.slice(-2);
  211.           let slot = summonSlots.findIndex((a) => a.item.id == itemID);
  212.           return (slot >= 0 ? summonSlots[slot].quantity : 0) <= number;
  213.         };
  214.       }
  215.       return () => {
  216.         return checkAmmoQty(itemID) <= number;
  217.       };
  218.     case "Mastery Level":
  219.       let masteryID = fetchMasteryID(name, masteryItem);
  220.       return () => {
  221.         return getMasteryLevel(CONSTANTS.skill[name], masteryID) >= number;
  222.       };
  223.     case "Pet Unlocked": {
  224.       const petID = PETS.findIndex((pet) => {
  225.         const re = new RegExp(`^${name.split(" (")[0]}`, "g");
  226.         return re.test(pet.name);
  227.       });
  228.       return () => {
  229.         return petUnlocked[petID];
  230.       };
  231.     }
  232.     case "Mastery Pool %": {
  233.       const skill = CONSTANTS.skill[name];
  234.       return () => {
  235.         return getMasteryPoolProgress(skill) >= number;
  236.       };
  237.     }
  238.     case "Potion Depleted":
  239.       return () => {
  240.         return herbloreBonuses[pageIndex[name]].charges <= 0;
  241.       };
  242.     case "Enemy in Combat": {
  243.       const monsterID = MONSTERS.findIndex((a) => a.name == name);
  244.       return () => {
  245.         return combatManager.isInCombat && combatManager.selectedMonster == monsterID;
  246.       };
  247.     }
  248.   }
  249. }
  250.  
  251. function fetchMasteryID(skillName, itemName) {
  252.   const itemID = items.findIndex((a) => a.name == itemName);
  253.   let masteryID = itemID >= 0 && items[itemID].masteryID ? items[itemID].masteryID[1] : null;
  254.   switch (skillName) {
  255.     case "Cooking":
  256.       masteryID = Cooking.recipes.find((a) => a.itemID == itemID).masteryID;
  257.       break;
  258.     case "Herblore":
  259.       masteryID = Herblore.potions.find((a) => a.name == itemName).masteryID;
  260.       break;
  261.     case "Thieving":
  262.       masteryID = Thieving.npcs.find((a) => a.name == itemName).id;
  263.       break;
  264.     case "Agility":
  265.       masteryID = Agility.obstacles.findIndex((a) => a.name == itemName);
  266.       break;
  267.     case "Astrology":
  268.       masteryID = Astrology.constellations.findIndex((a) => a.name == itemName);
  269.       break;
  270.     case "Mining":
  271.       masteryID = Mining.rockData.findIndex((a) => a.name == itemName);
  272.       break;
  273.   }
  274.   return masteryID;
  275. }
  276.  
  277. function setAction(actionCategory, actionName, skillItem, skillItem2, qty) {
  278.   qty = parseInt(qty, 10);
  279.   const itemID = items.findIndex((a) => a.name == actionName);
  280.   switch (actionCategory) {
  281.     case "Start Skill":
  282.       return setSkillAction(actionName, skillItem, skillItem2);
  283.     case "Start Combat": {
  284.       //slayer task selection
  285.       if (actionName == "Slayer Task") {
  286.         return () => {
  287.           if (combatManager.slayerTask.killsLeft > 0) {
  288.             const mID = combatManager.slayerTask.monster.id;
  289.             const areaData = [...areaMenus.combat.areas, ...areaMenus.slayer.areas].find((a) =>
  290.               a.monsters.includes(mID)
  291.             );
  292.             if (combatManager.isInCombat && combatManager.selectedMonster == mID) return true;
  293.             combatManager.stopCombat();
  294.             combatManager.selectMonster(mID, areaData);
  295.             return true;
  296.           }
  297.           return false;
  298.         };
  299.       }
  300.       //dungeon selection
  301.       const dungeonIndex = DUNGEONS.findIndex((a) => a.name == actionName);
  302.       if (dungeonIndex >= 0) {
  303.         return () => {
  304.           if (
  305.             DUNGEONS[dungeonIndex].requiresCompletion === undefined ||
  306.             dungeonCompleteCount[DUNGEONS[dungeonIndex].requiresCompletion] >= 1
  307.           ) {
  308.             combatManager.selectDungeon(dungeonIndex);
  309.             return true;
  310.           }
  311.           return false;
  312.         };
  313.       }
  314.       //regular monster selection
  315.       const monsterIndex = MONSTERS.findIndex((a) => a.name == actionName);
  316.       const areaData = [...areaMenus.combat.areas, ...areaMenus.slayer.areas].find((a) =>
  317.         a.monsters.includes(monsterIndex)
  318.       );
  319.       return () => {
  320.         if (checkRequirements(areaData.entryRequirements)) {
  321.           if (!(combatManager.isInCombat && combatManager.selectedMonster == monsterIndex))
  322.             combatManager.selectMonster(monsterIndex, areaData);
  323.           return true;
  324.         }
  325.         return false;
  326.       };
  327.     }
  328.     case "Change Attack Style": {
  329.       if (actionName == "Select Spell") {
  330.         switch (skillItem) {
  331.           case "Normal":
  332.             return () => {
  333.               const spellID = SPELLS.findIndex((a) => a.name == skillItem2);
  334.               //check level req
  335.               if (skillLevel[CONSTANTS.skill.Magic] < SPELLS[spellID].magicLevelRequired) return false;
  336.               player.toggleSpell(spellID);
  337.               return true;
  338.             };
  339.           case "Curse":
  340.             return () => {
  341.               const spellID = CURSES.findIndex((a) => a.name == skillItem2);
  342.               //check level req
  343.               if (skillLevel[CONSTANTS.skill.Magic] < CURSES[spellID].magicLevelRequired) return false;
  344.               player.toggleCurse(spellID);
  345.               return true;
  346.             };
  347.           case "Aurora":
  348.             return () => {
  349.               const spellID = AURORAS.findIndex((a) => a.name == skillItem2);
  350.               //check level req
  351.               if (skillLevel[CONSTANTS.skill.Magic] < AURORAS[spellID].magicLevelRequired) return false;
  352.               //check item req
  353.               if (
  354.                 AURORAS[spellID].requiredItem >= 0 &&
  355.                 !player.equipment.slotArray.map((a) => a.item.id).includes(AURORAS[spellID].requiredItem)
  356.               )
  357.                 return false;
  358.               player.toggleAurora(spellID);
  359.               return true;
  360.             };
  361.           case "Ancient":
  362.             return () => {
  363.               const spellID = ANCIENT.findIndex((a) => a.name == skillItem2);
  364.               //check level req
  365.               if (skillLevel[CONSTANTS.skill.Magic] < ANCIENT[spellID].magicLevelRequired) return false;
  366.               //check dungeon req
  367.               if (
  368.                 dungeonCompleteCount[ANCIENT[spellID].requiredDungeonCompletion[0]] <
  369.                 ANCIENT[spellID].requiredDungeonCompletion[1]
  370.               )
  371.                 return false;
  372.               player.toggleSpellAncient(spellID);
  373.               return true;
  374.             };
  375.         }
  376.       }
  377.       const style = CONSTANTS.attackStyle[actionName];
  378.       return () => {
  379.         if (player.attackType == "magic") {
  380.           if (style < 6) return false;
  381.         } else if (player.attackType === "ranged") {
  382.           if (style > 5 || style < 3) return false;
  383.         } else {
  384.           if (style > 2) return false;
  385.         }
  386.         player.setAttackStyle(player.attackType, actionName);
  387.         return true;
  388.       };
  389.     }
  390.     case "Switch Equipment Set": {
  391.       const equipSet = parseInt(actionName) - 1;
  392.       return () => {
  393.         if (player.equipmentSets.length > equipSet) {
  394.           player.changeEquipmentSet(equipSet);
  395.           return true;
  396.         }
  397.         return false;
  398.       };
  399.     }
  400.     case "Equip Item":
  401.       return () => {
  402.         const bankID = getBankId(itemID);
  403.         if (bankID === -1) return false;
  404.         if (sellItemMode) toggleSellItemMode();
  405.         if (items[itemID].canEat) {
  406.           selectBankItem(itemID);
  407.           equipFoodQty = bank[bankID].qty;
  408.           equipFood();
  409.           return getBankQty(itemID) == 0; //returns false if there is any of the item left in bank (couldn't equip)
  410.         }
  411.         if (items[itemID].type == "Familiar") {
  412.           let slot = player.equipment.slotArray.slice(-3).findIndex((a) => a.item.id == itemID);
  413.           if (slot >= 0) {
  414.             player.equipItem(itemID, player.selectedEquipmentSet, `Summon${slot}`, bank[bankID].qty);
  415.           } else if (player.equipment.slotArray[12].quantity == 0) {
  416.             player.equipItem(itemID, player.selectedEquipmentSet, "Summon1", bank[bankID].qty);
  417.           } else if (player.equipment.slotArray[13].quantity == 0) {
  418.             player.equipItem(itemID, player.selectedEquipmentSet, "Summon2", bank[bankID].qty);
  419.           }
  420.           return getBankQty(itemID) == 0;
  421.         }
  422.         if (items[itemID].validSlots[0] == "Quiver") {
  423.           player.equipItem(itemID, player.selectedEquipmentSet, "Quiver", bank[bankID].qty);
  424.           return getBankQty(itemID) == 0; //returns false if there is any of the item left in bank (couldn't equip)
  425.         }
  426.         player.equipItem(itemID, player.selectedEquipmentSet);
  427.         return player.equipment.slots[items[itemID].validSlots[0]].item.id === itemID; //returns false if the item is not equipped
  428.       };
  429.     case "Equip Passive":
  430.       return () => {
  431.         if (dungeonCompleteCount[15] < 1 || getBankId(itemID) === -1) return false;
  432.         player.equipCallback(itemID, "Passive");
  433.         return player.equipment.slots.Passive.item.id === itemID;
  434.       };
  435.     case "Unequip Item": {
  436.       return () => {
  437.         for (const i in player.equipment.slots) {
  438.           if (player.equipment.slots[i].item.id == itemID) {
  439.             player.unequipCallback(i)();
  440.             return getBankQty(itemID) > 0; //returns false if there is 0 of the items in bank (no space to unequip)
  441.           }
  442.         }
  443.         return false;
  444.       };
  445.     }
  446.     case "Buy Item":
  447.       return () => {
  448.         return shop[actionName].buy(qty);
  449.       };
  450.     case "Sell Item":
  451.       return () => {
  452.         if (!bank.find((a) => a.id == itemID)) return false;
  453.         if (sellItemMode) toggleSellItemMode();
  454.         selectBankItem(itemID);
  455.         sellItem();
  456.         if (showSaleNotifications) swal.clickConfirm();
  457.         return true;
  458.       };
  459.     case "Use Potion":
  460.       return () => {
  461.         if (!bank.find((a) => a.id == itemID)) return false;
  462.         usePotion(itemID);
  463.         return true;
  464.       };
  465.     case "Activate Prayers": {
  466.       let choice = [];
  467.       if (actionName != "None") {
  468.         choice.push(PRAYER.findIndex((a) => a.name == actionName));
  469.         if (skillItem != "None") {
  470.           choice.push(PRAYER.findIndex((a) => a.name == skillItem));
  471.         }
  472.       }
  473.       return () => {
  474.         const validPrayers = choice.filter((a) => skillLevel[CONSTANTS.skill.Prayer] > PRAYER[a].prayerLevel);
  475.         changePrayers(validPrayers);
  476.         return true;
  477.       };
  478.     }
  479.     case "Build Agility Obstacle": {
  480.       const obstacleID = Agility.obstacles.findIndex((a) => a.name == skillItem);
  481.       const obstacleNumber = parseInt(actionName) - 1;
  482.       return () => {
  483.         if (chosenAgilityObstacles[obstacleNumber] == obstacleID) return true;
  484.         if (
  485.           !canIAffordThis(
  486.             Agility.obstacles[obstacleID].cost,
  487.             Agility.obstacles[obstacleID].skillRequirements,
  488.             obstacleID
  489.           )
  490.         )
  491.           return false;
  492.         if (chosenAgilityObstacles[obstacleNumber] >= 0) destroyAgilityObstacle(obstacleNumber, true);
  493.         buildAgilityObstacle(obstacleID, true);
  494.         return true;
  495.       };
  496.     }
  497.     case "Remove Agility Obstacle": {
  498.       const obstacleNumber = parseInt(actionName) - 1;
  499.       return () => {
  500.         if (chosenAgilityObstacles[obstacleNumber] >= 0) destroyAgilityObstacle(obstacleNumber, true);
  501.         return true;
  502.       };
  503.     }
  504.   }
  505. }
  506.  
  507. function setSkillAction(actionName, skillItem, skillItem2) {
  508.   const itemID = items.findIndex((a) => a.name == skillItem);
  509.   let actionID = 0;
  510.   switch (actionName) {
  511.     case "Agility":
  512.       return () => {
  513.         if (game.activeSkill !== globalThis.ActiveSkills.AGILITY) game.agility.start();
  514.         return true;
  515.       };
  516.     case "Astrology": {
  517.       const constellation = Astrology.constellations.find((a) => a.name == skillItem); // Find constellation
  518.       return () => {
  519.         if (skillLevel[CONSTANTS.skill.Astrology] < constellation.level) return false;
  520.         if (game.activeSkill !== globalThis.ActiveSkills.ASTROLOGY || game.astrology.activeConstellation.id != constellation.id) game.astrology.studyConstellationOnClick(constellation.id);
  521.         return true;
  522.       };
  523.     }
  524.     case "Cooking": {
  525.       const itemID = items.findIndex((a) => a.name == skillItem2);
  526.       const category = Cooking.recipes.find((a) => a.itemID == itemID).cookingCategory;
  527.       if (skillItem == "Active") {
  528.         return () => {
  529.           [0, 1, 2].forEach((category) => collectFromStockpile(category));
  530.           if (skillLevel[CONSTANTS.skill.Cooking] < Cooking.recipes.find((a) => a.itemID == itemID).level)
  531.             return false;
  532.           if (offline.skill == CONSTANTS.skill.Cooking && offline.action.active == itemID) return true;
  533.           selectCookingRecipe(category, itemID);
  534.           toggleActiveCook(category);
  535.           const passives = passiveCooking.reduce((arr, item, index) => {
  536.             return index != category && item >= 0 ? [...arr, index] : arr;
  537.           }, []);
  538.           passives.forEach((a) => togglePassiveCook(a));
  539.           return true;
  540.         };
  541.       } else {
  542.         return () => {
  543.           [0, 1, 2].forEach((category) => collectFromStockpile(category));
  544.           if (skillLevel[CONSTANTS.skill.Cooking] < Cooking.recipes.find((a) => a.itemID == itemID).level) return false;
  545.           if (passiveCooking[category] == itemID) return true;
  546.           selectCookingRecipe(category, itemID);
  547.           togglePassiveCook(category);
  548.           return true;
  549.         };
  550.       }
  551.     }
  552.     case "Crafting":
  553.       actionID = Crafting.recipes.find((a) => a.itemID == itemID).masteryID;
  554.       return () => {
  555.         if (skillLevel[CONSTANTS.skill.Crafting] < Crafting.recipes[actionID].level) return false;
  556.         if (game.crafting.selectedRecipeID !== actionID) game.crafting.selectRecipeOnClick(actionID);
  557.         if (game.activeSkill !== globalThis.ActiveSkills.CRAFTING) game.crafting.start();
  558.         return true;
  559.       };
  560.     case "Firemaking":
  561.       actionID = Firemaking.recipes.findIndex((x) => x.logID == itemID);
  562.       return () => {
  563.         if (skillLevel[CONSTANTS.skill.Firemaking] < Firemaking.recipes[actionID].levelRequired) return false;
  564.         if (!game.firemaking.activeRecipe || game.firemaking.activeRecipe.logID !== actionID)
  565.           game.firemaking.selectLog(actionID);
  566.         if (!game.firemaking.isActive) game.firemaking.burnLog();
  567.         return true;
  568.       };
  569.     case "Fishing": {
  570.       const fishIndex = Fishing.data.find((a) => a.itemID == itemID).masteryID;
  571.       const areaID = Fishing.areas.findIndex((a) => a.fish.includes(fishIndex));
  572.       const fishID = Fishing.areas[areaID].fish.findIndex((a) => a == fishIndex);
  573.       return () => {
  574.         if (
  575.           (!player.equipment.slotArray.map((a) => a.item.id).includes(CONSTANTS.item.Barbarian_Gloves) &&
  576.             areaID == 6) ||
  577.           (!secretAreaUnlocked && areaID == 7) ||
  578.           skillLevel[CONSTANTS.skill.Fishing] < Fishing.data[fishIndex].level
  579.         )
  580.           return false;
  581.         if (game.activeSkill !== globalThis.ActiveSkills.FISHING) {
  582.           selectFish(areaID, fishID);
  583.           startFishing(areaID, fishID, true);
  584.         } else {
  585.           if (areaID != offline.action[0] || fishID != offline.action[1]) {
  586.             startFishing(offline.action[0], offline.action[1], true);
  587.             selectFish(areaID, fishID);
  588.             startFishing(areaID, fishID, true);
  589.           }
  590.         }
  591.         return true;
  592.       };
  593.     }
  594.     case "Fletching":
  595.       actionID = Fletching.recipes.find((a) => a.itemID == itemID).masteryID;
  596.       const log = items.findIndex((a) => a.name == skillItem2);
  597.       if (skillItem != "Arrow Shafts") {
  598.         return () => {
  599.           if (skillLevel[CONSTANTS.skill.Fletching] < Fletching.recipes[actionID].level) return false;
  600.           if (game.fletching.selectedRecipeID !== actionID) game.fletching.selectRecipeOnClick(actionID);
  601.           if (game.activeSkill !== globalThis.ActiveSkills.FLETCHING) game.fletching.start();
  602.           return true;
  603.         };
  604.       }
  605.       return () => {
  606.         if (skillLevel[CONSTANTS.skill.Fletching] < Fletching.recipes[actionID].level || !checkBankForItem(log))
  607.           return false;
  608.         if (selectedFletchLog != log || selectedFletch !== actionID) game.fletching.selectAltRecipeOnClick(actionID);
  609.         if (game.activeSkill !== globalThis.ActiveSkills.FLETCHING) game.fletching.start();
  610.         return true;
  611.       };
  612.     case "Herblore":
  613.       actionID = Herblore.potions.findIndex((a) => a.name == skillItem);
  614.       return () => {
  615.         if (skillLevel[CONSTANTS.skill.Herblore] < Herblore.potions[actionID].level) return false;
  616.         if (game.herblore.selectedRecipeID !== actionID) game.herblore.selectRecipeOnClick(actionID);
  617.         if (!game.herblore.isActive) game.herblore.start();
  618.         return true;
  619.       };
  620.     case "Mining":
  621.       actionID = Mining.rockData.findIndex((a) => a.name == skillItem);
  622.       return () => {
  623.         if (
  624.           (actionID === 9 && !game.mining.canMineDragonite) ||
  625.           skillLevel[CONSTANTS.skill.Mining] < Mining.rockData[actionID].levelRequired
  626.         )
  627.           return false;
  628.         if (!game.mining.isActive || game.mining.selectedRockId != actionID) game.mining.onRockClick(actionID);
  629.         return true;
  630.       };
  631.     case "Magic": {
  632.       actionID = AltMagic.spells.findIndex((a) => a.name == skillItem);
  633.       const magicItem = items.findIndex((a) => a.name == skillItem2);
  634.       return () => {
  635.         if (skillLevel[CONSTANTS.skill.Magic] < AltMagic.spells[actionID].level) return false;
  636.         if (game.altMagic.selectedSpellID !== actionID) game.altMagic.selectSpellOnClick(actionID);
  637.         switch (AltMagic.spells[actionID].consumes) {
  638.           case 3:
  639.             const bar = Smithing.recipes.find((a) => a.itemID == magicItem);
  640.             if (skillLevel[CONSTANTS.skill.Smithing] < bar.level) return false;
  641.             if (game.altMagic.selectedSmithingRecipe != bar) game.altMagic.selectBarOnClick(bar);
  642.             break;
  643.           case 1:
  644.           case 0:
  645.             if (game.altMagic.selectedConversionItem != magicItem) game.altMagic.selectItemOnClick(magicItem);
  646.             break;
  647.         }
  648.         if (!game.altMagic.isActive) game.altMagic.start();
  649.         return true;
  650.       };
  651.     }
  652.     case "Runecrafting":
  653.       actionID = Runecrafting.recipes.findIndex((a) => a.itemID == itemID);
  654.       return () => {
  655.         if (skillLevel[CONSTANTS.skill.Runecrafting] < Runecrafting.recipes[actionID].level) return false;
  656.         if (game.runecrafting.selectedRecipeID !== actionID) game.runecrafting.selectRecipeOnClick(actionID);
  657.         if (game.activeSkill !== globalThis.ActiveSkills.RUNECRAFTING) game.runecrafting.start();
  658.         return true;
  659.       };
  660.     case "Smithing":
  661.       actionID = Smithing.recipes.findIndex((a) => a.itemID == itemID);
  662.       return () => {
  663.         if (skillLevel[CONSTANTS.skill.Smithing] < Smithing.recipes[actionID].level) return false;
  664.         if (game.smithing.selectedRecipeID !== actionID) game.smithing.selectRecipeOnClick(actionID);
  665.         if (!game.smithing.isActive) game.smithing.start();
  666.         return true;
  667.       };
  668.     case "Summoning": {
  669.       const summonID = Summoning.marks.find((a) => a.itemID == itemID).masteryID;
  670.       let recipeID = 0;
  671.       if (options.actions["Start Skill"]["Summoning"][skillItem] != null) {
  672.         const ingredientID = items.findIndex((a) => a.name == skillItem2);
  673.         recipeID = items[itemID].summoningReq.findIndex((a) => a.slice(-1)[0].id == ingredientID);
  674.       }
  675.       return () => {
  676.         //exit if low level
  677.         if (skillLevel[CONSTANTS.skill.Summoning] < Summoning.marks.find((a) => a.summoningID == summonID).level)
  678.           return false;
  679.         //if summon is not selected, choose it
  680.         if (selectedSummon != summonID || summoningData.defaultRecipe[summonID] != recipeID) {
  681.           game.summoning.selectRecipeOnClick(recipeID);
  682.         }
  683.         if (game.activeSkill !== globalThis.ActiveSkills.SUMMONING) game.summoning.start();
  684.         return game.activeSkill === globalThis.ActiveSkills.SUMMONING;
  685.       };
  686.     }
  687.     case "Thieving": {
  688.       const npc = Thieving.npcs.find((a) => a.name == skillItem);
  689.       const area = Thieving.areas.find((a) => a.npcs.includes(npc.id));
  690.       const panel = thievingMenu.areaPanels.find((a) => a.area == area);
  691.       return () => {
  692.         if (skillLevel[CONSTANTS.skill.Thieving] < npc.level) return false;
  693.         if (offline.skill == CONSTANTS.skill.Thieving && game.thieving.currentNPC == npc) return true;
  694.         thievingMenu.selectNPCInPanel(npc, panel);
  695.         game.thieving.startThieving(area, npc);
  696.         return true;
  697.       };
  698.     }
  699.     case "Woodcutting":
  700.       actionID = [itemID, items.findIndex((a) => a.name == skillItem2)].slice(
  701.         0,
  702.         playerModifiers.increasedTreeCutLimit + 1
  703.       );
  704.       return () => {
  705.         let result = true;
  706.         let currentTrees = [];
  707.         game.woodcutting.activeTrees.forEach((a) => currentTrees.push(a.id));
  708.         currentTrees.forEach((tree) => {
  709.           if (actionID.includes(tree)) {
  710.             actionID.splice(
  711.               actionID.findIndex((a) => a == tree),
  712.               1
  713.             );
  714.           } else {
  715.             actionID.unshift(tree);
  716.           }
  717.         });
  718.  
  719.         actionID.forEach((i) => {
  720.           if (skillLevel[CONSTANTS.skill.Woodcutting] >= Woodcutting.trees[i].levelRequired) {
  721.             game.woodcutting.selectTree(Woodcutting.trees[i]);
  722.           } else {
  723.             result = false;
  724.           }
  725.         });
  726.         return result;
  727.       };
  728.   }
  729. }
  730.  
  731. class Action {
  732.   /**
  733.    * Create an action object with trigger
  734.    * @param {string} category (Tier 1 option) category for trigger
  735.    * @param {string} name (Tier 2 option) skill/item name
  736.    * @param {string} greaterThan (Tier 3 option) either ≥ or ≤
  737.    * @param {string} masteryItem (Tier 3 option) target name for mastery
  738.    * @param {string} number (Tier 4 option) target number for skill/mastery/item
  739.    * @param {string} actionCategory (Tier 1 option) category for action
  740.    * @param {string} actionName (Tier 2 option) skill/monster/item/set name
  741.    * @param {string} skillItem (Tier 3 option) name for skilling action
  742.    * @param {string} skillItem2 (Tier 4 option) name of second tree to cut or alt.magic item
  743.    * @param {string} qty (Tier 4 option) amount of item to buy if applicable
  744.    */
  745.   constructor(
  746.     category,
  747.     name,
  748.     greaterThan,
  749.     masteryItem,
  750.     number,
  751.     actionCategory,
  752.     actionName,
  753.     skillItem,
  754.     skillItem2,
  755.     qty
  756.   ) {
  757.     switch (category) {
  758.       case "Idle":
  759.         this.description = `If no active skills/combat:`;
  760.         break;
  761.       case "Item Quantity":
  762.         this.description = `If ${name} ${greaterThan} ${number}:`;
  763.         break;
  764.       case "Prayer Points":
  765.         this.description = `If prayer points ${greaterThan} ${number}:`;
  766.         break;
  767.       case "Skill Level":
  768.         this.description = `If ${name} ≥ level ${number}:`;
  769.         break;
  770.       case "Skill XP":
  771.         this.description = `If ${name} ≥ ${number}xp:`;
  772.         break;
  773.       case "Equipped Item Quantity": {
  774.         let plural = name;
  775.         if (!/s$/i.test(name)) plural += "s";
  776.         this.description = `If ≤ ${number} ${plural} equipped:`;
  777.         break;
  778.       }
  779.       case "Mastery Level":
  780.         this.description = `If ${name} ${masteryItem} mastery ≥ ${number}:`;
  781.         break;
  782.       case "Pet Unlocked":
  783.         this.description = `If ${name} unlocked:`;
  784.         break;
  785.       case "Mastery Pool %":
  786.         this.description = `If ${name} mastery pool ≥ ${number}%:`;
  787.         break;
  788.       case "Potion Depleted":
  789.         this.description = `If ${name} potion has depleted:`;
  790.         break;
  791.       case "Enemy in Combat":
  792.         this.description = `If fighting ${name}:`;
  793.     }
  794.     this.data = [category, name, greaterThan, masteryItem, number];
  795.     this.elementID = `AQ${nameIncrement++}`;
  796.     this.trigger = setTrigger(category, name, greaterThan, masteryItem, number);
  797.     if (typeof actionCategory == "string") {
  798.       this.action = [
  799.         {
  800.           elementID: `AQ${nameIncrement++}`,
  801.           data: [actionCategory, actionName, skillItem, skillItem2, qty],
  802.           start: setAction(actionCategory, actionName, skillItem, skillItem2, qty),
  803.           description: actionDescription(actionCategory, actionName, skillItem, skillItem2, qty),
  804.         },
  805.       ];
  806.     } else {
  807.       this.action = [];
  808.     }
  809.   }
  810. }
  811.  
  812. function actionDescription(actionCategory, actionName, skillItem, skillItem2, qty) {
  813.   let description = "";
  814.   switch (actionCategory) {
  815.     case "Start Skill":
  816.       description += `start ${actionName} ${skillItem}`;
  817.       if (actionName == "Summoning") {
  818.         description = `start creating ${skillItem} tablets`;
  819.         if (options.actions["Start Skill"]["Summoning"][skillItem] != null) {
  820.           description += ` from ${skillItem2}`;
  821.         }
  822.       }
  823.       if (actionName == "Astrology") description = `Start studying ${skillItem} in ${actionName}`;
  824.       if (actionName == "Cooking") description = `Start ${skillItem} Cooking ${skillItem2}`;
  825.       if (actionName == "Woodcutting") description += ` & ${skillItem2}`;
  826.       if (skillItem == "Arrow Shafts") description += ` from ${skillItem2}`;
  827.       if (actionName == "Magic") {
  828.         description += ` with ${skillItem2}`;
  829.         if (!/s$/i.test(skillItem2)) description += "s";
  830.       }
  831.       break;
  832.     case "Start Combat":
  833.       description += `start fighting ${actionName}`;
  834.       break;
  835.     case "Change Attack Style":
  836.       if (actionName == "Select Spell") {
  837.         description += `select ${skillItem2} spell`;
  838.       } else {
  839.         description += `change attack style to ${actionName}`;
  840.       }
  841.       break;
  842.     case "Switch Equipment Set":
  843.       description += `switch to equipment set ${actionName}`;
  844.       break;
  845.     case "Equip Item":
  846.       description += `equip ${actionName} to current set`;
  847.       break;
  848.     case "Equip Passive":
  849.       description += `equip ${actionName} to passive slot`;
  850.       break;
  851.     case "Unequip Item":
  852.       description += `unequip ${actionName} from current set`;
  853.       break;
  854.     case "Buy Item":
  855.       if (qty > 1) {
  856.         description += `buy ${qty} ${actionName} from shop`;
  857.       } else {
  858.         description += `buy ${actionName} from shop`;
  859.       }
  860.       break;
  861.     case "Sell Item":
  862.       description += `sell ${actionName}`;
  863.       break;
  864.     case "Use Potion":
  865.       description += `use ${actionName} potion`;
  866.       break;
  867.     case "Activate Prayers":
  868.       {
  869.         if (actionName == "None") {
  870.           description += `turn off prayers`;
  871.         } else {
  872.           description += `turn on ${actionName}`;
  873.           if (skillItem != "None") description += ` and ${skillItem}`;
  874.         }
  875.       }
  876.       break;
  877.     case "Build Agility Obstacle":
  878.       description += `build ${skillItem}`;
  879.       break;
  880.     case "Remove Agility Obstacle":
  881.       description += `remove obstacle ${actionName}`;
  882.       break;
  883.   }
  884.   return description;
  885. }
  886.  
  887. function resetForm(arr) {
  888.   arr.forEach((menu) => {
  889.     document.getElementById(`aq-num${menu}`).type = "hidden";
  890.     document.getElementById(`aq-num${menu}`).value = "";
  891.     validInputs[menu].forEach((a, i) => {
  892.       if (i != 0) {
  893.         document.getElementById(`aq-text${menu}${i}`).type = "hidden"; //hide all except first
  894.         document.getElementById(`aq-list${menu}${i}`).innerHTML = ""; //empty datalists
  895.       }
  896.       document.getElementById(`aq-text${menu}${i}`).value = ""; //clear values
  897.       validInputs[menu][i] = null;
  898.     });
  899.   });
  900. }
  901.  
  902. function submitForm() {
  903.   try {
  904.     //create array of the input values
  905.     const arr = [];
  906.     ["A", "B"].forEach((menu) => {
  907.       for (let i = 0; i < validInputs[menu].length; i++) arr.push(document.getElementById(`aq-text${menu}${i}`).value);
  908.       arr.push(document.getElementById(`aq-num${menu}`).value);
  909.     });
  910.     arr.splice(["≥", "≤", ""].includes(arr[2]) ? 3 : 2, 0, "");
  911.  
  912.     //validate trigger and action
  913.     if (
  914.       validateInput(
  915.         options.triggers,
  916.         arr.slice(0, 5).filter((a) => a !== "")
  917.       ) &&
  918.       validateInput(
  919.         options.actions,
  920.         arr.slice(5).filter((a) => a !== "")
  921.       )
  922.     ) {
  923.       addToQueue(new Action(...arr));
  924.       resetForm(["A", "B"]);
  925.     }
  926.   } catch (e) {
  927.     console.error(e);
  928.   }
  929.   return false;
  930. }
  931.  
  932. /**
  933.  * Function to validate user input
  934.  * @param {Object} obj options object to check against
  935.  * @param {Array} tier array of user inputs
  936.  * @param {number} n leave blank (used for recursion)
  937.  * @returns {boolean} true if input is valid
  938.  */
  939. function validateInput(obj, tier, n = 0) {
  940.   if (!obj.hasOwnProperty([tier[n]])) return false;
  941.   if (obj[tier[n]] === null || (obj[tier[n]] === "num" && /^\d{1,10}$/.test(tier[n + 1]))) return true;
  942.   return validateInput(obj[tier[n]], tier, n + 1);
  943. }
  944.  
  945. /**
  946.  * Updates input text boxes
  947.  * @param {string} menu ('A'||'B'||'C')
  948.  */
  949. function dropdowns(menu) {
  950.   let obj;
  951.   if (menu == "A") {
  952.     obj = options.triggers;
  953.   } else if (menu == "B") {
  954.     obj = options.actions;
  955.   } else {
  956.     obj = options[currentlyEditing.type == "triggers" ? "triggers" : "actions"];
  957.   }
  958.   for (let i = 0; i < validInputs[menu].length; i++) {
  959.     const value = document.getElementById(`aq-text${menu}${i}`).value;
  960.     if (Object.keys(obj).includes(value)) {
  961.       if (obj[value] == "num") {
  962.         document.getElementById(`aq-num${menu}`).type = "text";
  963.         break;
  964.       }
  965.       if (obj[value] == null) break;
  966.       obj = obj[value];
  967.       if (validInputs[menu][i] != value) {
  968.         validInputs[menu][i] = value;
  969.         document.getElementById(`aq-text${menu}${i + 1}`).type = "text";
  970.         document.getElementById(`aq-list${menu}${i + 1}`).innerHTML = "";
  971.         Object.keys(obj).forEach((e) => {
  972.           document.getElementById(`aq-list${menu}${i + 1}`).insertAdjacentHTML("beforeend", `<option>${e}</option>`);
  973.         });
  974.       }
  975.     } else {
  976.       validInputs[menu][i] = null;
  977.       for (i++; i < validInputs[menu].length; i++) {
  978.         try {
  979.           validInputs[menu][i] = null;
  980.           document.getElementById(`aq-text${menu}${i}`).type = "hidden";
  981.           document.getElementById(`aq-text${menu}${i}`).value = "";
  982.         } catch {}
  983.       }
  984.       document.getElementById(`aq-num${menu}`).type = "hidden";
  985.       document.getElementById(`aq-num${menu}`).value = "";
  986.     }
  987.   }
  988. }
  989.  
  990. const aqHTML = `<div class="content" id="action-queue-container" style="display: none">
  991. <div class="row row-deck">
  992.   <div class="col-md-12">
  993.     <div class="block block-rounded block-link-pop border-top border-settings border-4x">
  994.       <form class="aq-mastery-config" id="aq-mastery-config-container" style="display: none">
  995.         <div style="display: inline-block; margin-left: 20px; height: 180px; vertical-align: top">
  996.           <h3 class="aq-header">Mastery Config</h3>
  997.           <div>
  998.             <select id="aq-skill-list" class="aq-select"></select>
  999.           </div>
  1000.           <div>
  1001.             <select id="aq-checkpoint-list" class="aq-select">
  1002.               <option value="0">0%</option>
  1003.               <option value="0.1">10%</option>
  1004.               <option value="0.25">25%</option>
  1005.               <option value="0.5">50%</option>
  1006.               <option value="0.95">95%</option>
  1007.             </select>
  1008.           </div>
  1009.           <div>
  1010.             <select id="aq-mastery-strategy" class="aq-select">
  1011.               <option value="false">Lowest mastery</option>
  1012.               <option value="true">Custom priority</option>
  1013.             </select>
  1014.           </div>
  1015.           <div>
  1016.             <select id="aq-base" class="aq-select"></select>
  1017.           </div>
  1018.           <div>
  1019.             <input type="text" id="aq-mastery-array" class="aq-select"/>
  1020.           </div>
  1021.         </div>
  1022.         <div style="margin-left: 20px">
  1023.           <button type="button" class="btn btn-sm aq-green" id="aq-config-close">Done</button>
  1024.         </div>
  1025.       </form>
  1026.       <form class="aq-popup" id="aq-edit-container" style="display: none;">
  1027.         <div style="display: inline-block; margin-left: 20px; height: 180px; vertical-align: top">
  1028.           <h3 id="aq-edit-form" class="aq-header">Action</h3>
  1029.           <div>
  1030.             <input type="text" class="aq-dropdown" id="aq-textC0" required list="aq-listC0" placeholder="Category" />
  1031.           </div>
  1032.           <div>
  1033.             <input type="hidden" class="aq-dropdown" id="aq-textC1" list="aq-listC1" />
  1034.           </div>
  1035.           <div>
  1036.             <input type="hidden" class="aq-dropdown" id="aq-textC2" list="aq-listC2" />
  1037.           </div>
  1038.           <div>
  1039.             <input type="hidden" class="aq-dropdown" id="aq-textC3" list="aq-listC3" />
  1040.           </div>
  1041.           <div>
  1042.             <input type="hidden" class="aq-dropdown" id="aq-numC" pattern="^\\d{1,10}$" placeholder="number" title="Positive integer"/>
  1043.           </div>
  1044.         </div>
  1045.         <div style="margin-left: 20px">
  1046.           <button type="button" id="aq-save-edit" class="btn btn-sm aq-blue">Save</button>
  1047.           <button type="button" id="aq-cancel" class="btn btn-sm btn-danger">Cancel</button>
  1048.         </div>
  1049.       </form>
  1050.       <div class="block-content">
  1051.         <div>
  1052.           <form id="aq-form">
  1053.             <div style="display: inline-block; margin-left: 20px; height: 180px; vertical-align: top">
  1054.               <h3 class="aq-header">Trigger</h3>
  1055.               <div>
  1056.                 <input type="text" class="aq-dropdown" id="aq-textA0" required list="aq-listA0" placeholder="Category" />
  1057.               </div>
  1058.               <div>
  1059.                 <input type="hidden" class="aq-dropdown" id="aq-textA1" list="aq-listA1" />
  1060.               </div>
  1061.               <div>
  1062.                 <input type="hidden" class="aq-dropdown" id="aq-textA2" list="aq-listA2" />
  1063.               </div>
  1064.               <div>
  1065.                 <input type="hidden" class="aq-dropdown" id="aq-numA" pattern="^\\d{1,10}$" placeholder="number" title="Positive integer"/>
  1066.               </div>
  1067.             </div>
  1068.             <div style="display: inline-block; margin-left: 20px; height: 180px; vertical-align: top">
  1069.               <h3 class="aq-header">Action</h3>
  1070.               <div>
  1071.                 <input type="text" class="aq-dropdown" id="aq-textB0" required list="aq-listB0" placeholder="Category" />
  1072.               </div>
  1073.               <div>
  1074.                 <input type="hidden" class="aq-dropdown" id="aq-textB1" list="aq-listB1" />
  1075.               </div>
  1076.               <div>
  1077.                 <input type="hidden" class="aq-dropdown" id="aq-textB2" list="aq-listB2" />
  1078.               </div>
  1079.               <div>
  1080.                 <input type="hidden" class="aq-dropdown" id="aq-textB3" list="aq-listB3" />
  1081.               </div>
  1082.               <div>
  1083.                 <input type="hidden" class="aq-dropdown" id="aq-numB" pattern="^\\d{1,10}$" placeholder="number" title="Positive integer"/>
  1084.               </div>
  1085.             </div>
  1086.             <div style="margin-left: 20px">
  1087.               <input type="submit" class="btn btn-sm aq-blue" value="Add to queue">
  1088.               <button type="button" id="aq-pause" class="btn btn-sm aq-yellow">Pause</button>
  1089.             </div>
  1090.           </form>
  1091.         </div>
  1092.         <form style="margin: 10px 0 5px 20px">
  1093.           <button type="button" class="btn btn-sm aq-grey" id="aq-download">Download Action List</button>
  1094.           <input type="submit" class="btn btn-sm aq-grey" value="Import Action List" />
  1095.           <input type="text" id="aq-pastebin" style="width: 236px;" required pattern="^\\[.*\\]$" placeholder="Paste data here" />
  1096.         </form>
  1097.         <div style="display: flex;justify-content: space-between;max-width: 550px;margin: 10px 0 0 25px;">
  1098.           <p style="margin: 0;">Looping</p>
  1099.           <div class="">
  1100.             <div class="custom-control custom-radio custom-control-inline custom-control-lg">
  1101.                 <input type="radio" class="custom-control-input" id="aq-loop-enable" name="aq-looping">
  1102.                 <label class="custom-control-label" for="aq-loop-enable">Enable</label>
  1103.             </div>
  1104.             <div class="custom-control custom-radio custom-control-inline custom-control-lg">
  1105.                 <input type="radio" class="custom-control-input" id="aq-loop-disable" name="aq-looping" checked="">
  1106.                 <label class="custom-control-label" for="aq-loop-disable">Disable</label>
  1107.             </div>
  1108.           </div>
  1109.         </div>
  1110.         <div style="display: flex;justify-content: space-between;max-width: 550px;margin: 10px 0 0 25px;">
  1111.           <p style="margin: 0;">Mastery Pool Management</p>
  1112.           <div class="">
  1113.             <div class="custom-control custom-radio custom-control-inline custom-control-lg">
  1114.                 <input type="radio" class="custom-control-input" id="aq-mastery-enable" name="aq-mastery">
  1115.                 <label class="custom-control-label" for="aq-mastery-enable">Enable</label>
  1116.             </div>
  1117.             <div class="custom-control custom-radio custom-control-inline custom-control-lg">
  1118.                 <input type="radio" class="custom-control-input" id="aq-mastery-disable" name="aq-mastery" checked="">
  1119.                 <label class="custom-control-label" for="aq-mastery-disable">Disable</label>
  1120.             </div>
  1121.           </div>
  1122.         </div>
  1123.         <div style="margin: 10px 0 0 25px; display: flex; justify-content: space-between">
  1124.           <button type="button" class="btn btn-sm aq-grey" id="aq-mastery-config">Advanced Mastery Options</button>
  1125.           <button type="button" style="font-size: 0.875rem" class="btn aq-delete btn-danger" id="aq-delete-all">delete all</button>
  1126.         </div>
  1127.         <h2 class="content-heading border-bottom mb-4 pb-2">Current Queue</h2>
  1128.         <div style="min-height: 50px" id="aq-item-container"></div>
  1129.       </div>
  1130.     </div>
  1131.   </div>
  1132. </div>
  1133. </div>
  1134. <datalist id="aq-listA0"></datalist>
  1135. <datalist id="aq-listA1"></datalist>
  1136. <datalist id="aq-listA2"></datalist>
  1137. <datalist id="aq-listB0"></datalist>
  1138. <datalist id="aq-listB1"></datalist>
  1139. <datalist id="aq-listB2"></datalist>
  1140. <datalist id="aq-listB3"></datalist>
  1141. <datalist id="aq-listC0"></datalist>
  1142. <datalist id="aq-listC1"></datalist>
  1143. <datalist id="aq-listC2"></datalist>
  1144. <datalist id="aq-listC3"></datalist>
  1145. <style>
  1146. .aq-dropdown {
  1147.   width: 260px;
  1148. }
  1149. .aq-header {
  1150.   margin-bottom: 10px;
  1151.   color: whitesmoke;
  1152. }
  1153. .aq-arrow {
  1154.   font-size: 2rem;
  1155.   padding: 0px 0.25rem;
  1156.   line-height: 0px;
  1157.   margin: 0.25rem 2px;
  1158.   border-radius: 0.2rem;
  1159. }
  1160. .aq-item {
  1161.   background-color: #464646;
  1162.   padding: 12px;
  1163.   margin: 12px;
  1164.   cursor: move;
  1165. }
  1166. .aq-item-inner {
  1167.   display: flex;
  1168.   justify-content: space-between;
  1169.   cursor: move;
  1170. }
  1171. .aq-delete {
  1172.   font-size: 1.2rem;
  1173.   padding: 0px 0.36rem;
  1174.   line-height: 0px;
  1175.   margin: 0.25rem 0.25rem 0.25rem 0.125rem;
  1176.   border-radius: 0.2rem;
  1177. }
  1178. .aq-grey {
  1179.   background-color: #676767;
  1180. }
  1181. .aq-grey:hover {
  1182.   background-color: #848484;
  1183. }
  1184. .aq-blue {
  1185.   background-color: #0083ff;
  1186. }
  1187. .aq-blue:hover {
  1188.   background-color: #63b4ff;
  1189. }
  1190. .aq-green {
  1191.   background-color: #5a9e00;
  1192. }
  1193. .aq-green:hover {
  1194.   background-color: #7bd900;
  1195. }
  1196. .aq-yellow {
  1197.   background-color: #e69721;
  1198. }
  1199. .aq-yellow:hover {
  1200.   background-color: #ffb445;
  1201. }
  1202. .t-drag {
  1203.   opacity: 0.5;
  1204. }
  1205. .a-drag {
  1206.   opacity: 0.5;
  1207. }
  1208. .aq-popup {
  1209.   position: fixed;
  1210.   right: 5%;
  1211.   top: 20%;
  1212.   z-index: 2;
  1213.   background-color: #3f4046;
  1214.   padding: 20px 20px 20px 0;
  1215.   border-top: 1px solid #e1e6e9;
  1216.   border-radius: 0.25rem;
  1217.   border-width: 4px;
  1218. }
  1219. .aq-mastery-config {
  1220.   position: fixed;
  1221.   right: 67%;
  1222.   top: 18%;
  1223.   z-index: 3;
  1224.   background-color: #3f4046;
  1225.   padding: 20px 20px 20px 0;
  1226.   border-top: 1px solid #e1e6e9;
  1227.   border-radius: 0.25rem;
  1228.   border-width: 4px;
  1229. }
  1230. .aq-select {
  1231.   width: 200px;
  1232. }
  1233. </style>
  1234. `;
  1235.  
  1236. function loadAQ() {
  1237.   //add item names
  1238.   for (const a of items) {
  1239.     options.triggers["Item Quantity"][a.name] = { "≥": "num", "≤": "num" };
  1240.     options.actions["Sell Item"][a.name] = null;
  1241.     if (a.validSlots && a.validSlots.includes("Passive")) options.actions["Equip Passive"][a.name] = null;
  1242.   }
  1243.  
  1244.   //add attack styles
  1245.   for (const s in CONSTANTS.attackStyle) {
  1246.     if (isNaN(s)) options.actions["Change Attack Style"][s] = null;
  1247.   }
  1248.   //add normal spells
  1249.   for (const s of SPELLS) {
  1250.     options.actions["Change Attack Style"]["Select Spell"]["Normal"][s.name] = null;
  1251.   }
  1252.   //add curse spells
  1253.   for (const s of CURSES) {
  1254.     options.actions["Change Attack Style"]["Select Spell"]["Curse"][s.name] = null;
  1255.   }
  1256.   //add aurora spells
  1257.   for (const s of AURORAS) {
  1258.     options.actions["Change Attack Style"]["Select Spell"]["Aurora"][s.name] = null;
  1259.   }
  1260.   //add ancient spells
  1261.   for (const s of ANCIENT) {
  1262.     options.actions["Change Attack Style"]["Select Spell"]["Ancient"][s.name] = null;
  1263.   }
  1264.  
  1265.   //add pet names
  1266.   for (const pet of PETS) {
  1267.     const name = `${pet.name.split(",")[0]} (${pet.acquiredBy})`;
  1268.     options.triggers["Pet Unlocked"][name] = null;
  1269.   }
  1270.  
  1271.   //add skill names
  1272.   Object.keys(CONSTANTS.skill).forEach((a) => {
  1273.     if (isNaN(a)) options.triggers["Skill Level"][a] = "num";
  1274.   });
  1275.   options.triggers["Skill XP"] = options.triggers["Skill Level"];
  1276.   Object.keys(options.triggers["Mastery Level"]).forEach(
  1277.     (skill) => (options.triggers["Mastery Pool %"][skill] = "num")
  1278.   );
  1279.  
  1280.   //add mastery/action names for each skill
  1281.   {
  1282.     Astrology.constellations.forEach((item) => {
  1283.       options.triggers["Mastery Level"]["Astrology"][item.name] = "num";
  1284.       options.actions["Start Skill"]["Astrology"][item.name] = null;
  1285.     });
  1286.     Cooking.recipes.forEach((item) => {
  1287.       options.triggers["Mastery Level"]["Cooking"][items[item.itemID].name] = "num";
  1288.     });
  1289.     options.actions["Start Skill"]["Cooking"]["Active"] = Cooking.recipes.reduce((obj, a) => {
  1290.       obj[items[a.itemID].name] = null;
  1291.       return obj;
  1292.     }, {});
  1293.     options.actions["Start Skill"]["Cooking"]["Passive"] = options.actions["Start Skill"]["Cooking"]["Active"];
  1294.  
  1295.     Crafting.recipes.forEach((item) => {
  1296.       options.triggers["Mastery Level"]["Crafting"][items[item.itemID].name] = "num";
  1297.       options.actions["Start Skill"]["Crafting"][items[item.itemID].name] = null;
  1298.     });
  1299.  
  1300.     items.forEach((item) => {
  1301.       if (item.type == "Seeds") {
  1302.         options.triggers["Mastery Level"]["Farming"][item.name] = "num";
  1303.       }
  1304.     });
  1305.  
  1306.     items.forEach((item) => {
  1307.       if (item.type == "Logs") {
  1308.         options.triggers["Mastery Level"]["Firemaking"][item.name] = "num";
  1309.         options.actions["Start Skill"]["Firemaking"][item.name] = null;
  1310.       }
  1311.     });
  1312.  
  1313.     Fishing.data.forEach((item) => {
  1314.       options.triggers["Mastery Level"]["Fishing"][items[item.itemID].name] = "num";
  1315.       options.actions["Start Skill"]["Fishing"][items[item.itemID].name] = null;
  1316.     });
  1317.  
  1318.     items.forEach((item) => {
  1319.       if (item.type == "Logs") {
  1320.         options.triggers["Mastery Level"]["Woodcutting"][item.name] = "num";
  1321.         options.actions["Start Skill"]["Woodcutting"][item.name] = {};
  1322.       }
  1323.     });
  1324.     for (const log in options.actions["Start Skill"]["Woodcutting"]) {
  1325.       Object.keys(options.actions["Start Skill"]["Woodcutting"]).forEach(
  1326.         (a) => (options.actions["Start Skill"]["Woodcutting"][log][a] = null)
  1327.       );
  1328.     }
  1329.  
  1330.     Fletching.recipes.forEach((item) => {
  1331.       options.triggers["Mastery Level"]["Fletching"][items[item.itemID].name] = "num";
  1332.       options.actions["Start Skill"]["Fletching"][items[item.itemID].name] = null;
  1333.     });
  1334.     options.actions["Start Skill"]["Fletching"]["Arrow Shafts"] = {};
  1335.     for (const log in options.actions["Start Skill"]["Woodcutting"]) {
  1336.       options.actions["Start Skill"]["Fletching"]["Arrow Shafts"][log] = null;
  1337.     }
  1338.  
  1339.     Herblore.potions.forEach((item) => {
  1340.       options.triggers["Mastery Level"]["Herblore"][item.name] = "num";
  1341.       options.actions["Start Skill"]["Herblore"][item.name] = null;
  1342.     });
  1343.  
  1344.     Agility.obstacles.forEach((item) => {
  1345.       options.triggers["Mastery Level"]["Agility"][item.name] = "num";
  1346.     });
  1347.  
  1348.     Mining.rockData.forEach((item) => {
  1349.       options.triggers["Mastery Level"]["Mining"][item.name] = "num";
  1350.       options.actions["Start Skill"]["Mining"][item.name] = null;
  1351.     });
  1352.  
  1353.     Runecrafting.recipes.forEach((item) => {
  1354.       options.triggers["Mastery Level"]["Runecrafting"][items[item.itemID].name] = "num";
  1355.       options.actions["Start Skill"]["Runecrafting"][items[item.itemID].name] = null;
  1356.     });
  1357.  
  1358.     Smithing.recipes.forEach((item) => {
  1359.       options.triggers["Mastery Level"]["Smithing"][items[item.itemID].name] = "num";
  1360.       options.actions["Start Skill"]["Smithing"][items[item.itemID].name] = null;
  1361.     });
  1362.  
  1363.     Thieving.npcs.forEach((npc) => {
  1364.       options.triggers["Mastery Level"]["Thieving"][npc.name] = "num";
  1365.       options.actions["Start Skill"]["Thieving"][npc.name] = null;
  1366.     });
  1367.  
  1368.     Summoning.marks.forEach((item) => {
  1369.       options.triggers["Mastery Level"]["Summoning"][items[item.itemID].name] = "num";
  1370.       if (items[item.itemID].equipRequirements.length == 1) {
  1371.         options.actions["Start Skill"]["Summoning"][items[item.itemID].name] = null;
  1372.       } else {
  1373.         options.actions["Start Skill"]["Summoning"][items[item.itemID].name] = {};
  1374.         items[item.itemID].equipRequirements.forEach((recipe) => {
  1375.           const ingredient = recipe.slice(-1)[0].id;
  1376.           options.actions["Start Skill"]["Summoning"][items[item.itemID].name][items[ingredient].name] = null;
  1377.         });
  1378.       }
  1379.     });
  1380.   }
  1381.  
  1382.   //agility obstacles
  1383.   options.actions["Build Agility Obstacle"] = Agility.obstacles.reduce((obj, a) => {
  1384.     if (!obj.hasOwnProperty(a.category + 1)) obj[a.category + 1] = {};
  1385.     obj[a.category + 1][a.name] = null;
  1386.     return obj;
  1387.   }, {});
  1388.   Object.keys(options.actions["Build Agility Obstacle"]).forEach(
  1389.     (a) => (options.actions["Remove Agility Obstacle"][a] = null)
  1390.   );
  1391.  
  1392.   //potions
  1393.   options.actions["Use Potion"] = items.reduce((obj, item) => {
  1394.     if (item.type == "Potion") obj[item.name] = null;
  1395.     return obj;
  1396.   }, {});
  1397.  
  1398.   //prayer actions
  1399.   PRAYER.forEach((prayer) => (options.actions["Activate Prayers"][prayer.name] = {}));
  1400.   for (const prayer1 in options.actions["Activate Prayers"]) {
  1401.     PRAYER.forEach((prayer) => (options.actions["Activate Prayers"][prayer1][prayer.name] = null));
  1402.     options.actions["Activate Prayers"][prayer1]["None"] = null;
  1403.   }
  1404.   options.actions["Activate Prayers"]["None"] = null;
  1405.  
  1406.   //add altmagic names
  1407.   AltMagic.spells.forEach((spell) => {
  1408.     options.actions["Start Skill"]["Magic"][spell.name] = {};
  1409.     if (spell.consumes === 3) {
  1410.       for (const item of AltMagic.smithingBarRecipes) {
  1411.         options.actions["Start Skill"]["Magic"][spell.name][items[item.itemID].name] = null;
  1412.       }
  1413.     } else if (spell.consumes === 1) {
  1414.       Fishing.junkItems.forEach((a) => (options.actions["Start Skill"]["Magic"][spell.name][items[a].name] = null));
  1415.     } else if (spell.consumes === 0) {
  1416.       options.actions["Start Skill"]["Magic"][spell.name] = options.actions["Sell Item"];
  1417.     } else options.actions["Start Skill"]["Magic"][spell.name] = null;
  1418.   });
  1419.  
  1420.   //add food and ammo names
  1421.   for (const a of items.filter((a) => a.canEat)) {
  1422.     options.triggers["Equipped Item Quantity"][a.name] = "num";
  1423.     options.actions["Equip Item"][a.name] = null;
  1424.   }
  1425.   for (const a of items.filter(
  1426.     (a) => a.hasOwnProperty("validSlots") && (a.validSlots[0] == "Quiver" || a.validSlots[0] == "Summon1")
  1427.   ))
  1428.     options.triggers["Equipped Item Quantity"][a.name] = "num";
  1429.  
  1430.   //edit buyShopItem  function so that it returns boolean based on if it met requirements
  1431.   eval(
  1432.     buyShopItem
  1433.       .toString()
  1434.       .replace(/}\s*}$/, "return canBuy}}")
  1435.       .replace(/^function (\w+)/, "window.$1 = function")
  1436.   );
  1437.  
  1438.   //add shop items
  1439.   for (const category in SHOP) {
  1440.     SHOP[category].forEach((item, id) => {
  1441.       let name = item.name;
  1442.       if (name == "Extra Equipment Set") {
  1443.         item.cost.gp > 0 ? (name += " (GP)") : (name += " (SC)");
  1444.       }
  1445.       if (category == "Materials" || category == "Gloves") {
  1446.         shop[name] = {
  1447.           buy: (qty) => {
  1448.             updateBuyQty(qty);
  1449.             return buyShopItem(category, id, true);
  1450.           },
  1451.         };
  1452.         options.actions["Buy Item"][name] = "num";
  1453.       } else {
  1454.         shop[name] = { buy: () => buyShopItem(category, id, true) };
  1455.         options.actions["Buy Item"][name] = null;
  1456.       }
  1457.     });
  1458.   }
  1459.  
  1460.   //add monster/dungeon names
  1461.   {
  1462.     //collect monster IDs
  1463.     const monsterIDs = [];
  1464.     for (const area of combatAreas) monsterIDs.push(...area.monsters);
  1465.     for (const area of slayerAreas) monsterIDs.push(...area.monsters);
  1466.     //add names to array
  1467.     for (const monster of monsterIDs) options.actions["Start Combat"][MONSTERS[monster].name] = null;
  1468.     for (const dungeon of DUNGEONS) options.actions["Start Combat"][dungeon.name] = null;
  1469.     for (const monster of MONSTERS) options.triggers["Enemy in Combat"][monster.name] = null;
  1470.   }
  1471.  
  1472.   //add equippable items
  1473.   for (const a of items.filter((a) => a.hasOwnProperty("validSlots"))) {
  1474.     options.actions["Equip Item"][a.name] = null;
  1475.     options.actions["Unequip Item"][a.name] = null;
  1476.   }
  1477.  
  1478.   //add in sidebar item
  1479.   document.getElementsByClassName("bank-space-nav")[0].parentNode.parentNode.insertAdjacentHTML(
  1480.     "afterend",
  1481.     `<li class="nav-main-item">
  1482.   <a class="nav-main-link nav-compact" style="cursor: pointer;">
  1483.     <img class="nav-img" src="assets/media/skills/prayer/mystic_lore.svg">
  1484.     <span class="nav-main-link-name">Action Queue</span>
  1485.     <small id="current-queue" style="color: rgb(210, 106, 92);">inactive</small>
  1486.   </a>
  1487. </li>`
  1488.   );
  1489.   //add click for sidebar item
  1490.   $("li.nav-main-item:contains(Action Queue)")[0].addEventListener("click", () => actionTab());
  1491.  
  1492.   const htmlCollection = $('div[onclick^="changePage"]');
  1493.   for (let i = 0; i < htmlCollection.length; i++) htmlCollection[i].addEventListener("click", () => hideActionTab());
  1494.  
  1495.   //add main html
  1496.   document.getElementById("main-container").insertAdjacentHTML("beforeend", aqHTML);
  1497.  
  1498.   //add button clicks
  1499.   document.getElementById("aq-pause").addEventListener("click", () => togglePause());
  1500.   document.getElementById("aq-download").addEventListener("click", () => downloadActions());
  1501.   document.getElementById("aq-mastery-config").addEventListener("click", () => masteryPopup(true));
  1502.   document.getElementById("aq-loop-enable").addEventListener("click", () => toggleLoop(true));
  1503.   document.getElementById("aq-loop-disable").addEventListener("click", () => toggleLoop(false));
  1504.   document.getElementById("aq-mastery-enable").addEventListener("click", () => toggleMastery(true));
  1505.   document.getElementById("aq-mastery-disable").addEventListener("click", () => toggleMastery(false));
  1506.   document.getElementById("aq-cancel").addEventListener("click", () => cancelEdit());
  1507.   document.getElementById("aq-delete-all").addEventListener("click", () => clearQueue());
  1508.   document.getElementById("aq-save-edit").addEventListener("click", () => submitEdit());
  1509.   document.getElementById("aq-form").addEventListener("submit", (e) => {
  1510.     e.preventDefault();
  1511.     submitForm();
  1512.   });
  1513.   document.getElementById("aq-item-container").parentNode.children[1].addEventListener("submit", (e) => {
  1514.     e.preventDefault();
  1515.     importActions();
  1516.   });
  1517.   for (const menu in validInputs) {
  1518.     validInputs[menu].forEach((a, i) => {
  1519.       document.getElementById(`aq-text${menu}${i}`).addEventListener("input", () => {
  1520.         dropdowns(menu);
  1521.       });
  1522.     });
  1523.   }
  1524.   document.getElementById("aq-skill-list").addEventListener("change", () => updateMasteryConfig());
  1525.   document.getElementById("aq-checkpoint-list").addEventListener("change", () => updateMasteryConfig(false));
  1526.   document.getElementById("aq-mastery-strategy").addEventListener("change", () => updateMasteryConfig(false));
  1527.   document.getElementById("aq-base").addEventListener("change", () => updateMasteryConfig(false));
  1528.   document.getElementById("aq-config-close").addEventListener("click", () => masteryPopup(false));
  1529.   document.getElementById(`aq-mastery-array`).addEventListener("input", () => updateMasteryConfig(false));
  1530.  
  1531.   //fills category lists
  1532.   Object.keys(options.triggers).forEach((a) =>
  1533.     document.getElementById("aq-listA0").insertAdjacentHTML("beforeend", `<option>${a}</option>`)
  1534.   );
  1535.   Object.keys(options.actions).forEach((a) =>
  1536.     document.getElementById("aq-listB0").insertAdjacentHTML("beforeend", `<option>${a}</option>`)
  1537.   );
  1538.  
  1539.   //add event listener for dragging trigger blocks
  1540.   const triggerContainer = document.getElementById("aq-item-container");
  1541.   triggerContainer.addEventListener("dragover", (e) => {
  1542.     e.preventDefault();
  1543.     const draggable = document.querySelector(".t-drag");
  1544.     if (!draggable || document.querySelector(".a-drag") != null) return;
  1545.     const afterElement = getDragAfterElement(triggerContainer, e.clientY, ".aq-item");
  1546.     if (afterElement == null) {
  1547.       triggerContainer.appendChild(draggable);
  1548.     } else {
  1549.       triggerContainer.insertBefore(draggable, afterElement);
  1550.     }
  1551.   });
  1552.  
  1553.   //mastery stuff
  1554.   for (let i = 1; i < 100; i++) {
  1555.     lvlIndex[i] = exp.level_to_xp(i) + 1;
  1556.   }
  1557.   for (const skill in MASTERY) {
  1558.     masteryConfig[skill] = {
  1559.       checkpoint: 0.95,
  1560.       prio: false,
  1561.       base: 87,
  1562.       arr: [],
  1563.     };
  1564.     masteryClone[skill] = {
  1565.       pool: MASTERY[skill].pool,
  1566.       lvl: [],
  1567.     };
  1568.     updateMasteryLvl(skill);
  1569.   }
  1570.  
  1571.   for (const name in CONSTANTS.skill) {
  1572.     if (Object.keys(MASTERY).includes(`${CONSTANTS.skill[name]}`))
  1573.       document
  1574.         .getElementById("aq-skill-list")
  1575.         .insertAdjacentHTML("beforeend", `<option value="${CONSTANTS.skill[name]}">${name}</option>`);
  1576.   }
  1577.   for (let i = 60; i < 88; i++)
  1578.     document.getElementById("aq-base").insertAdjacentHTML("beforeend", `<option value="${i}">${i}</option>`);
  1579.   tooltips.masteryConfig = [
  1580.     tippy(document.getElementById("aq-checkpoint-list"), {
  1581.       content: "Minimum pool % to maintain",
  1582.       animation: false,
  1583.     }),
  1584.     tippy(document.getElementById("aq-mastery-strategy"), {
  1585.       content: "Mastery pool spending strategy",
  1586.       animation: false,
  1587.     }),
  1588.     tippy(document.getElementById("aq-base"), {
  1589.       content: "Target mastery level for custom priority list",
  1590.       animation: false,
  1591.     }),
  1592.   ];
  1593.  
  1594.   window.masteryIDs = {};
  1595.   for (const skillName in options.triggers["Mastery Level"]) {
  1596.     masteryIDs[skillName] = {};
  1597.     for (const name in options.triggers["Mastery Level"][skillName])
  1598.       masteryIDs[skillName][name] = fetchMasteryID(skillName, name);
  1599.   }
  1600.  
  1601.   //load locally stored action queue if it exists
  1602.   loadLocalSave();
  1603.   console.log("Action Queue loaded");
  1604. }
  1605.  
  1606. function triggerCheck() {
  1607.   let result = true;
  1608.   if (currentActionIndex >= actionQueueArray.length) {
  1609.     if (queueLoop && actionQueueArray.length > 0) {
  1610.       currentActionIndex = 0;
  1611.       updateQueue();
  1612.       return;
  1613.     } else {
  1614.       clearInterval(triggerCheckInterval);
  1615.       triggerCheckInterval = null;
  1616.       updateTextColour("stop");
  1617.       return;
  1618.     }
  1619.   }
  1620.   if (actionQueueArray[currentActionIndex].trigger()) {
  1621.     actionQueueArray[currentActionIndex].action.forEach((action, i) => {
  1622.       result = action.start();
  1623.       document.getElementById(actionQueueArray[currentActionIndex].elementID).children[1].children[
  1624.         i
  1625.       ].children[1].children[0].style.display = result ? "none" : "";
  1626.     });
  1627.     currentActionIndex + 1 >= actionQueueArray.length && queueLoop ? (currentActionIndex = 0) : currentActionIndex++;
  1628.     updateQueue();
  1629.   }
  1630. }
  1631.  
  1632. /**
  1633.  * Updates colour and text in sidebar
  1634.  * @param {string} type ("start" || "stop" || "pause")
  1635.  */
  1636. function updateTextColour(type) {
  1637.   switch (type) {
  1638.     case "start":
  1639.       document.getElementById("current-queue").style.color = "#46c37b";
  1640.       document.getElementById("current-queue").innerHTML = "running";
  1641.       break;
  1642.     case "stop":
  1643.       document.getElementById("current-queue").style.color = "#d26a5c";
  1644.       document.getElementById("current-queue").innerHTML = "inactive";
  1645.       break;
  1646.     case "pause":
  1647.       document.getElementById("current-queue").style.color = "#f3b760";
  1648.       document.getElementById("current-queue").innerHTML = "paused";
  1649.   }
  1650. }
  1651.  
  1652. function updateQueue() {
  1653.   actionQueueArray.forEach((action, index) => {
  1654.     const element = document.getElementById(action.elementID);
  1655.     if (index === currentActionIndex) {
  1656.       for (let i = 0; i < element.children[1].children.length; i++) {
  1657.         element.children[1].children[i].children[1].children[0].style.display = "none";
  1658.       }
  1659.       element.style.backgroundColor = "#385a0b";
  1660.     } else element.style.backgroundColor = "";
  1661.   });
  1662. }
  1663.  
  1664. function toggleLoop(start) {
  1665.   queueLoop = start;
  1666. }
  1667.  
  1668. function togglePause() {
  1669.   queuePause = !queuePause;
  1670.   if (queuePause) {
  1671.     clearInterval(triggerCheckInterval);
  1672.     triggerCheckInterval = null;
  1673.     document.getElementById("aq-pause").innerHTML = "Unpause";
  1674.     document.getElementById("aq-pause").classList.add("aq-green");
  1675.     document.getElementById("aq-pause").classList.remove("aq-yellow");
  1676.     updateTextColour("pause");
  1677.   } else {
  1678.     if (actionQueueArray.length > 0) {
  1679.       updateQueue();
  1680.       triggerCheckInterval = setInterval(() => {
  1681.         triggerCheck();
  1682.       }, 1000);
  1683.       updateTextColour("start");
  1684.     } else {
  1685.       updateTextColour("stop");
  1686.     }
  1687.     document.getElementById("aq-pause").innerHTML = "Pause";
  1688.     document.getElementById("aq-pause").classList.add("aq-yellow");
  1689.     document.getElementById("aq-pause").classList.remove("aq-green");
  1690.   }
  1691. }
  1692.  
  1693. let loadCheckInterval = setInterval(() => {
  1694.   if (isLoaded) {
  1695.     clearInterval(loadCheckInterval);
  1696.     loadAQ();
  1697.   }
  1698. }, 200);
  1699.  
  1700. function autoSave() {
  1701.   const saveData = {
  1702.     index: currentActionIndex,
  1703.     data: [],
  1704.     loop: queueLoop,
  1705.     mastery: manageMasteryInterval === null ? false : true,
  1706.   };
  1707.   for (const action of actionQueueArray) {
  1708.     let actionList = [];
  1709.     action.action.forEach((a) => actionList.push(a.data));
  1710.     saveData.data.push([...action.data, actionList]);
  1711.   }
  1712.   window.localStorage.setItem("AQSAVE" + currentCharacter, JSON.stringify(saveData));
  1713.   window.localStorage.setItem("AQMASTERY", JSON.stringify(masteryConfig));
  1714. }
  1715.  
  1716. //autosave every ~minute
  1717. setInterval(() => {
  1718.   autoSave();
  1719. }, 59550);
  1720.  
  1721. function loadLocalSave() {
  1722.   const obj = JSON.parse(window.localStorage.getItem("AQSAVE" + currentCharacter));
  1723.   const config = JSON.parse(window.localStorage.getItem("AQMASTERY"));
  1724.   if (config != null) {
  1725.     for (const skill in config) {
  1726.       masteryConfig[skill] = config[skill];
  1727.     }
  1728.   }
  1729.  
  1730.   if (obj === null) return;
  1731.   if (obj.loop) {
  1732.     toggleLoop(true);
  1733.     document.getElementById("aq-loop-enable").checked = true;
  1734.   }
  1735.   if (obj.mastery) {
  1736.     toggleMastery(true);
  1737.     document.getElementById("aq-mastery-enable").checked = true;
  1738.   }
  1739.   if (obj.data.length > 0) togglePause();
  1740.   currentActionIndex = obj.index;
  1741.   for (const params of obj.data) {
  1742.     if (params.length == 6) {
  1743.       const newAction = new Action(...params.slice(0, 5));
  1744.       params[5].forEach((data) => {
  1745.         newAction.action.push({
  1746.           elementID: `AQ${nameIncrement++}`,
  1747.           data,
  1748.           start: setAction(...data),
  1749.           description: actionDescription(...data),
  1750.         });
  1751.       });
  1752.       addToQueue(newAction);
  1753.     } else {
  1754.       addToQueue(new Action(...params));
  1755.     }
  1756.   }
  1757.   updateQueue();
  1758. }
  1759.  
  1760. function setCurrentAction(id) {
  1761.   const index = actionQueueArray.findIndex((a) => a.elementID == id);
  1762.   if (index >= 0) {
  1763.     currentActionIndex = index;
  1764.     updateQueue();
  1765.   }
  1766. }
  1767.  
  1768. function importActions() {
  1769.   const string = document.getElementById("aq-pastebin").value;
  1770.   if (!queuePause && actionQueueArray.length === 0) togglePause();
  1771.   let arr = [];
  1772.   try {
  1773.     arr = JSON.parse(string.trim());
  1774.     if (!Array.isArray(arr)) return false;
  1775.     for (const params of arr) {
  1776.       try {
  1777.         let newAction = null;
  1778.         if (params.length == 10) {
  1779.           newAction = new Action(...params);
  1780.         } else if (params.length == 6) {
  1781.           newAction = new Action(...params.slice(0, 5));
  1782.           params[5].forEach((data) => {
  1783.             newAction.action.push({
  1784.               elementID: `AQ${nameIncrement++}`,
  1785.               data,
  1786.               start: setAction(...data),
  1787.               description: actionDescription(...data),
  1788.             });
  1789.           });
  1790.         }
  1791.         if (
  1792.           !newAction.description.includes("undefined") &&
  1793.           !newAction.description.includes("null") &&
  1794.           typeof newAction.trigger == "function" &&
  1795.           newAction.action.every((a) => {
  1796.             return (
  1797.               !a.description.includes("undefined") && !a.description.includes("null") && typeof a.start == "function"
  1798.             );
  1799.           })
  1800.         )
  1801.           addToQueue(newAction);
  1802.       } catch {}
  1803.     }
  1804.     document.getElementById("aq-pastebin").value = "";
  1805.     updateQueue();
  1806.   } catch (e) {
  1807.     console.error(e);
  1808.   } finally {
  1809.     return false;
  1810.   }
  1811. }
  1812.  
  1813. function downloadActions() {
  1814.   const saveData = [];
  1815.   for (const action of actionQueueArray) {
  1816.     let actionList = [];
  1817.     action.action.forEach((a) => actionList.push(a.data));
  1818.     saveData.push([...action.data, actionList]);
  1819.   }
  1820.   let file = new Blob([JSON.stringify(saveData)], {
  1821.     type: "text/plain",
  1822.   });
  1823.   if (window.navigator.msSaveOrOpenBlob) window.navigator.msSaveOrOpenBlob(file, "Melvor_Action_Queue.txt");
  1824.   else {
  1825.     var a = document.createElement("a"),
  1826.       url = URL.createObjectURL(file);
  1827.     a.href = url;
  1828.     a.download = "Melvor_Action_Queue.txt";
  1829.     document.body.appendChild(a);
  1830.     a.click();
  1831.     setTimeout(function () {
  1832.       document.body.removeChild(a);
  1833.       window.URL.revokeObjectURL(url);
  1834.     }, 0);
  1835.   }
  1836. }
  1837.  
  1838. function updateMasteryLvl(skill) {
  1839.   MASTERY[skill].xp.forEach((xp, i) => {
  1840.     let level = 1;
  1841.     while (xp >= lvlIndex[level + 1]) level++;
  1842.     masteryClone[skill].lvl[i] = level;
  1843.   });
  1844.   masteryClone[skill].completed = masteryClone[skill].lvl.every((a) => a == 99);
  1845.   masteryClone[skill].pool = MASTERY[skill].pool;
  1846. }
  1847.  
  1848. function manageMastery() {
  1849.   for (const skill in MASTERY) {
  1850.     //token claiming
  1851.     const maxPool = MASTERY[skill].xp.length * 500000;
  1852.     const bankID = getBankId(CONSTANTS.item[`Mastery_Token_${SKILLS[skill].name}`]);
  1853.     if (bankID !== -1 && bank[bankID].qty > 0 && MASTERY[skill].pool < maxPool * 0.999) {
  1854.       const maxTokens = Math.floor(((maxPool - MASTERY[skill].pool) * 1000) / maxPool);
  1855.       {
  1856.         let itemID = CONSTANTS.item[`Mastery_Token_${SKILLS[skill].name}`];
  1857.         let qtyToUse = Math.min(bank[bankID].qty, maxTokens);
  1858.         let totalXpToAdd = Math.floor(getMasteryPoolTotalXP(skill) * 0.001) * qtyToUse;
  1859.         addMasteryXPToPool(skill, totalXpToAdd, false, true);
  1860.         updateItemInBank(bankID, itemID, -qtyToUse);
  1861.       }
  1862.     }
  1863.  
  1864.     //exit if pool unchanged
  1865.     if (
  1866.       masteryClone[skill].pool == MASTERY[skill].pool &&
  1867.       MASTERY[skill].pool < maxPool * masteryConfig[skill].checkpoint
  1868.     )
  1869.       continue;
  1870.  
  1871.     //exit if maxed mastery
  1872.     updateMasteryLvl(skill);
  1873.     if (masteryClone[skill].completed) continue;
  1874.  
  1875.     //choose masteryID
  1876.     let masteryID = 0;
  1877.     if (!masteryConfig[skill].prio || masteryClone[skill].lvl.some((a) => a < 60)) {
  1878.       for (let i = 1; i < MASTERY[skill].xp.length; i++) {
  1879.         if (MASTERY[skill].xp[i] < MASTERY[skill].xp[masteryID]) masteryID = i;
  1880.       }
  1881.     } else {
  1882.       const noncompletedPrio = masteryConfig[skill].arr.filter(
  1883.         (a) => masteryClone[skill].lvl[a] < masteryConfig[skill].base
  1884.       );
  1885.       if (noncompletedPrio.length == 0) {
  1886.         //choose lowest of nonprio or lowest of prio if nonprio maxed
  1887.         let arr = MASTERY[skill].xp.map((a, i) => i);
  1888.         for (const x of masteryConfig[skill].arr) arr[x] = null;
  1889.         arr = arr.filter((a) => a != null);
  1890.         if (arr.every((a) => masteryClone[skill].lvl[a] >= 99)) arr = [...masteryConfig[skill].arr];
  1891.         arr.sort((a, b) => MASTERY[skill].xp[a] - MASTERY[skill].xp[b]);
  1892.         masteryID = arr[0];
  1893.       } else {
  1894.         for (const id of masteryConfig[skill].arr) {
  1895.           if (MASTERY[skill].xp[id] == lvlIndex[masteryConfig[skill].base]) {
  1896.             //choose lowest of [nonprio, noncompleted prio]
  1897.             let arr = MASTERY[skill].xp.map((a, i) => i);
  1898.             for (const x of masteryConfig[skill].arr) arr[x] = null;
  1899.             arr = arr.filter((a) => a != null);
  1900.             arr.push(...noncompletedPrio);
  1901.             arr.sort((a, b) => MASTERY[skill].xp[a] - MASTERY[skill].xp[b]);
  1902.             masteryID = arr[0];
  1903.             break;
  1904.           } else if (masteryClone[skill].lvl[id] < masteryConfig[skill].base) {
  1905.             masteryID = id;
  1906.             break;
  1907.           }
  1908.         }
  1909.       }
  1910.     }
  1911.     if (masteryID == undefined) continue;
  1912.  
  1913.     //level up chosen mastery
  1914.     if (
  1915.       MASTERY[skill].xp[masteryID] < 13034432 &&
  1916.       (MASTERY[skill].pool == maxPool ||
  1917.         MASTERY[skill].pool - lvlIndex[masteryClone[skill].lvl[masteryID] + 1] + MASTERY[skill].xp[masteryID] >
  1918.           masteryConfig[skill].checkpoint * maxPool)
  1919.     ) {
  1920.       if (masteryPoolLevelUp > 1) masteryPoolLevelUp = 1;
  1921.       let xp = lvlIndex[masteryClone[skill].lvl[masteryID] + 1] - MASTERY[skill].xp[masteryID];
  1922.       if (MASTERY[skill].pool >= xp) {
  1923.         addMasteryXP(skill, masteryID, 0, true, xp, false);
  1924.         addMasteryXPToPool(skill, -xp, false, true);
  1925.         updateSpendMasteryScreen(skill, masteryID);
  1926.         //showSpendMasteryXP(skill);
  1927.       }
  1928.       if (skill === CONSTANTS.skill.Fishing) {
  1929.         for (let i = 0; i < Fishing.areas.length; i++) {
  1930.           for (let f = 0; f < Fishing.areas[i].fish.length; f++) {
  1931.             if (Fishing.areas[i].fish[f] === masteryID) {
  1932.               updateFishingMastery(i, f);
  1933.               break;
  1934.             }
  1935.           }
  1936.         }
  1937.       }
  1938.     }
  1939.   }
  1940. }
  1941.  
  1942. function toggleMastery(start) {
  1943.   for (const skill in MASTERY) {
  1944.     masteryClone[skill] = {
  1945.       pool: MASTERY[skill].pool,
  1946.       lvl: [],
  1947.     };
  1948.     updateMasteryLvl(skill);
  1949.   }
  1950.   if (start && manageMasteryInterval === null) {
  1951.     manageMasteryInterval = setInterval(() => {
  1952.       manageMastery();
  1953.     }, 1000);
  1954.   } else if (!start) {
  1955.     clearInterval(manageMasteryInterval);
  1956.     manageMasteryInterval = null;
  1957.   }
  1958. }
  1959.  
  1960. function addToQueue(obj) {
  1961.   actionQueueArray.push(obj);
  1962.   document.getElementById("aq-item-container").insertAdjacentHTML(
  1963.     "beforeend",
  1964.     `<div class="aq-item" id="${obj.elementID}" draggable="true">
  1965.   <div class="aq-item-inner">
  1966.     <p style="margin: auto 0">${obj.description}</p>
  1967.     <div style="min-width: 170px; min-height: 39px; display: flex; justify-content: flex-end;">
  1968.       <button type="button" class="btn aq-arrow aq-grey" style="font-size: 0.875rem;">select</button>
  1969.       <button type="button" class="btn aq-arrow aq-grey" style="padding: 0 0.1rem 0.2rem 0.1rem;">+</button>
  1970.       <button type="button" class="btn aq-arrow aq-grey" style="padding:0 0.09rem;">
  1971.         <svg width="22" height="22" viewBox="0 0 24 24">
  1972.           <path fill-rule="evenodd" clip-rule="evenodd" d="M19.2929 9.8299L19.9409 9.18278C21.353 7.77064 21.353 5.47197 19.9409 4.05892C18.5287 2.64678 16.2292 2.64678 14.817 4.05892L14.1699 4.70694L19.2929 9.8299ZM12.8962 5.97688L5.18469 13.6906L10.3085 18.813L18.0201 11.0992L12.8962 5.97688ZM4.11851 20.9704L8.75906 19.8112L4.18692 15.239L3.02678 19.8796C2.95028 20.1856 3.04028 20.5105 3.26349 20.7337C3.48669 20.9569 3.8116 21.046 4.11851 20.9704Z" fill="currentColor"></path>
  1973.         </svg>
  1974.       </button>
  1975.       <button type="button" class="btn aq-delete btn-danger">X</button>
  1976.     </div>
  1977.   </div>
  1978.   <div style="min-height: 39px; padding-left: 10px;"></div>
  1979. </div>`
  1980.   );
  1981.  
  1982.   //add button clicks
  1983.   const buttons = document.getElementById(obj.elementID).children[0].children[1].children;
  1984.   buttons[0].addEventListener("click", () => setCurrentAction(obj.elementID));
  1985.   buttons[1].addEventListener("click", () => editQueue(obj.elementID, "add"));
  1986.   buttons[2].addEventListener("click", () => editQueue(obj.elementID, "triggers"));
  1987.   buttons[3].addEventListener("click", () => deleteAction(obj.elementID, "trigger"));
  1988.  
  1989.   //add tooltips
  1990.   tooltips[obj.elementID] = [
  1991.     tippy(document.getElementById(obj.elementID).children[0].children[1].children[0], {
  1992.       content: "Set as current trigger",
  1993.       animation: false,
  1994.     }),
  1995.     tippy(document.getElementById(obj.elementID).children[0].children[1].children[1], {
  1996.       content: "Add action",
  1997.       animation: false,
  1998.     }),
  1999.     tippy(document.getElementById(obj.elementID).children[0].children[1].children[2], {
  2000.       content: "Edit trigger",
  2001.       animation: false,
  2002.     }),
  2003.     tippy(document.getElementById(obj.elementID).children[0].children[1].children[3], {
  2004.       content: "Delete trigger & actions",
  2005.       animation: false,
  2006.     }),
  2007.   ];
  2008.   //add eventlisteners for dragging trigger block
  2009.   const element = document.getElementById(obj.elementID);
  2010.   element.addEventListener("dragstart", () => {
  2011.     element.classList.add("t-drag");
  2012.   });
  2013.   element.addEventListener("dragend", () => {
  2014.     reorderQueue();
  2015.     element.classList.remove("t-drag");
  2016.   });
  2017.  
  2018.   //append html for each action
  2019.   obj.action.forEach((action) => {
  2020.     document.getElementById(obj.elementID).children[1].insertAdjacentHTML(
  2021.       "beforeend",
  2022.       `<div id='${action.elementID}' class="aq-item-inner" draggable="true">
  2023.   <p style="margin: auto 0">${action.description}</p>
  2024.   <div style="min-width: 170px; min-height: 39px; display: flex; justify-content: flex-end;">
  2025.     <small style="display: none; margin: auto 0.25rem">action failed</small>
  2026.     <button type="button" class="btn aq-arrow aq-grey" style="padding:0 0.09rem;">
  2027.       <svg width="22" height="22" viewBox="0 0 24 24">
  2028.         <path fill-rule="evenodd" clip-rule="evenodd" d="M19.2929 9.8299L19.9409 9.18278C21.353 7.77064 21.353 5.47197 19.9409 4.05892C18.5287 2.64678 16.2292 2.64678 14.817 4.05892L14.1699 4.70694L19.2929 9.8299ZM12.8962 5.97688L5.18469 13.6906L10.3085 18.813L18.0201 11.0992L12.8962 5.97688ZM4.11851 20.9704L8.75906 19.8112L4.18692 15.239L3.02678 19.8796C2.95028 20.1856 3.04028 20.5105 3.26349 20.7337C3.48669 20.9569 3.8116 21.046 4.11851 20.9704Z" fill="currentColor"></path>
  2029.       </svg>
  2030.     </button>
  2031.     <button type="button" class="btn aq-delete btn-danger">X</button>
  2032.   </div>
  2033. </div>`
  2034.     );
  2035.     //add tooltips
  2036.     tooltips[action.elementID] = [
  2037.       tippy(document.getElementById(action.elementID).children[1].children[1], {
  2038.         content: "Edit Action",
  2039.         animation: false,
  2040.       }),
  2041.       tippy(document.getElementById(action.elementID).children[1].children[2], {
  2042.         content: "Delete Action",
  2043.         animation: false,
  2044.       }),
  2045.     ];
  2046.     //add eventlisteners for dragging actions
  2047.     const element = document.getElementById(action.elementID);
  2048.     element.addEventListener("dragstart", () => {
  2049.       element.classList.add("a-drag");
  2050.     });
  2051.     element.addEventListener("dragend", () => {
  2052.       element.classList.remove("a-drag");
  2053.     });
  2054.     //add button clicks
  2055.     const buttons = element.children[1].children;
  2056.     buttons[1].addEventListener("click", () => editQueue(action.elementID, "actions"));
  2057.     buttons[2].addEventListener("click", () => deleteAction(action.elementID, "action"));
  2058.   });
  2059.  
  2060.   //add eventlistener for dragging actions within trigger blocks
  2061.   const container = document.getElementById(obj.elementID).children[1];
  2062.   container.addEventListener("dragover", (e) => {
  2063.     e.preventDefault();
  2064.     const draggable = document.querySelector(".a-drag");
  2065.     if (!draggable) return;
  2066.     const afterElement = getDragAfterElement(container, e.clientY, ".aq-item-inner");
  2067.     if (afterElement == null) {
  2068.       container.appendChild(draggable);
  2069.     } else {
  2070.       container.insertBefore(draggable, afterElement);
  2071.     }
  2072.   });
  2073.  
  2074.   if (triggerCheckInterval === null && !queuePause) {
  2075.     currentActionIndex = 0;
  2076.     updateQueue();
  2077.     triggerCheckInterval = setInterval(() => {
  2078.       triggerCheck();
  2079.     }, 1000);
  2080.     updateTextColour("start");
  2081.   }
  2082. }
  2083.  
  2084. function deleteAction(id, type) {
  2085.   tooltips[id].forEach((a) => a.destroy());
  2086.   delete tooltips[id];
  2087.   if (type == "trigger") {
  2088.     const i = actionQueueArray.findIndex((a) => a.elementID == id);
  2089.     if (i < 0) return;
  2090.     for (const action of actionQueueArray[i].action) {
  2091.       tooltips[action.elementID].forEach((a) => a.destroy());
  2092.       delete tooltips[action.elementID];
  2093.     }
  2094.     //remove from array
  2095.     actionQueueArray.splice(i, 1);
  2096.     if (currentActionIndex > i) currentActionIndex--;
  2097.     updateQueue();
  2098.   } else if (type == "action") {
  2099.     let i = 0;
  2100.     for (const trigger of actionQueueArray) {
  2101.       i = trigger.action.findIndex((a) => a.elementID == id);
  2102.       if (i < 0) continue;
  2103.       trigger.action.splice(i, 1);
  2104.       break;
  2105.     }
  2106.   }
  2107.   //remove html
  2108.   const element = document.getElementById(id);
  2109.   if (element) element.remove();
  2110. }
  2111.  
  2112. function addAction(id, actionCategory, actionName, skillItem, skillItem2, qty) {
  2113.   let elementID = `AQ${nameIncrement++}`;
  2114.   let description = actionDescription(actionCategory, actionName, skillItem, skillItem2, qty);
  2115.   actionQueueArray
  2116.     .find((a) => a.elementID == id)
  2117.     .action.push({
  2118.       elementID,
  2119.       data: [actionCategory, actionName, skillItem, skillItem2, qty],
  2120.       start: setAction(actionCategory, actionName, skillItem, skillItem2, qty),
  2121.       description,
  2122.     });
  2123.   document.getElementById(id).children[1].insertAdjacentHTML(
  2124.     "beforeend",
  2125.     `<div id='${elementID}' class="aq-item-inner" draggable="true">
  2126.   <p style="margin: auto 0">${description}</p>
  2127.   <div style="min-width: 170px; min-height: 39px; display: flex; justify-content: flex-end;">
  2128.     <small style="display: none; margin: auto 0.25rem">action failed</small>
  2129.     <button type="button" class="btn aq-arrow aq-grey" style="padding:0 0.09rem;">
  2130.       <svg width="22" height="22" viewBox="0 0 24 24">
  2131.         <path fill-rule="evenodd" clip-rule="evenodd" d="M19.2929 9.8299L19.9409 9.18278C21.353 7.77064 21.353 5.47197 19.9409 4.05892C18.5287 2.64678 16.2292 2.64678 14.817 4.05892L14.1699 4.70694L19.2929 9.8299ZM12.8962 5.97688L5.18469 13.6906L10.3085 18.813L18.0201 11.0992L12.8962 5.97688ZM4.11851 20.9704L8.75906 19.8112L4.18692 15.239L3.02678 19.8796C2.95028 20.1856 3.04028 20.5105 3.26349 20.7337C3.48669 20.9569 3.8116 21.046 4.11851 20.9704Z" fill="currentColor"></path>
  2132.       </svg>
  2133.     </button>
  2134.     <button type="button" class="btn aq-delete btn-danger">X</button>
  2135.   </div>
  2136. </div>`
  2137.   );
  2138.   const element = document.getElementById(elementID);
  2139.   //add tooltips
  2140.   tooltips[elementID] = [
  2141.     tippy(element.children[1].children[1], {
  2142.       content: "Edit Action",
  2143.       animation: false,
  2144.     }),
  2145.     tippy(element.children[1].children[2], {
  2146.       content: "Delete Action",
  2147.       animation: false,
  2148.     }),
  2149.   ];
  2150.  
  2151.   //add eventlisteners for dragging
  2152.   element.addEventListener("dragstart", () => {
  2153.     element.classList.add("a-drag");
  2154.   });
  2155.   element.addEventListener("dragend", () => {
  2156.     element.classList.remove("a-drag");
  2157.   });
  2158.   //add button clicks
  2159.   const buttons = element.children[1].children;
  2160.   buttons[1].addEventListener("click", () => editQueue(elementID, "actions"));
  2161.   buttons[2].addEventListener("click", () => deleteAction(elementID, "action"));
  2162. }
  2163.  
  2164. function getDragAfterElement(container, y, type) {
  2165.   const not = type == "aq-item" ? ".t-drag" : ".a-drag";
  2166.   const elements = [...container.querySelectorAll(`${type}:not(${not})`)];
  2167.   return elements.reduce(
  2168.     (closest, child) => {
  2169.       const box = child.getBoundingClientRect();
  2170.       const offset = y - box.top - box.height / 2;
  2171.       if (offset < 0 && offset > closest.offset) {
  2172.         return { offset: offset, element: child };
  2173.       } else {
  2174.         return closest;
  2175.       }
  2176.     },
  2177.     { offset: Number.NEGATIVE_INFINITY }
  2178.   ).element;
  2179. }
  2180.  
  2181. function reorderQueue() {
  2182.   const targetIndex = actionQueueArray[currentActionIndex].elementID;
  2183.   //remove stray dragging classes
  2184.   document
  2185.     .getElementById("aq-item-container")
  2186.     .querySelectorAll(".a-drag")
  2187.     .forEach((a) => a.classList.remove("a-drag"));
  2188.   document
  2189.     .getElementById("aq-item-container")
  2190.     .querySelectorAll(".t-drag")
  2191.     .forEach((a) => a.classList.remove("t-drag"));
  2192.   //sort triggers
  2193.   const triggerOrder = {};
  2194.   [...document.getElementById("aq-item-container").children].forEach((item, index) => (triggerOrder[item.id] = index));
  2195.   actionQueueArray.sort((a, b) => triggerOrder[a.elementID] - triggerOrder[b.elementID]);
  2196.   //sort actions
  2197.   const actionList = actionQueueArray.reduce((a, b) => a.concat(b.action), []);
  2198.   let increment = -1;
  2199.   [...document.getElementById("aq-item-container").querySelectorAll(".aq-item-inner")].forEach((item) => {
  2200.     if (item.id == "") {
  2201.       increment++;
  2202.       actionQueueArray[increment].action = [];
  2203.     } else {
  2204.       actionQueueArray[increment].action.push(actionList.find((a) => a.elementID == item.id));
  2205.     }
  2206.   });
  2207.   //reorder currentActionIndex
  2208.   currentActionIndex = actionQueueArray.findIndex((a) => a.elementID == targetIndex);
  2209. }
  2210.  
  2211. function editQueue(id, type) {
  2212.   cancelEdit(); //reset form
  2213.   currentlyEditing = { id, type };
  2214.   let inputArray = [];
  2215.   let obj = options[type];
  2216.   //set inputArray
  2217.   if (type == "triggers") {
  2218.     inputArray = actionQueueArray.find((a) => a.elementID == id).data.filter((a) => a !== null && a !== "");
  2219.     document.getElementById("aq-edit-form").innerHTML = "Edit Trigger";
  2220.   } else if (type == "actions") {
  2221.     document.getElementById("aq-edit-form").innerHTML = "Edit Action";
  2222.     for (const item of actionQueueArray) {
  2223.       if (item.action.find((a) => a.elementID == id)) {
  2224.         inputArray = item.action.find((a) => a.elementID == id).data.filter((a) => a !== null && a !== "");
  2225.         break;
  2226.       }
  2227.     }
  2228.   } else {
  2229.     document.getElementById("aq-edit-form").innerHTML = "New Action";
  2230.     obj = options.actions;
  2231.   }
  2232.   //set datalist for category
  2233.   document.getElementById("aq-listC0").innerHTML = "";
  2234.   Object.keys(obj).forEach((e) => {
  2235.     document.getElementById("aq-listC0").insertAdjacentHTML("beforeend", `<option>${e}</option>`);
  2236.   });
  2237.  
  2238.   //populate text boxes to edit
  2239.   for (let i = 0; i < inputArray.length; i++) {
  2240.     let textBox;
  2241.     if (i == inputArray.length - 1 && /^\d{1,10}$/.test(inputArray[i])) {
  2242.       textBox = document.getElementById("aq-numC");
  2243.     } else {
  2244.       textBox = document.getElementById(`aq-textC${i}`);
  2245.       //set datalist
  2246.       document.getElementById(`aq-listC${i}`).innerHTML = "";
  2247.       Object.keys(obj).forEach((e) => {
  2248.         document.getElementById(`aq-listC${i}`).insertAdjacentHTML("beforeend", `<option>${e}</option>`);
  2249.       });
  2250.       obj = obj[inputArray[i]];
  2251.     }
  2252.     textBox.value = inputArray[i];
  2253.     textBox.type = "text";
  2254.     validInputs.C[i] = inputArray[i];
  2255.   }
  2256.   const y = Math.max(document.getElementById(id).getBoundingClientRect().top - 255, 0);
  2257.   document.getElementById("aq-edit-container").style.top = `${y}px`;
  2258.   document.getElementById("aq-edit-container").style.display = "";
  2259. }
  2260.  
  2261. function cancelEdit() {
  2262.   document.getElementById("aq-edit-container").style.display = "none";
  2263.   resetForm(["C"]);
  2264. }
  2265.  
  2266. function submitEdit() {
  2267.   const a = document.getElementById("aq-edit-form").innerHTML.includes("Trigger");
  2268.   const arr = [];
  2269.   for (let i = 0; i < validInputs.C.length; i++) arr.push(document.getElementById(`aq-textC${i}`).value);
  2270.   if (a) arr.pop();
  2271.   arr.push(document.getElementById(`aq-numC`).value);
  2272.   if (a) arr.splice(["≥", "≤", ""].includes(arr[2]) ? 3 : 2, 0, "");
  2273.  
  2274.   if (
  2275.     validateInput(
  2276.       a ? options.triggers : options.actions,
  2277.       arr.filter((a) => a !== "")
  2278.     )
  2279.   ) {
  2280.     if (currentlyEditing.type == "add") {
  2281.       addAction(currentlyEditing.id, ...arr);
  2282.     } else if (currentlyEditing.type == "triggers") {
  2283.       const action = new Action(...arr);
  2284.       const i = actionQueueArray.findIndex((a) => a.elementID == currentlyEditing.id);
  2285.       actionQueueArray[i].description = action.description;
  2286.       actionQueueArray[i].trigger = action.trigger;
  2287.       actionQueueArray[i].data = action.data;
  2288.       document.getElementById(currentlyEditing.id).children[0].children[0].innerHTML = action.description;
  2289.     } else {
  2290.       const description = actionDescription(...arr);
  2291.       const start = setAction(...arr);
  2292.       for (const item of actionQueueArray) {
  2293.         const action = item.action.find((a) => a.elementID == currentlyEditing.id);
  2294.         if (action) {
  2295.           action.data = arr;
  2296.           action.start = start;
  2297.           action.description = description;
  2298.           document.getElementById(currentlyEditing.id).children[0].innerHTML = description;
  2299.           break;
  2300.         }
  2301.       }
  2302.     }
  2303.     cancelEdit();
  2304.   }
  2305.   return false;
  2306. }
  2307.  
  2308. function updateMasteryConfig(changeSkill = true) {
  2309.   if (changeSkill) {
  2310.     if (masteryConfigChanges.skill != null) {
  2311.       updateMasteryPriority();
  2312.       let arr =
  2313.         masteryConfigChanges.arr == null
  2314.           ? [...masteryConfig[masteryConfigChanges.skill].arr]
  2315.           : [...masteryConfigChanges.arr];
  2316.       masteryConfig[masteryConfigChanges.skill] = {
  2317.         checkpoint: masteryConfigChanges.checkpoint,
  2318.         prio: masteryConfigChanges.prio,
  2319.         base: masteryConfigChanges.base,
  2320.         arr,
  2321.       };
  2322.     }
  2323.     const skill = document.getElementById("aq-skill-list").value;
  2324.     document.getElementById("aq-checkpoint-list").value = masteryConfig[skill].checkpoint.toString();
  2325.     document.getElementById("aq-mastery-strategy").value = masteryConfig[skill].prio.toString();
  2326.     document.getElementById("aq-base").disabled = !masteryConfig[skill].prio;
  2327.     document.getElementById("aq-mastery-array").disabled = !masteryConfig[skill].prio;
  2328.     document.getElementById("aq-base").value = masteryConfig[skill].base.toString();
  2329.     document.getElementById("aq-mastery-array").value = JSON.stringify(masteryConfig[skill].arr);
  2330.     masteryConfigChanges.skill = null;
  2331.   } else {
  2332.     masteryConfigChanges.skill = document.getElementById("aq-skill-list").value;
  2333.     masteryConfigChanges.checkpoint = parseFloat(document.getElementById("aq-checkpoint-list").value);
  2334.     masteryConfigChanges.prio = JSON.parse(document.getElementById("aq-mastery-strategy").value);
  2335.     masteryConfigChanges.base = parseInt(document.getElementById("aq-base").value);
  2336.     updateMasteryPriority();
  2337.     document.getElementById("aq-base").disabled = !JSON.parse(document.getElementById("aq-mastery-strategy").value);
  2338.     document.getElementById("aq-mastery-array").disabled = !JSON.parse(
  2339.       document.getElementById("aq-mastery-strategy").value
  2340.     );
  2341.   }
  2342. }
  2343.  
  2344. function updateMasteryPriority() {
  2345.   const string = document.getElementById("aq-mastery-array").value;
  2346.   let arr = null;
  2347.   try {
  2348.     arr = JSON.parse(string.trim());
  2349.   } catch {}
  2350.   if (!Array.isArray(arr)) return (masteryConfigChanges.arr = null);
  2351.   arr = [...new Set(arr)].filter((a) => typeof MASTERY[masteryConfigChanges.skill].xp[a] == "number");
  2352.   masteryConfigChanges.arr = [...arr];
  2353. }
  2354.  
  2355. function masteryPopup(open) {
  2356.   if (open) {
  2357.     masteryConfigChanges.skill = null;
  2358.     updateMasteryConfig();
  2359.     document.getElementById("aq-mastery-config-container").style.display = "";
  2360.   } else {
  2361.     updateMasteryConfig();
  2362.     document.getElementById("aq-mastery-config-container").style.display = "none";
  2363.   }
  2364. }
  2365.  
  2366. /**
  2367.  * Function to change active prayers
  2368.  * @param {Array} choice array of prayer IDs
  2369.  */
  2370. function changePrayers(choice = []) {
  2371.   for (const i of player.activePrayers.entries()) {
  2372.     choice.includes(i[0])
  2373.       ? choice.splice(
  2374.           choice.findIndex((a) => a == i[0]),
  2375.           1
  2376.         )
  2377.       : choice.unshift(i[0]);
  2378.   }
  2379.   for (const prayer of choice) player.togglePrayer(prayer);
  2380. }
  2381.  
  2382. /**
  2383.  * Function to delete every action
  2384.  */
  2385. function clearQueue() {
  2386.   for (let i = actionQueueArray.length - 1; i >= 0; i--) {
  2387.     deleteAction(actionQueueArray[i].elementID, "trigger");
  2388.   }
  2389. }
  2390.  
Add Comment
Please, Sign In to add comment