DeKleineKobini / TORN: Armoury Toggle

// ==UserScript==
// @name         TORN: Armoury Toggle
// @version      2.0.0
// @author       DeKleineKobini
// @description  Toggle the armoury to only show available items.
// @namespace    dekleinekobini.armourtoggle
// @require      https://openuserjs.org/src/libs/DeKleineKobini/DKK_Torn_Utilities.js
// @match        https://www.torn.com/factions.php?step=your*
// @license      MIT
// @updateURL    https://openuserjs.org/meta/DeKleineKobini/TORN_Armoury_Toggle.meta.js
// @grant        none
// ==/UserScript==

setDebug(false);

/* --------------------
CODE - EDIT ON OWN RISK
-------------------- */
setPrefixEasy("AT");

var checked = false;

xhrIntercept(function(page, json, uri) {
    if (page != "factions" || !json) return;
    if (!json.items || !json.items.length) return;

    let tab;
    let type = json.items[0].type;
    switch(type) {
        case "Primary":
        case "Secondary":
        case "Melee":
            tab = "Weapons";
            break;
        case "Defensive":
            tab = "Armor";
            break;
    }
    if (!tab) return;

    let aria = $("li[aria-controls|='armoury'][aria-selected=true]").attr("aria-controls");

    var itemList = $("#" + aria);
    if ($(".armourytoggle").length) $("#input-available").remove();

    debug(`Refreshing loaned items at '${aria}'.`);

    observeMutations(itemList[0], ".list-title", true, function() {
        let button = itemList.find(".loaned").not(".t-overflow").first();
        button.html("<input class='armourytoggle' type='checkbox' id='input-available'" + (checked ? " checked" : "") + "> Available");

        button.find("input").click(function() {
            var ele = $("li:has(div[data-role='retrieve'])");

            checked = $(this).is(":checked");
            debug("Changing states.")
            if($(this).is(":checked")){
                ele.hide();
            } else {
                ele.show();
            }
        });

        if (checked) {
            document.getElementById("input-available").checked = checked;
            $("li:has(div[data-role='retrieve'])").hide();
        }
    });
});