User:King Dragonhoff/wikia.js

/*

<<<<<< This script is under construction. >>>>>>

Clash Royale Deck Builder tool
By King Dragonhoff Special thanks to Blaster Niceshot Dependencies - The Statistics section on card articles must have the appropriate ID's.   - id="unit-statistics" should be applied to the div element surrounding the Statistics section. - id="unit-statistics-table" should be applied to the table with the level-dependent statistics. - id="unit-attributes-table" should be applied to the table with the statistics that are the same for all levels of the card. - Remember that an ID must never be used more than once per page. - Cells in the unit-statistics-table must contain a number. If the exact statistic is unknown, enter an estimate along with Template:fact. - The tables on card articles must not contain cells that use the colspan or rowspan attributes. - The header cells in the card tables must remain consistant across the site. (e.g. The cell must remain "Damage per second". It cannot be changed to "DPS"    on a page.) - Template:Card is used to display the card images. - Template:MyBattleDeck has code that allows users to save the deck shown to   one of the save slots on the tool. Maintainance Since this tool retrieves the card statistics and attributes from the wiki articles, this script will typically only need to be modified when new cards are added to the game. - Add new cards to the ccalcInputs function - Add new cards that spawn units on death to the operations for average hitpoints - If the card has any strange exceptions, have the calc check those. - The following templates will need to be updated to account for new cards. - Card - LookupCardRarity - LookupCardMaxLevel (if the max level of a rarity is changed) - Add error catches - warnings section - classify cards - add section for comparing two cards - add counters for each card in the deck - what level of certain troops can the ballistic spells defeat - have MyBattleDeck template check for duplicate cards - base card comparison colors on averages, not numerical position?

// *********************** Variables and functions ************************* var lookupResult = {}; var savedDeck, selectedDeck = "1", retrievedInputString, j; var dataTimeout, errorMsgSent, saveDeckMsgSent; var chosenCardNum, chosenCardLvlPlusOne, chosenCard; var elixirTotal, elixirAverage, elixirBar, elixirBarDiff, c; var hitpointsTotal, hitpointsAverage, hitpointsBar, hitpointsBarDiff, d, dCount, dCountNoX; var dpsTotal, dpsAverage, dpsBar, dpsBarDiff, e; var cardTypeTroop, cardTypeSpell, cardTypeBuilding, h; var dmgTypeSplash, dmgTypeSingle, dmgTypeNone, f; var targetsNone, targetsBuilding, targetsGround, targetsAny, g; var i; // Define input elements function ccalcInputs(type,number) { if (type === "Common") { return 'Common Rare Epic Legendary Archers Arrows Barbarians Bomber Cannon Fire Spirits Goblins Ice Spirit Knight Minion Horde <option value="Minions">Minions <option value="Mortar">Mortar <option value="Royal Giant">Royal Giant <option value="Skeletons">Skeletons <option value="Spear Goblins">Spear Goblins <option value="Tesla">Tesla <option value="Zap">Zap  <select id="ccalc-level' + number + '" name="ccalc-level' + number + '" class="ccalc-level-input"> 1  2  3  4  5  6  7  8  9  10  11  12  13  '; } else if (type === "Rare") { return '<select id="ccalc-rarity' + number + '" name="ccalc-rarity' + number + '"class="ccalc-rarity-input"><option value="Common">Common <option value="Rare" selected>Rare <option value="Epic">Epic <option value="Legendary">Legendary <select id="ccalc-card' + number + '" name="ccalc-card' + number + '" class="ccalc-card-input"><option value="Barbarian Hut" selected>Barbarian Hut <option value="Bomb Tower">Bomb Tower <option value="Elixir Collector">Elixir Collector <option value="Fireball">Fireball <option value="Furnace">Furnace <option value="Giant">Giant <option value="Goblin Hut">Goblin Hut <option value="Hog Rider">Hog Rider <option value="Inferno Tower">Inferno Tower <option value="Mini P.E.K.K.A.">Mini P.E.K.K.A. <option value="Musketeer">Musketeer <option value="Rocket">Rocket <option value="Three Musketeers">Three Musketeers <option value="Tombstone">Tombstone <option value="Valkyrie">Valkyrie <option value="Wizard">Wizard  <select id="ccalc-level' + number + '" name="ccalc-level' + number + '" class="ccalc-level-input"> 1  2  3  4  5  6  7  8  9  10  11  '; } else if (type === "Epic") { return '<select id="ccalc-rarity' + number + '" name="ccalc-rarity' + number + '"class="ccalc-rarity-input"><option value="Common">Common <option value="Rare">Rare <option value="Epic" selected>Epic <option value="Legendary">Legendary <select id="ccalc-card' + number + '" name="ccalc-card' + number + '" class="ccalc-card-input"><option value="Baby Dragon" selected>Baby Dragon <option value="Balloon">Balloon <option value="Bowler">Bowler <option value="Dark Prince">Dark Prince <option value="Freeze">Freeze <option value="Giant Skeleton">Giant Skeleton <option value="Goblin Barrel">Goblin Barrel <option value="Golem">Golem <option value="Guards">Guards <option value="Lightning">Lightning <option value="Mirror">Mirror <option value="P.E.K.K.A.">P.E.K.K.A. <option value="Poison">Poison <option value="Prince">Prince <option value="Rage">Rage <option value="Skeleton Army">Skeleton Army <option value="Witch">Witch <option value="X-Bow">X-Bow  <select id="ccalc-level' + number + '" name="ccalc-level' + number + '" class="ccalc-level-input"> 1  2  3  4  5  6  7  8  '; } else if (type === "Legendary") { return '<select id="ccalc-rarity' + number + '" name="ccalc-rarity' + number + '"class="ccalc-rarity-input"><option value="Common">Common <option value="Rare">Rare <option value="Epic">Epic <option value="Legendary" selected>Legendary <select id="ccalc-card' + number + '" name="ccalc-card' + number + '" class="ccalc-card-input"><option value="Ice Wizard" selected>Ice Wizard <option value="Lava Hound">Lava Hound <option value="Lumberjack">Lumberjack <option value="Miner">Miner <option value="Princess">Princess <option value="Sparky">Sparky <option value="The Log">The Log  <select id="ccalc-level' + number + '" name="ccalc-level' + number + '" class="ccalc-level-input"> 1  2  3  4  5  '; } else { return '<select id="ccalc-rarity' + number + '" name="ccalc-rarity' + number + '"class="ccalc-rarity-input"><option value="Common" selected>Common <option value="Rare">Rare <option value="Epic">Epic <option value="Legendary">Legendary <select id="ccalc-card' + number + '" name="ccalc-card' + number + '" class="ccalc-card-input"><option value="Archers" selected>Archers <option value="Arrows">Arrows <option value="Barbarians">Barbarians <option value="Bomber">Bomber <option value="Cannon">Cannon <option value="Fire Spirits">Fire Spirits <option value="Goblins">Goblins <option value="Knight">Knight <option value="Minion Horde">Minion Horde <option value="Minions">Minions <option value="Mortar">Mortar <option value="Royal Giant">Royal Giant <option value="Skeletons">Skeletons <option value="Spear Goblins">Spear Goblins <option value="Tesla">Tesla <option value="Zap">Zap  <select id="ccalc-level' + number + '" name="ccalc-level' + number + '" class="ccalc-level-input"> 1  2  3  4  5  6  7  8  9  10  11  12  13  '; } } // Data Retrieval Function function getPageData(page) { var property = ''; var attribute = ''; // Code that will execute while AJAX request is running clearTimeout(dataTimeout); dataTimeout = setTimeout(function {       alert("It is taking a long time to retrieve the card's statistics. If the form is not re-enabled soon, check your Internet connection and refresh the page. If this does not seem to be the problem, check the card's wiki page to ensure that it has not been vandalized. If you are unable to fix the problem, contact a member of the wiki's staff.");    }, 15000); $('#ccalc-submit').html(' ').prop("disabled", true); $('#ccalc-save').html(' ').prop("disabled", true); $(".ccalc-rarity-input, .ccalc-card-input").prop("disabled", true); // Test if data for this page has already been retrieved if (lookupResult[page]) { // data already exists clearTimeout(dataTimeout); $('#ccalc-submit').html('Submit').prop("disabled", false); $('#ccalc-save').html('Save Deck to Slot ' + selectedDeck + ' ').prop("disabled", false); $(".ccalc-rarity-input, .ccalc-card-input").prop("disabled", false); } else { // data does not exist // AJAX Request $.get('http://clashroyale.wikia.com/index.php?title=' + page) .done(function(statData) {           lookupResult[page] = {};            $('#unit-attributes-table tbody tr:eq(0) th',statData).each(function(b) { attribute = $(this).clone.children.remove.end.text.trim.toLowerCase; lookupResult[page][attribute] = $('td:eq(' + b + ')',$("#unit-attributes-table tbody tr:eq(1)",statData)).text.trim; });           $('#unit-statistics-table tbody tr:eq(0) th',statData).each(function(i) { property = $(this).clone.children.remove.end.text.trim.toLowerCase; if (i > 0) { lookupResult[page][property] = [0]; $('#unit-statistics-table tbody tr',statData).each(function(a) {                       if (a > 0) {                            lookupResult[page][property].push($('td:eq(' + i + ')',$(this)).text.trim.replace(/\D/g, ""));                            if (a === $('#unit-statistics-table tbody tr',statData).length - 1 && i === $('#unit-statistics-table tbody tr:eq(0) th',statData).length - 1) {                                // Code that will execute                                // after AJAX request has finished and                                // data has been added to lookupResult object                                clearTimeout(dataTimeout);                                $('#ccalc-submit').html('Submit').prop("disabled", false);                                $('#ccalc-save').html('Save Deck to Slot ' + selectedDeck + ' ').prop("disabled", false);                                $(".ccalc-rarity-input, .ccalc-card-input").prop("disabled", false); }                       }                    });                }            });        });    } } // Get basic statistics table of a card function getStatisticsSection(page, rowNum) {    // Code that will execute while AJAX request is running    clearTimeout(dataTimeout);    dataTimeout = setTimeout(function { alert("It is taking a long time to retrieve the card's statistics. If the statistics do not appear soon, check your Internet connection and refresh the page. If this does not seem to be the problem, check the card's wiki page to ensure that it has not been vandalized. If you are unable to fix the problem, contact a member of the wiki's staff."); }, 15000);   $('#ccalc-individual-stats-result').html('<center class="fa fa-spinner fa-pulse" style="color: white; font-size: 24px;"> ');    // AJAX Request    $.get('http://clashroyale.wikia.com/index.php?title=' + page)    .done(function(pageContent) { $("div.table-back",pageContent).children.hide.appendTo("#ccalc-individual-stats-result").fadeIn("slow"); $("#ccalc-individual-stats-result h2").remove; $("#ccalc-individual-stats #unit-statistics-table tr:nth-of-type(" + rowNum + ")").css("background-color", "#ffffb3"); clearTimeout(dataTimeout); $('#ccalc-individual-stats-result center.fa-spinner').remove; }); } // Deck image updating function function refreshDeck(card,index) {   $.getJSON('/api.php?action=parse&text=&format=json', function(n) { var addCardTemplate = n.parse.text['*']; $('td.ccalc-card[data-card-index="' + index + '"]').html(addCardTemplate); }); } // Get deck data from a MyBattleDeck display function userDeckData(attribute,cardNum) {   return $(".ccalc-user-deck-data-selected .user-deck-" + attribute + cardNum).text; } // Card name by number function function cardName(number) {    return $("#ccalc-card" + number).val; } // Card rarity by number function function cardRarity(number) {    return $("#ccalc-rarity" + number).val; } // Card level by number function function cardLevel(number) {    return $("#ccalc-level" + number).val; } // Error Message function function ccerrorMsg {    if (errorMsgSent !== "sent") {        alert("The calculator was unable to retrieve one or more of the cards' statistics. Please check your Internet connection and submit again or refresh the page. If this does not seem to be the problem, check the card's wiki page to ensure that it has not been vandalized. If you are unable to fix the problem, contact a member of the wiki's staff."); }   errorMsgSent = "sent"; } // Card comparison table manipulator function function cardCompareTable(row,cell,mode,input) { var rowPlusOne = Number(row) + 1; var rowNumString = String(rowPlusOne); if (mode == "text") { $("#ccalc-cardComparison tr:nth-of-type(" + rowNumString + ") td:nth-of-type(" + cell + ")").text(input); } else if (mode == "color") { switch(Number(input)) { case 1: input = "#FF9E9E"; break; case 2: input = "#FFC054"; break; case 3: input = "#F6FF78"; break; case 4: input = "#B5FF8A"; break; case 5: input = "#45DE68"; }       $("#ccalc-cardComparison tr:nth-of-type(" + rowNumString + ") td:nth-of-type(" + cell + ")").css("background-color", input); } else if (mode == "get") { return $("#ccalc-cardComparison tr:nth-of-type(" + rowNumString + ") td:nth-of-type(" + cell + ")").text; } } // ****************************** Get Started ****************************** $(document).ready(function {   // Check for saved deck and place inputs accordingly    $('#ccalc-harness1').html(ccalcInputs("Common","1"));    $('#ccalc-harness2').html(ccalcInputs("Common","2"));    $('#ccalc-harness3').html(ccalcInputs("Common","3"));    $('#ccalc-harness4').html(ccalcInputs("Common","4"));    $('#ccalc-harness5').html(ccalcInputs("Common","5"));    $('#ccalc-harness6').html(ccalcInputs("Common","6"));    $('#ccalc-harness7').html(ccalcInputs("Common","7"));    $('#ccalc-harness8').html(ccalcInputs("Common","8"));    $('#ccalc-card1').val("Archers").attr({"data-fallback-val": "Archers", "data-fallback-rarity": "Common"});    $('#ccalc-card2').val("Arrows").attr({"data-fallback-val": "Arrows", "data-fallback-rarity": "Common"});    $('#ccalc-card3').val("Barbarians").attr({"data-fallback-val": "Barbarians", "data-fallback-rarity": "Common"});    $('#ccalc-card4').val("Bomber").attr({"data-fallback-val": "Bomber", "data-fallback-rarity": "Common"}); $('#ccalc-card5').val("Cannon").attr({"data-fallback-val": "Cannon", "data-fallback-rarity": "Common"}); $('#ccalc-card6').val("Fire Spirits").attr({"data-fallback-val": "Fire Spirits", "data-fallback-rarity": "Common"}); $('#ccalc-card7').val("Goblins").attr({"data-fallback-val": "Goblins", "data-fallback-rarity": "Common"}); $('#ccalc-card8').val("Knight").attr({"data-fallback-val": "Knight", "data-fallback-rarity": "Common"}); // Place form buttons $('#ccalc-submit-harness').html('<button type="submit" id="ccalc-submit">Submit '); $('#ccalc-save-harness').html('<button type="button" id="ccalc-save">Save Deck to Slot '); // Deck selection buttons $("#deck-selection .deck-select-button").click(function {       $(this).siblings.removeClass("selected-deck");        $(this).addClass("selected-deck");        selectedDeck = $(this).text;        $(".displaySelectedDeckNum").text(selectedDeck);    }); $(".displaySelectedDeckNum").text(selectedDeck); // ****************************** Save Inputs... ****************************   // For MyBattleDeck displays: show save buttons $(".ccalc-save-user-deck").click(function {       $(this).siblings(".save-user-deck-buttons").slideToggle;    }); // Save from the tool $('#ccalc-save').click(function {       savedDeck = [            {},            {rarity: cardRarity(1), card: cardName(1), level: cardLevel(1)},            {rarity: cardRarity(2), card: cardName(2), level: cardLevel(2)},            {rarity: cardRarity(3), card: cardName(3), level: cardLevel(3)},            {rarity: cardRarity(4), card: cardName(4), level: cardLevel(4)},            {rarity: cardRarity(5), card: cardName(5), level: cardLevel(5)},            {rarity: cardRarity(6), card: cardName(6), level: cardLevel(6)},            {rarity: cardRarity(7), card: cardName(7), level: cardLevel(7)},            {rarity: cardRarity(8), card: cardName(8), level: cardLevel(8)}        ];        localStorage.setItem("ccalcSavedDeck" + selectedDeck, JSON.stringify(savedDeck));    }); // Save from a MyBattleDeck display $('.deck-save-button').click(function {       $(".ccalc-user-deck-data-selected").removeClass("ccalc-user-deck-data-selected");        $(this).parents(".user-battle-deck").children(".ccalc-user-deck-data").addClass("ccalc-user-deck-data-selected");        // Check that all cards are valid        if (userDeckData("rarity","1") == "invalid" || userDeckData("rarity","2") == "invalid" || userDeckData("rarity","3") == "invalid" || userDeckData("rarity","4") == "invalid" || userDeckData("rarity","5") == "invalid" || userDeckData("rarity","6") == "invalid" || userDeckData("rarity","7") == "invalid" || userDeckData("rarity","8") == "invalid") {            alert("Cannot save! One or more of the cards in this deck is invalid.");        } else {            selectedDeck = $(this).text;            savedDeck = [                {},                {rarity: userDeckData("rarity","1"), card: userDeckData("card","1"), level: userDeckData("level","1")}, {rarity: userDeckData("rarity","2"), card: userDeckData("card","2"), level: userDeckData("level","2")}, {rarity: userDeckData("rarity","3"), card: userDeckData("card","3"), level: userDeckData("level","3")}, {rarity: userDeckData("rarity","4"), card: userDeckData("card","4"), level: userDeckData("level","4")}, {rarity: userDeckData("rarity","5"), card: userDeckData("card","5"), level: userDeckData("level","5")}, {rarity: userDeckData("rarity","6"), card: userDeckData("card","6"), level: userDeckData("level","6")}, {rarity: userDeckData("rarity","7"), card: userDeckData("card","7"), level: userDeckData("level","7")}, {rarity: userDeckData("rarity","8"), card: userDeckData("card","8"), level: userDeckData("level","8")} ];           localStorage.setItem("ccalcSavedDeck" + selectedDeck, JSON.stringify(savedDeck)); alert("This deck has been saved to deck slot " + selectedDeck + " on the Deck Builder Tool."); }   });    // ************************* ...and restore them ****************************    $('#deck-selection .deck-select-button').click(function { if (localStorage.getItem("ccalcSavedDeck" + selectedDeck) !== null) { retrievedInputString = localStorage.getItem("ccalcSavedDeck" + selectedDeck); savedDeck = JSON.parse(retrievedInputString); for (j = 1; j < 9; j++) { $('#ccalc-harness' + String(j)).html(ccalcInputs(savedDeck[j].rarity,String(j))); $('#ccalc-card' + String(j)).val(savedDeck[j].card).attr({"data-fallback-val": savedDeck[j].card, "data-fallback-rarity": savedDeck[j].rarity}); $('#ccalc-level' + String(j)).val(savedDeck[j].level); getPageData(savedDeck[j].card); refreshDeck(savedDeck[j].card,j); }       } else { if (saveDeckMsgSent !== "sent") { alert("You have not saved anything to deck slot " + selectedDeck + ". Change the inputs and click the save button to save a deck."); saveDeckMsgSent = "sent"; }       }    });    // ******************* On rarity change, replace inputs *****************    $('#cardCalculator').on('change', '.ccalc-rarity-input', function { var newRarity = this.value; var cardIndex = $(this).parent.attr("data-card-index"); var oldCard = $("#ccalc-card" + cardIndex).attr("data-fallback-val"); var oldCardRarity = $("#ccalc-card" + cardIndex).attr("data-fallback-rarity"); $(this).parent.html(ccalcInputs(newRarity,cardIndex)); // Perform card change functions as if the card selection was changed var changedInput = $("#ccalc-card" + cardIndex); var newCard = $(changedInput).val; var newCardIndex = cardIndex; // If user selects an already-selected card, swap them. var dupCardIndex = $(".ccalc-card-input[data-fallback-val='" + newCard + "']").parent.attr("data-card-index"); if (dupCardIndex) { refreshDeck(oldCard,dupCardIndex); }       $(".ccalc-card-input[data-fallback-val='" + newCard + "']").parent.html(ccalcInputs(oldCardRarity,dupCardIndex)).children(".ccalc-card-input").val(oldCard).attr({"data-fallback-val": oldCard, "data-fallback-rarity": oldCardRarity}); // Replace fallback value, get data, replace card image $(changedInput).attr({"data-fallback-val": newCard, "data-fallback-rarity": $("#ccalc-rarity" + newCardIndex).val}); getPageData(newCard); refreshDeck(newCard,newCardIndex); });   // ******** On card change, get card statistics and change deck image ********    $('#cardCalculator').on('change', '.ccalc-card-input', function { var changedInput = this; var newCard = this.value; var oldCard = $(this).attr("data-fallback-val"); var oldCardRarity = $(this).attr("data-fallback-rarity"); var newCardIndex = $(this).parent.attr('data-card-index'); // If user selects an already-selected card, swap them. var dupCardIndex = $(".ccalc-card-input[data-fallback-val='" + newCard + "']").parent.attr("data-card-index"); if (dupCardIndex) { refreshDeck(oldCard,dupCardIndex); }       $(".ccalc-card-input[data-fallback-val='" + newCard + "']").parent.html(ccalcInputs(oldCardRarity,dupCardIndex)).children(".ccalc-card-input").val(oldCard).attr({"data-fallback-val": oldCard, "data-fallback-rarity": oldCardRarity}); // Replace fallback value, get data, replace card image $(this).attr({"data-fallback-val": newCard, "data-fallback-rarity": $("#ccalc-rarity" + newCardIndex).val}); getPageData(newCard); refreshDeck(newCard,newCardIndex); });   $('.ccalc-card-input').change;    // ******** Show basic statistics table when card in deck is clicked ********    $("td.ccalc-card").click(function { $("#ccalc-individual-stats-result").children.remove; $("#ccalc-individual-stats").slideDown("slow"); chosenCardNum = $(this).attr("data-card-index"); chosenCardLvlPlusOne = Number(cardLevel(chosenCardNum)) + 1; chosenCard = cardName(chosenCardNum); $("#individual-stats-card").text(chosenCard); getStatisticsSection(chosenCard,chosenCardLvlPlusOne); });   // Close the result window for basic statisitcs    $("#ccalc-individual-stats-hide").click(function { $("#ccalc-individual-stats").slideUp("slow"); });   // ************************* Submit and show results ************************    $("#ccalc-submit").click(function { // Check for card stat objects if ($.isEmptyObject(lookupResult[$("#ccalc-card1").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card2").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card3").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card4").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card5").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card6").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card7").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card8").val]) === false) { // Successful Output $("#cardCalculator-result").slideDown("slow"); // **************** Bar: Average Elixir Cost ************************* elixirTotal = 0; for (c = 1; c < 9; c++) { if (isNaN(lookupResult[cardName(c)].cost) === true) { lookupResult[cardName(c)].cost = 2; }               elixirTotal += Number(lookupResult[cardName(c)].cost); }           elixirAverage = elixirTotal / 8; elixirBar = (elixirAverage * 100) / 8; // 8 is the max capcity of the bar elixirBarDiff = 100 - elixirBar; $("#ccalc-averageElixir .bar1").css("width", elixirBar + "%").children(".bar-value").text(round(2,elixirAverage)); $("#ccalc-averageElixir .bar2").css("width", elixirBarDiff + "%"); // ********************* Bar: Average Hitpoints *********************** hitpointsTotal = 0; // Sum card hitpoint values for (d = 1; d < 9; d++) { // Check for count value dCount = String(lookupResult[cardName(d)].count); dCountNoX = dCount.replace(/x/g, ""); if (isNaN(dCountNoX) === true || lookupResult[cardName(d)].count === undefined) { lookupResult[cardName(d)].count = 1; } else { lookupResult[cardName(d)].count = Number(dCountNoX); }               // Make sure the card can have hitpoints if (lookupResult[cardName(d)].type == "Troop" || lookupResult[cardName(d)].type == "Building") { // Check for a card that spawns units on death then check for missing value if (cardName(d) == "Golem") { if (lookupResult[cardName(d)]["golem hitpoints"] !== undefined && lookupResult[cardName(d)]["golemite hitpoints"] !== undefined) { hitpointsTotal += Number(lookupResult[cardName(d)]["golem hitpoints"][cardLevel(d)]) + (2 * Number(lookupResult[cardName(d)]["golemite hitpoints"][cardLevel(d)])); lookupResult[cardName(d)].hitpoints = []; lookupResult[cardName(d)].hitpoints[cardLevel(d)] = Number(lookupResult[cardName(d)]["golem hitpoints"][cardLevel(d)]) + (2 * Number(lookupResult[cardName(d)]["golemite hitpoints"][cardLevel(d)])); } else { ccerrorMsg; }                   } else if (cardName(d) == "Lava Hound") { if (lookupResult[cardName(d)]['lava hound hitpoints'] !== undefined && lookupResult[cardName(d)]['lava pup hitpoints'] !== undefined) { hitpointsTotal += Number(lookupResult[cardName(d)]['lava hound hitpoints'][cardLevel(d)]) + (6 * Number(lookupResult[cardName(d)]['lava pup hitpoints'][cardLevel(d)])); lookupResult[cardName(d)].hitpoints = []; lookupResult[cardName(d)].hitpoints[cardLevel(d)] = Number(lookupResult[cardName(d)]['lava hound hitpoints'][cardLevel(d)]) + (6 * Number(lookupResult[cardName(d)]['lava pup hitpoints'][cardLevel(d)])); } else { ccerrorMsg; }                   } else { if (lookupResult[cardName(d)].hitpoints !== undefined) { hitpointsTotal += Number(lookupResult[cardName(d)].hitpoints[cardLevel(d)]) * Number(lookupResult[cardName(d)].count); } else { ccerrorMsg; }                   }                } else { lookupResult[cardName(d)].hitpoints = []; lookupResult[cardName(d)].hitpoints[cardLevel(d)] = 0; }           }            hitpointsAverage = hitpointsTotal / 8; hitpointsBar = (hitpointsAverage * 100) / 4500; // 4500 is the max capacity of the bar hitpointsBarDiff = 100 - hitpointsBar; $("#ccalc-averageHitpoints .bar1").css("width", hitpointsBar + "%").children(".bar-value").text(round(2,hitpointsAverage)); $("#ccalc-averageHitpoints .bar2").css("width", hitpointsBarDiff + "%"); // ************************ Bar: Average DPS *********************** dpsTotal = 0; // Sum card DPS values for (e = 1; e < 9; e++) { // (Count value was checked and saved to the object by the average hitpoints loop) // Make sure the card can have DPS if (lookupResult[cardName(e)].type == "Troop" || lookupResult[cardName(e)].type == "Building") { // Check for an abnormal card then check for missing value // Golem and Lava Hound spawn units that do damage if (cardName(e) == "Golem") { if (lookupResult[cardName(e)]["golem damage per second"] !== undefined && lookupResult[cardName(e)]["golemite damage per second"] !== undefined) { dpsTotal += Number(lookupResult[cardName(e)]["golem damage per second"][cardLevel(e)]) + (2 * Number(lookupResult[cardName(e)]["golemite damage per second"][cardLevel(e)])); lookupResult[cardName(e)]['damage per second'] = []; lookupResult[cardName(e)]['damage per second'][cardLevel(e)] = Number(lookupResult[cardName(e)]["golem damage per second"][cardLevel(e)]) + (2 * Number(lookupResult[cardName(e)]["golemite damage per second"][cardLevel(e)])); } else { ccerrorMsg; }                   } else if (cardName(e) == "Lava Hound") { if (lookupResult[cardName(e)]['lava hound damage per second'] !== undefined && lookupResult[cardName(e)]['lava pup damage per second'] !== undefined) { dpsTotal += Number(lookupResult[cardName(e)]['lava hound damage per second'][cardLevel(e)]) + (6 * Number(lookupResult[cardName(e)]['lava pup damage per second'][cardLevel(e)])); lookupResult[cardName(e)]['damage per second'] = []; lookupResult[cardName(e)]['damage per second'][cardLevel(e)] = Number(lookupResult[cardName(e)]['lava hound damage per second'][cardLevel(e)]) + (6 * Number(lookupResult[cardName(e)]['lava pup damage per second'][cardLevel(e)])); } else { ccerrorMsg; }                   // Fire Spirits only do damage on death } else if (cardName(e) == "Fire Spirits") { if (lookupResult['Fire Spirits']['area damage'] !== undefined) { dpsTotal += Number(lookupResult['Fire Spirits']['area damage'][cardLevel(e)]) * Number(lookupResult['Fire Spirits'].count); lookupResult[cardName(e)]['damage per second'] = []; lookupResult[cardName(e)]['damage per second'][cardLevel(e)] = Number(lookupResult['Fire Spirits']['area damage'][cardLevel(e)]) * Number(lookupResult['Fire Spirits'].count); } else { ccerrorMsg; }                   // Ice Spirits only do damage on death } else if (cardName(e) == "Ice Spirit") { if (lookupResult['Ice Spirit']['area damage'] !== undefined) { dpsTotal += Number(lookupResult['Ice Spirit']['area damage'][cardLevel(e)]) * Number(lookupResult['Ice Spirit'].count); lookupResult[cardName(e)]['damage per second'] = []; lookupResult[cardName(e)]['damage per second'][cardLevel(e)] = Number(lookupResult['Ice Spirit']['area damage'][cardLevel(e)]) * Number(lookupResult['Ice Spirit'].count); } else { ccerrorMsg; }                   // Inferno Tower damage charges } else if (cardName(e) == "Inferno Tower") { dpsTotal += 200 + (Number(cardLevel(e)) * 20); lookupResult[cardName(e)]['damage per second'] = []; lookupResult[cardName(e)]['damage per second'][cardLevel(e)] = 200 + (Number(cardLevel(e)) * 20); // Spawner building DPS ignored, Elixir Collector does no damage } else if (cardName(e) == "Barbarian Hut" || cardName(e) == "Goblin Hut" || cardName(e) == "Elixir Collector" || cardName(e) == "Furnace" || cardName(e) == "Tombstone") { dpsTotal += 0; lookupResult[cardName(e)]['damage per second'] = []; lookupResult[cardName(e)]['damage per second'][cardLevel(e)] = 0; } else if (lookupResult[cardName(e)]['damage per second'] !== undefined) { dpsTotal += Number(lookupResult[cardName(e)]['damage per second'][cardLevel(e)]) * Number(lookupResult[cardName(e)].count); } else { ccerrorMsg; }               } else { lookupResult[cardName(e)]['damage per second'] = []; lookupResult[cardName(e)]['damage per second'][cardLevel(e)] = 0; }           }            dpsAverage = dpsTotal / 8; dpsBar = (dpsAverage * 100) / 500; // 500 is the max capacity of the bar dpsBarDiff = 100 - dpsBar; $("#ccalc-averageDPS .bar1").css("width", dpsBar + "%").children(".bar-value").text(round(2,dpsAverage)); $("#ccalc-averageDPS .bar2").css("width", dpsBarDiff + "%"); // ********************** Bar: Card Type ********************** cardTypeTroop = 0; cardTypeSpell = 0; cardTypeBuilding = 0; // Count number of each card type for (h = 1; h < 9; h++) { if (lookupResult[cardName(h)].type === "Troop") { cardTypeTroop++; } else if (lookupResult[cardName(h)].type === "Spell") { cardTypeSpell++; } else { cardTypeBuilding++; }           }            cardTypeTroop *= 12.5; cardTypeSpell *= 12.5; cardTypeBuilding *= 12.5; $("#ccalc-cardType .bar1").css("width", cardTypeTroop + "%").attr("data-bar-fill", cardTypeTroop); $("#ccalc-cardType .bar2").css("width", cardTypeSpell + "%").attr("data-bar-fill", cardTypeSpell); $("#ccalc-cardType .bar3").css("width", cardTypeBuilding + "%").attr("data-bar-fill", cardTypeBuilding); // ********************** Bar: Can Target ********************** targetsAny = 0; targetsGround = 0; targetsBuilding = 0; targetsNone = 0; // Count number of each target type for (g = 1; g < 9; g++) { if (lookupResult[cardName(g)].target === "Air & Ground" || lookupResult[cardName(g)].target === "Air and Ground") { targetsAny++; } else if (lookupResult[cardName(g)].target === "Ground") { targetsGround++; } else if (lookupResult[cardName(g)].target === "Building" || lookupResult[cardName(g)].target === "Buildings") { targetsBuilding++; } else { targetsNone++; }           }            targetsAny *= 12.5; targetsGround *= 12.5; targetsBuilding *= 12.5; targetsNone *= 12.5; $("#ccalc-canTarget .bar1").css("width", targetsAny + "%").attr("data-bar-fill", targetsAny); $("#ccalc-canTarget .bar2").css("width", targetsGround + "%").attr("data-bar-fill", targetsGround); $("#ccalc-canTarget .bar3").css("width", targetsBuilding + "%").attr("data-bar-fill", targetsBuilding); $("#ccalc-canTarget .bar4").css("width", targetsNone + "%").attr("data-bar-fill", targetsNone); // ********************** Bar: Damage Type ********************** dmgTypeSplash = 0; dmgTypeSingle = 0; dmgTypeNone = 0; // Count number of each damage type for (f = 1; f < 9; f++) { if ($.isEmptyObject(lookupResult[cardName(f)]['area damage']) === false) { dmgTypeSplash++; } else if ($.isEmptyObject(lookupResult[cardName(f)].damage) === false) { dmgTypeSingle++; } else { dmgTypeNone++; }           }            dmgTypeSplash *= 12.5; dmgTypeSingle *= 12.5; dmgTypeNone *= 12.5; $("#ccalc-damageType .bar1").css("width", dmgTypeSplash + "%").attr("data-bar-fill", dmgTypeSplash); $("#ccalc-damageType .bar2").css("width", dmgTypeSingle + "%").attr("data-bar-fill", dmgTypeSingle); $("#ccalc-damageType .bar3").css("width", dmgTypeNone + "%").attr("data-bar-fill", dmgTypeNone); // *********** Remove certain bars if they are zero. ************           $("#ccalc-analysis-bars .bar-fully-hide").each(function {                if ($(this).attr("data-bar-fill") === "0") {                    $(this).children.css("opacity", "0");                } else {                    $(this).children.css("opacity", "1");                }            }); // **************************** Card Comparison Table **************************** // Add Card Names for (i = 1; i < 9; i++) { cardCompareTable(i,"1","text",cardName(i)); }           // Elixir Cost column var deckElixir = []; for (i = 1; i < 9; i++) { cardCompareTable(i,"2","text",lookupResult[cardName(i)].cost); deckElixir.push(cardCompareTable(i,"2","get")); }           deckElixir.sort(function(a, b){return b-a}); $("#ccalc-cardComparison tr td:nth-of-type(2)").each(function {               if ($(this).text == deckElixir[1]) {$(this).css("background-color", "#FFC054");}                if ($(this).text == deckElixir[2]) {$(this).css("background-color", "#FFC054");}                if ($(this).text == deckElixir[5]) {$(this).css("background-color", "#B5FF8A");}                if ($(this).text == deckElixir[6]) {$(this).css("background-color", "#B5FF8A");}                if ($(this).text == deckElixir[3]) {$(this).css("background-color", "#F6FF78");}                if ($(this).text == deckElixir[4]) {$(this).css("background-color", "#F6FF78");}                if ($(this).text == deckElixir[0]) {$(this).css("background-color", "#FF9E9E");}                if ($(this).text == deckElixir[7]) {$(this).css("background-color", "#45DE68");}            }); // HP column var deckHP = []; for (i = 1; i < 9; i++) { cardCompareTable(i,"4","text",round(0,lookupResult[cardName(i)].hitpoints[cardLevel(i)] * Number(lookupResult[cardName(i)].count))); deckHP.push(cardCompareTable(i,"4","get")); }           deckHP.sort(function(a, b){return a-b}); $("#ccalc-cardComparison tr td:nth-of-type(4)").each(function {               if ($(this).text == deckHP[1]) {$(this).css("background-color", "#FFC054");}                if ($(this).text == deckHP[2]) {$(this).css("background-color", "#FFC054");}                if ($(this).text == deckHP[5]) {$(this).css("background-color", "#B5FF8A");}                if ($(this).text == deckHP[6]) {$(this).css("background-color", "#B5FF8A");}                if ($(this).text == deckHP[3]) {$(this).css("background-color", "#F6FF78");}                if ($(this).text == deckHP[4]) {$(this).css("background-color", "#F6FF78");}                if ($(this).text == deckHP[0]) {$(this).css("background-color", "#FF9E9E");}                if ($(this).text == deckHP[7]) {$(this).css("background-color", "#45DE68");}            }); // HP/Elixir column var deckHPbyCost = []; for (i = 1; i < 9; i++) { cardCompareTable(i,"3","text",round(1,cardCompareTable(i,"4","get") / cardCompareTable(i,"2","get"))); deckHPbyCost.push(cardCompareTable(i,"3","get")); }           deckHPbyCost.sort(function(a, b){return a-b}); $("#ccalc-cardComparison tr td:nth-of-type(3)").each(function {               if ($(this).text == deckHPbyCost[1]) {$(this).css("background-color", "#FFC054");}                if ($(this).text == deckHPbyCost[2]) {$(this).css("background-color", "#FFC054");}                if ($(this).text == deckHPbyCost[5]) {$(this).css("background-color", "#B5FF8A");}                if ($(this).text == deckHPbyCost[6]) {$(this).css("background-color", "#B5FF8A");}                if ($(this).text == deckHPbyCost[3]) {$(this).css("background-color", "#F6FF78");}                if ($(this).text == deckHPbyCost[4]) {$(this).css("background-color", "#F6FF78");}                if ($(this).text == deckHPbyCost[0]) {$(this).css("background-color", "#FF9E9E");}                if ($(this).text == deckHPbyCost[7]) {$(this).css("background-color", "#45DE68");}            }); // DPS column var deckDPS = []; for (i = 1; i < 9; i++) { cardCompareTable(i,"6","text",round(0,lookupResult[cardName(i)]['damage per second'][cardLevel(i)] * Number(lookupResult[cardName(i)].count))); deckDPS.push(cardCompareTable(i,"6","get")); }           deckDPS.sort(function(a, b){return a-b}); $("#ccalc-cardComparison tr td:nth-of-type(6)").each(function {               if ($(this).text == deckDPS[1]) {$(this).css("background-color", "#FFC054");}                if ($(this).text == deckDPS[2]) {$(this).css("background-color", "#FFC054");}                if ($(this).text == deckDPS[5]) {$(this).css("background-color", "#B5FF8A");}                if ($(this).text == deckDPS[6]) {$(this).css("background-color", "#B5FF8A");}                if ($(this).text == deckDPS[3]) {$(this).css("background-color", "#F6FF78");}                if ($(this).text == deckDPS[4]) {$(this).css("background-color", "#F6FF78");}                if ($(this).text == deckDPS[0]) {$(this).css("background-color", "#FF9E9E");}                if ($(this).text == deckDPS[7]) {$(this).css("background-color", "#45DE68");}            }); } else { // This is the else of the original "check for objects" if statement. ccerrorMsg; }   }); });