3jameo3 / HaremHeroes Automatic Redone

// ==UserScript==
// @name         HaremHeroes Automatic Redone
// @namespace    3jameo3
// @version      2.1.2
// @description  Based on Eileen12's old script with some revamps here and there.
// @author       3jameo3
// @match        http*://nutaku.haremheroes.com/*
// @updateURL    https://openuserjs.org/meta/3jameo3/HaremHeroes_Automatic_Redone.meta.js
// @require      https://cdn.jsdelivr.net/js-cookie/2.2.0/js.cookie.js
// @require      https://code.jquery.com/jquery-2.1.1.min.js
// @grant        GM_addStyle
// @license      MIT
// ==/UserScript==
this.$ = this.jQuery = jQuery.noConflict(true);
GM_addStyle('/* The switch - the box around the slider */ .switch { position: relative; display: inline-block; width: 60px; height: 34px; } /* Hide default HTML checkbox */ .switch input {display:none;} /* The slider */ .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; -webkit-transition: .4s; transition: .4s; } input:checked + .slider { background-color: #2196F3; } input:focus + .slider { box-shadow: 0 0 1px #2196F3; } input:checked + .slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); } /* Rounded sliders */ .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; }');

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds) {
      break;
    }
  }
}

var proceedQuest = function () {
  //console.log("Starting auto quest.");
  var currentQuestMunuOption = $("nav div[rel='content'] a:has(.continue_quest)");
  if (currentQuestMunuOption === undefined || currentQuestMunuOption.attr("href") === undefined) {
    console.log("Could not find current quest menu button for verification. Probably it hasn't yet loaded.");
    return;
  }
  // Check if at correct page.
  if (currentQuestMunuOption.attr("href") !== window.location.pathname) {
    // Click on current quest to naviagte to it.
    console.log("Navigating to current quest.");
    sessionStorage.autoLoop = "false";
    window.location = window.location.origin + currentQuestMunuOption.attr("href");
    return;
  }

  // Get the proceed button type
  var proceedButtonMatch = $("#controls button:not([style='display: none;'])");
  console.log("Proceed Button Match == " + proceedButtonMatch);
  var proceedCostEnergy = Number($("#controls .cost span[cur='*']").text());
  console.log("Proceed Cost Energy == " + proceedCostEnergy);
  var proceedCostMoney = Number($("#controls .cost span[cur='$']").text().trim().replace(',', ''));
  console.log("Proceed Cost Money == " + proceedCostMoney);
  var proceedType = proceedButtonMatch.attr("act");
  console.log("Proceed Type == " + proceedType);

  if (proceedButtonMatch.length === 0) {
    console.log("Could not find resume button.");
  }
  else if (proceedType === "free") {
    console.log("Proceeding for free.");
    proceedButtonMatch.click();
  }
  else if (proceedType === "pay") {
    var energyCurrent = Number($("span[hero='energy_quest']").text());
    console.log("Current Energy == " + energyCurrent);
    var moneyCurrent = Number($("div[hero='soft_currency'] span").get(0).innerHTML.trim().replace(',', '').replace(',', '').replace(/\s/g, ""));
    console.log("Current Money == " + moneyCurrent);
    if (proceedCostEnergy <= energyCurrent) {
      // We have energy.
      console.log("Spending " + proceedCostEnergy + " Energy to proceed.");
    }
    else {
      console.log("Quest requires " + proceedCostEnergy + " Energy to proceed.");
      sessionStorage.questRequirement = "*" + proceedCostEnergy;
      return;
    }
    if (proceedCostMoney <= moneyCurrent) {
      // We have money.
      console.log("Spending " + proceedCostMoney + " Money to proceed.");
    }
    else {
      console.log("Spending " + proceedCostMoney + " Money to proceed.");
      sessionStorage.questRequirement = "$" + proceedCostMoney;
      return;
    }
    proceedButtonMatch.click();
    sessionStorage.autoLoop = "false";
    location.reload();
  }
  else if (proceedType === "use_item") {
    console.log("Proceeding by using X" + Number($("#controls .item span").text()) + " of the required item.");
    proceedButtonMatch.click();
  }
  else if (proceedType === "battle") {
    console.log("Proceeding to battle troll...");
    sessionStorage.questRequirement = "battle";
    // Proceed to battle troll.
    proceedButtonMatch.click();
    sessionStorage.autoLoop = "false";
    location.reload();
  }
  else if (proceedType === "end_archive") {
    console.log("Reached end of current archive. Proceeding to next archive.");
    sessionStorage.autoLoop = "false";
    proceedButtonMatch.click();
  }
  else if (proceedType === "end_play") {
    var energyCurrent = Number($("span[hero='energy_quest']").text());
    console.log("Current Energy == " + energyCurrent);
    var moneyCurrent = Number($("div[hero='soft_currency'] span").get(0).innerHTML.trim().replace(',', '').replace(',', '').replace(/\s/g, ""));
    console.log("Current Money == " + moneyCurrent);
    if (proceedCostEnergy <= energyCurrent) {
      // We have energy.
      console.log("Spending " + proceedCostEnergy + " Energy to proceed.");
    }
    else {
      console.log("Quest requires " + proceedCostEnergy + " Energy to proceed.");
      sessionStorage.questRequirement = "*" + proceedCostEnergy;
      return;
    }
    if (proceedCostMoney <= moneyCurrent) {
      // We have money.
      console.log("Spending " + proceedCostMoney + " Money to proceed.");
    }
    else {
      console.log("Spending " + proceedCostMoney + " Money to proceed.");
      sessionStorage.questRequirement = "$" + proceedCostMoney;
      return;
    }
    console.log("Reached end of current play. Proceeding to next play.");
    sessionStorage.autoLoop = "false";
    proceedButtonMatch.click();
  }
  else {
    console.log("Could not identify given resume button.");
    sessionStorage.questRequirement = "unknownQuestButton";

  }
window.location = window.location.origin + $("nav div[rel='content'] a:has(.home)").attr("href");
};

var getSalary = function () {
  try {
    if ($("#harem_whole #harem_left h3").text() === "My Harem" ) {
      window.location = window.location.origin + $("nav div[rel='content'] a:has(.harem)").attr("href");
      console.log("Detected Harem Screen. Fetching Salary");
      var buttonMatch = $("#harem_whole #harem_left button:not([style='display: none;'])");
      var Claim = $("#harem_whole #harem_left button[class='collect_money']");

      if (buttonMatch.length === 0) console.log("Could not find salary button.");
      else if (Claim) {
        console.log("Collecting salary.");
        Claim.click();
        document.cookie = "nextSalaryTime=;";
        //window.location = window.location.origin + $("nav div[rel='content'] a:has(.home)").attr("href");
      }
      else {
        console.log("Could not identify given salary button.");
        sessionStorage.salaryRequirement = "unknownSalaryButton";
      }
    }
    else {
      // Not at Harem screen then goto the Harem screen.
      console.log("Navigating to Harem window.");
      sessionStorage.autoLoop = "false";
      window.location = window.location.origin + $("nav div[rel='content'] a:has(.harem)").attr("href");
      //sleep(1000);
      return;
    }
  }
  catch (ex) {
    console.log("Could not collect salary... " + ex);
  }
};

var doBossBattle = function () {
  var currentPower = Number($("span[hero='energy_fight']").text());
  if (currentPower < 1) {
    //console.log("No power for battle.");
    return;
  }
  // Battles the latest boss.
  // Navigate to latest boss.
  if (window.location.pathname.startsWith("/battle.html")) {
    // On the battle screen.
    doBattle();
  }
  else if (window.location.pathname.startsWith("/quest")) {
    // On some quest screen.
    // Goto this area's screen.
    console.log("Navigating to latest Troll.");
    sessionStorage.autoLoop = "false";
    window.location = window.location.origin + $("#breadcrumbs a[class='back']").last().attr("href");
    return;
  }
  else if (window.location.pathname.startsWith("/world")) {
    // On some world screen.
    // Click on the local Boss's battle button.
    console.log("Entering battle with this troll.");
    sessionStorage.autoLoop = "false";
    window.location = window.location.origin + $("#worldmap a[class='troll_world']").attr("href");
    return;
  }
  else {
    console.log("Navigating to latest Troll.");
    sessionStorage.autoLoop = "false";
    window.location = window.location.origin + $("nav div[rel='content'] a:has(.continue_quest)").attr("href");
    return;
  }
};

var doBattle = function () {
  //console.log("Performing auto battle.");
  var currentPower = Number($("span[hero='energy_fight']").text());
  if (currentPower < 1) {
    //console.log("No power for battle.");
    return;
  }
  // Confirm if on correct screen.
  if ($("#breadcrumbs span").last().text() === "Battle") {
    // On battle page.
    //console.log("On Battle Page.");
    if ($("#arena[class='canvas']").length === 1) {
      // Oponent choose screen
      console.log("On opponent choose screen.");
      // Fight the first opponent in list.
      $(".opponents_arena .sub_block .grey_text_button:contains('Select')")[0].click();
      sessionStorage.autoLoop = "false";
    }
    else if ($("#battle[class='canvas']").length === 1) {
      // Battle screen
      //console.log("On battle screen.");
      var battleButton = $("#battle_middle button[class='green_text_button redesign']");
      var Button = $("#battle_win button[class='blue_text_button']");
      if (battleButton === undefined) return;
      if (battleButton.attr("price_fe") === undefined) {
        console.log("Could not detect battle button price. Maybe its not loaded yet.");
        return;
      }
      if (currentPower >= battleButton.attr("price_fe")) {
        // We have the power.
        battleButton.click();
        // Skip
        setTimeout(function () {
          $("#battle_middle button[rel='skip']").click();
        }, 1000);
        setTimeout(function () {
          Button.click();
        }, 2500);

        if (sessionStorage.questRequirement === "battle") {
          // Battle Done.
          sessionStorage.questRequirement = "none";
        }
      }
      else {
        // We need more power.
        console.log("Battle requires " + battleButton.attr("price_fe") + " power.");
        sessionStorage.battlePowerRequired = battleButton.attr("price_fe");
        if (sessionStorage.questRequirement === "battle") sessionStorage.questRequirement = "P" + battleButton.attr("price_fe");
      }
    }
    else {
      console.log("Could not identify battle screen.");
      Button.click();
      if (sessionStorage.questRequirement === "battle") sessionStorage.questRequirement = "errorInAutoBattle";
      window.location = window.location.origin + $("nav div[rel='content'] a:has(.home)").attr("href");
      return;
    }
  }
  else {
    // Switch to the correct screen
    console.log("Switching to battle screen.");
    window.location = window.location.origin + $("nav div[rel='content'] a:has(.battle)").attr("href");
    sessionStorage.autoLoop = "false";
    return;
  }
};

var updateData = function () {
  //console.log("updating UI");
  sessionStorage.autoSalary = document.getElementById("autoSalaryCheckbox").checked;
  sessionStorage.autoQuest = document.getElementById("autoQuestCheckbox").checked;
  sessionStorage.autoBattle = document.getElementById("autoBattleCheckbox").checked;
  sessionStorage.autoFreePachinko = document.getElementById("autoFreePachinko").checked;
  sessionStorage.autoMissions = document.getElementById("autoMissions").checked;
};

var getPachinko = function () {
  try {
    if ($("#breadcrumbs span").last().text() === "Pachinko") {
      console.log("Detected Pachinko Screen. Fetching Pachinko");
      $("#pachinko button[free=1]")[0].click();
      document.cookie = "nextPachinkoTime=24hrs;max-age=" + 24 * 60 * 60;
    }
    else {
      // Not at Pachinko screen then goto the Pachinko screen.
      console.log("Navigating to Pachinko window.");
      sessionStorage.autoLoop = "false";
      window.location = window.location.origin + $("nav div[rel='content'] a:has(.pachinko)").attr("href");
      return;
    }
  }
  catch (ex) {
    console.log("Could not collect pachinko... " + ex);
  }
};

var getMission = function () {
  //console.log("Auto Missions Running");
  try {
    if ($("#breadcrumbs span").last().text() === "Activities") {
      console.log("Detected mission screen. Accepting a mission");
      var buttonMatch = $("#missions button:not([style='display: none;'])");
      var Accept = $("#missions button[rel^='mission_start']:not([style='display: none;'])");
      /*
      var Finish = $("#missions button[rel^='finish']:not([style='display: none;'])");
      var Present = $("#base_block #end_gift button:not([style='display: none;'])");
      */

      if (buttonMatch.length === 0) console.log("Could not find mission button.");
      else if (Accept) {
        console.log("Starting mission.");
        Accept.click();
        //sleep(1000);
        document.cookie = "nextActivityTime=;";
      }
      /*
      else if (Finish) {
          console.log("Lets not click that.");
          //Finish.click();
      }
      else if (($("#base_block #end_gift")) && Present) {
          console.log("Claiming mission completion reward(s).");
          Present.click();
      }
      */
      else {
        console.log("Could not identify given mission button.");
        sessionStorage.missionRequirement = "unknownMissionButton";
      }
    }
    else {
      // Not at Mission screen then goto the Mission screen.
      if (Cookies.get("nextActivityTime") === "0" || Cookies.get("nextActivityTime") === undefined || Cookies.get("nextActivityTime") === "" || (($("#home_missions_bar1 .text").length) === 0 && ($("#home_missions_bar2 .text").length) <= 2)) {
        console.log("Navigating to mission window.");
        sessionStorage.autoLoop = "false";
        window.location = window.location.origin + $("nav div[rel='content'] a:has(.activities)").attr("href");
        return;
      }
    }
  }
  catch (ex) {
    console.log("Could not do any missions... " + ex);
  }
};

var collectMission = function () {
  //console.log("Auto Missions Running");
  try {
    if ($("#breadcrumbs span").last().text() === "Activities") {
      console.log("Detected mission screen. Collecting mission(s)");
      var buttonMatch = $("#missions button:not([style='display: none;'])");
      var Claim = $("#missions button[rel^='claim']:not([style='display: none;'])");
      var Groovy = $("#popups #mission_rewards button[rel^='groovy']:not([style='display: none;'])");

      if (buttonMatch.length === 0) console.log("Could not find mission button.");
      else if (Claim && (Cookies.get("nextActivityTime") <= 1)) {
        console.log("Claiming mission");
        Claim.click();
        //sleep(1000);
      }
      else if (click) {}
      else if (($("#popups #mission_rewards")) && Groovy) {
        console.log("Claiming mission reward(s).");
        Groovy.click();
        window.location = window.location.origin + $("nav div[rel='content'] a:has(.activities)").attr("href");
        //sleep(500);
        document.cookie = "nextActivityTime=;";
      }
      else {
        console.log("Could not identify given mission button.");
        sessionStorage.missionRequirement = "unknownMissionButton";
      }
    }
    else {
      // Not at Mission screen then goto the Mission screen.
      if (Cookies.get("nextActivityTime") === "0" || Cookies.get("nextActivityTime") === undefined || Cookies.get("nextActivityTime") === "" || (($("#home_missions_bar1 .text").length) === 0 && ($("#home_missions_bar2 .text").length) <= 2)) {
        console.log("Navigating to Mission window.");
        sessionStorage.autoLoop = "false";
        window.location = window.location.origin + $("nav div[rel='content'] a:has(.activities)").attr("href");
        return;
      }
    }
  }
  catch (ex) {
    console.log("Could not collect mission(s)... " + ex);
  }
};

var autoLoop = function () {
  updateData();
  var busy = false;
  var page = window.location.href;
  var currentPower = Number($("span[hero='energy_fight']").text());
  //console.log("sal="+sessionStorage.autoSalary);
  if (sessionStorage.autoFreePachinko === "true" && busy === false) {
    // Navigate to pachinko
    if (Cookies.get("nextPachinkoTime") === undefined) {
      console.log("Time to fetch Pachinko.");
      getPachinko();
      busy = true;
    }
  }
  if (sessionStorage.autoSalary === "true" && busy === false) {
    if (Cookies.get("nextSalaryTime") === undefined) {
      console.log("Time to fetch salary.");
      getSalary();
      busy = true;
    }
    else if (Cookies.get("nextSalaryTime") === "") {
      console.log("Salary fetched. Getting next fetch time");
      if ($("nav div[rel='content'] a:has(.home)").attr("href") !== window.location.pathname) {
        console.log("Moving to home.");
        sessionStorage.autoLoop = "false";
        // Goto Home page.
        window.location = window.location.origin + $("nav div[rel='content'] a:has(.home)").attr("href");
        busy = true;
        return;
      }
      var CAB = $("#collect_all_bar .in").text();
      var closestTime;
      //console.log(CAB);
      if (CAB.includes('h') && CAB.includes('m')) {
        CAB = $("#collect_all_bar .in").text().replace('h', '').replace('m', '').replace(' ', '');
        //console.log('"'+CAB+'"');
        if (CAB.length == 1) {
          closestTime = Number((CAB[0]) * 3600);
        }
        if (CAB.length == 2) {
          closestTime = Number((CAB[0]) * 3600) + (Number(CAB[1]) * 60);
        }
        if (CAB.length == 3) {
          closestTime = Number((CAB[0]) * 3600) + (Number(CAB[1] + CAB[2]) * 60);
        }
        if (CAB.length == 4) {
          closestTime = Number((CAB[0] + CAB[1]) * 3600) + (Number(CAB[2] + CAB[3]) * 60);
        }
        //console.log('"'+closestTime+'"');
      }
      if (CAB.includes('m')) {
        CAB = $("#collect_all_bar .in").text().replace('m', '');
        //console.log('"'+CAB+'"');
        closestTime = Number(CAB.replace('m', '')) * 60;
        //console.log('"'+closestTime+'"');
      }
      if (CAB.includes('s')) {
        CAB = $("#collect_all_bar .in").text().replace('s', '');
        //console.log('"'+CAB+'"');
        closestTime = Number(CAB.replace('s', ''));
        //console.log('"'+closestTime+'"');
      }
      // Just in case something goes wrong area
      if ((CAB === undefined || CAB.length === 0) || (closestTime === undefined || closestTime === 0)) {
        closestTime = 5;
        getSalary();
        busy = true;
      }
      document.cookie = "nextSalaryTime=present;max-age=" + (closestTime < 0 ? 0 : closestTime);
      console.log("New fetch time stored in nextSalaryTime cookie.(+" + closestTime + " sec.)");
      busy = false;
    }
  }
  //
  if (sessionStorage.autoMissions === "true" && busy === false) {
    if (Cookies.get("nextActivityTime") === undefined && ($("#home_missions_bar1 .text").length) === 0 && ($("#home_missions_bar2 .text").length) <= 2 && ($("div[class='collect_notif']:not([style=''])"))) {
      console.log("Time to get a mission.");
      getMission();
      busy = true;
    }
    else if (Cookies.get("nextActivityTime") === "" && ($("#home_missions_bar1 .text").length) >= 0 && ($("#home_missions_bar2 .text").length) <= 2) {
      console.log("Accepting a mission. Getting countdown to next mission");
      if ($("nav div[rel='content'] a:has(.home)").attr("href") !== window.location.pathname) {
        console.log("Moving to home.");
        sessionStorage.autoLoop = "false";
        window.location = window.location.origin + $("nav div[rel='content'] a:has(.home)").attr("href");
        busy = true;
        return;
      }
      var MB1 = $("#home_missions_bar1 .text").text().replace('Complete in ', '')
      //console.log(MB1)
      if (MB1.includes('h') && MB1.includes('m')) {
        var MB1 = $("#home_missions_bar1 .text").text().replace('Complete in ', '').replace('h', '').replace('m', '').replace(' ', '');
        //console.log('"'+MB1+'"')
        if (MB1.length == 1) {
          var closestTime1 = Number((MB1[0]) * 3600);
        }
        if (MB1.length == 2) {
          var closestTime1 = Number((MB1[0]) * 3600) + (Number(MB1[1]) * 60);
        }
        if (MB1.length == 3) {
          var closestTime1 = Number((MB1[0]) * 3600) + (Number(MB1[1] + MB1[2]) * 60);
        }
        if (MB1.length == 4) {
          var closestTime1 = Number((MB1[0] + MB1[1]) * 3600) + (Number(MB1[2] + MB1[3]) * 60);
        }
        //console.log('"'+closestTime1+'"')
      }
      if (MB1.includes('m')) {
        MB1.replace('m', '')
        //console.log('"'+MB1+'"')
        var closestTime1 = Number(MB1.replace('m', '')) * 60
        //console.log('"'+closestTime1+'"')
      }
      if (MB1.includes('s')) {
        MB1.replace('s', '')
        //console.log('"'+MB1+'"')
        var closestTime1 = Number(MB1.replace('s', ''))
        //console.log('"'+closestTime1+'"')
      }
      // Just in case something goes wrong area
      if ((MB1.length === 0 && ($("#home_missions_bar2 .text").length) <= 2) || (closestTime1 === undefined || closestTime1 === 0)) {
        closestTime1 = 10*60;
        window.location = window.location.origin + $("nav div[rel='content'] a:has(.home)").attr("href");
        busy = true;
      }
      document.cookie = "nextActivityTime=present;max-age=" + (closestTime1 < 0 ? 0 : closestTime1);
      console.log("Time until next mission stored in nextActivityTime cookie.(+" + closestTime1 + " sec.)");
      busy = false;
    }
    if (Cookies.get("nextActivityTime") === "" && ($("#home_missions_bar1 .text").length) >= 0 && ($("#home_missions_bar2 .text").length) >= 0 && $("div[class='collect_notif']:not([style='display: none;'])")) {
      console.log("Time to collect the completed mission(s).");
      collectMission();
      busy = true;
    }
    if ((Cookies.get("nextActivityTime") === "" || Cookies.get("nextActivityTime") === undefined || Cookies.get("nextActivityTime") === 0) && ($("#home_missions_bar1 .text").length) <= 2 && ($("#home_missions_bar2 .text").length) >= 2) {
      console.log("All Missions Completed. Getting time until missions can be accepted again.");
      if ($("nav div[rel='content'] a:has(.home)").attr("href") !== window.location.pathname) {
        console.log("Moving to home.");
        sessionStorage.autoLoop = "false";
        window.location = window.location.origin + $("nav div[rel='content'] a:has(.home)").attr("href");
        busy = true;
        return;
      }
      var MB2 = $("#home_missions_bar2 .text").text().replace('Complete in ', '');
      //console.log(MB2)
      if (MB2.includes('h') && MB2.includes('m')) {
        var MB2 = $("#home_missions_bar2 .text").text().replace('Complete in ', '').replace('h', '').replace('m', '').replace(' ', '');
        //console.log('"'+MB2+'"')
        if (MB2.length == 1) {
          var closestTime1 = Number((MB2[0]) * 3600);
        }
        if (MB2.length == 2) {
          var closestTime1 = Number((MB2[0]) * 3600) + (Number(MB2[1]) * 60);
        }
        if (MB2.length == 3) {
          var closestTime1 = Number((MB2[0]) * 3600) + (Number(MB2[1] + MB2[2]) * 60);
        }
        if (MB2.length == 4) {
          var closestTime1 = Number((MB2[0] + MB2[1]) * 3600) + (Number(MB2[2] + MB2[3]) * 60);
        }
        //console.log('"'+closestTime1+'"')
      }
      if (MB2.includes('m')) {
        MB2.replace('m', '')
        //console.log('"'+MB2+'"')
        var closestTime1 = Number(MB2.replace('m', '')) * 60
        //console.log('"'+closestTime1+'"')
      }
      if (MB2.includes('s')) {
        MB2.replace('s', '')
        //console.log('"'+MB2+'"')
        var closestTime1 = Number(MB2.replace('s', ''))
        //console.log('"'+closestTime1+'"')
      }
      // Just in case something goes wrong area
      if ((MB1.length <= 1 && MB2.length >= 1) || (closestTime1 === undefined || closestTime1 === 0)) {
        closestTime1 = 10*60;
        window.location = window.location.origin + $("nav div[rel='content'] a:has(.home)").attr("href");
        busy = true;
      }
      document.cookie = "nextActivityTime=present;max-age=" + (closestTime1 < 0 ? 0 : closestTime1);
      console.log("Time until new missions stored in nextActivityTime cookie.(+" + closestTime1 + " sec.)");
      busy = false;
    }
  }
  //
  if (sessionStorage.autoQuest === "true" && busy === false) {
    if (sessionStorage.questRequirement === "battle") {
      //console.log("Quest requires battle.");
      doBossBattle();
      busy = true;
    }
    else if (sessionStorage.questRequirement[0] === '$') {
      if (Number(sessionStorage.questRequirement.substr(1)) < Number($("div[hero='soft_currency'] span").text().trim().replace(',', ''))) {
        // We have enough money... requirement fulfilled.
        console.log("Continuing quest, required money obtained.");
        sessionStorage.questRequirement = "none";
        proceedQuest();
        busy = true;
      }
      else {
        if (isNaN(sessionStorage.questRequirement.substr(1))) {
          sessionStorage.questRequirement = "none";
          console.log("Invalid money in session storage quest requirement !");
        }
        else {
          // Else we need more money.
          //console.log("Need money for quest, cannot continue. Turning ON AutoSalary.");
          sessionStorage.autoQuest = "true";
        }
        busy = false;
      }
    }
    else if (sessionStorage.questRequirement[0] === '*') {
      var energyNeeded = Number(sessionStorage.questRequirement.substr(1));
      var energyCurrent = Number($("span[hero='energy_quest']").text());
      if (energyNeeded <= energyCurrent) {
        // We have enough energy... requirement fulfilled.
        console.log("Continuing quest, required energy obtained.");
        sessionStorage.questRequirement = "none";
        proceedQuest();
        busy = true;
      }
      // Else we need energy, just wait.
      else {
        busy = false;
        //console.log("Replenishing energy for quest.(" + energyNeeded + " needed)");
      }
    }
    else if (sessionStorage.questRequirement[0] === 'P') {
      // Battle power required.
      var neededPower = Number(sessionStorage.questRequirement.substr(1));
      if (currentPower < neededPower) {
        console.log("Quest requires " + neededPower + " Battle Power for advancement. Waiting...");
        busy = false;
      }
      else {
        console.log("Battle Power obtained, resuming quest...");
        sessionStorage.questRequirement = "none";
        proceedQuest();
        busy = true;
      }
    }
    else if (sessionStorage.questRequirement === "unknownQuestButton") {
      console.log("AutoQuest disabled.AutoQuest cannot be performed due to unknown quest button. Please manually proceed the current quest screen.");
      document.getElementById("autoQuestCheckbox").checked = false;
      sessionStorage.autoQuest = "false";
      sessionStorage.questRequirement = "none";
      busy = false;
    }
    else if (sessionStorage.questRequirement === "errorInAutoBattle") {
      console.log("AutoQuest disabled.AutoQuest cannot be performed due errors in AutoBattle. Please manually proceed the current quest screen.");
      document.getElementById("autoQuestCheckbox").checked = false;
      sessionStorage.autoQuest = "false";
      sessionStorage.questRequirement = "none";
      busy = false;
    }
    else if (sessionStorage.questRequirement === "none") {
      //console.log("NONE req.");
      busy = true;
      proceedQuest();
    }
    else {
      console.log("Invalid quest requirement : " + sessionStorage.questRequirement);
      busy = false;
    }
  }
  else if (sessionStorage.autoQuest === "false") {
    sessionStorage.questRequirement = "none";
  }

  if (sessionStorage.autoBattle === "true") {
    if (busy === false && currentPower >= Number(sessionStorage.battlePowerRequired) && currentPower > 0) {
      sessionStorage.battlePowerRequired = "0";
      busy = true;
      if (sessionStorage.autoQuest === "true") {
        if (sessionStorage.questRequirement[0] === 'P') {
          console.log("AutoBattle disabled for power collection for AutoQuest.");
          document.getElementById("autoBattleCheckbox").checked = false;
          sessionStorage.autoBattle = "false";
          busy = false;
        }
        else
          doBossBattle();
      }
      else
        doBossBattle();
    }
  }
  else {
    sessionStorage.battlePowerRequired = "0";
  }

  if (busy === true && sessionStorage.userLink === "none") {
    sessionStorage.userLink = page;
  }
  else if (sessionStorage.userLink !== "none" && busy === false) {
    console.log("Restoring page " + sessionStorage.userLink);
    window.location = sessionStorage.userLink;
    sessionStorage.userLink = "none";
  }

  if (isNaN(sessionStorage.autoLoopTimeMili)) {
    console.log("AutoLoopTimeMili is not a number.");
    setDefaults();
  }
  else {
    if (sessionStorage.autoLoop === "true") setTimeout(autoLoop, Number(sessionStorage.autoLoopTimeMili));
    else console.log("autoLoop Disabled");
  }
};

var setDefaults = function () {
  var busy = "false";
  document.cookie = "nextActivityTime=0;";
  document.cookie = "nextSalaryTime=0;";
  var closestTime = 0;
  var closestTime1 = 0;
  console.log("Setting Defaults.");
  sessionStorage.autoSalary = "false";
  sessionStorage.autoFreePachinko = "false";
  sessionStorage.autoLoop = "true";
  sessionStorage.userLink = "none";
  sessionStorage.autoLoopTimeMili = "200";
  sessionStorage.autoQuest = "false";
  sessionStorage.autoBattle = "false";
  sessionStorage.battlePowerRequired = "0";
  sessionStorage.questRequirement = "none";
  sessionStorage.freshStart = "no";
  sessionStorage.autoMissions = "false";
};

var start = function () {
  //console.log("script started");
  // Add UI buttons.
  var UIcontainer = $("#contains_all nav div[rel='content']");
  UIcontainer.html('<div style="position: absolute;right: -16.475%; padding: 10px;width: inherit;text-align: center;display:flex;flex-direction:column;">' +
    '<span>AutoSal.</span><div><label class=\"switch\"><input id=\"autoSalaryCheckbox\" type=\"checkbox\"><span class=\"slider round\"></span></label></div>' +
    '<span>AutoQuest</span><div><label class=\"switch\"><input id=\"autoQuestCheckbox\" type=\"checkbox\"><span class=\"slider round\"></span></label></div>' +
    '<span>AutoBattle</span><div><label class=\"switch\"><input id=\"autoBattleCheckbox\" type=\"checkbox\"><span class=\"slider round\"></span></label></div>' +
    '<span>AutoPachinko(Free)</span><div><label class=\"switch\"><input id=\"autoFreePachinko\" type=\"checkbox\"><span class=\"slider round\"></span></label></div>' +
    '<span>AutoMissions</span><div><label class=\"switch\"><input id=\"autoMissions\" type=\"checkbox\"><span class=\"slider round\"></span></label></div>' +
    '</div>' + UIcontainer.html());
  document.getElementById("autoSalaryCheckbox").checked = sessionStorage.autoSalary === "true";
  document.getElementById("autoQuestCheckbox").checked = sessionStorage.autoQuest === "true";
  document.getElementById("autoBattleCheckbox").checked = sessionStorage.autoBattle === "true";
  document.getElementById("autoFreePachinko").checked = sessionStorage.autoFreePachinko === "true";
  document.getElementById("autoMissions").checked = sessionStorage.autoMissions === "true";
  sessionStorage.autoLoop = "true";
  if (typeof sessionStorage.freshStart == "undefined" || isNaN(Number(sessionStorage.autoLoopTimeMili))) {
    setDefaults();
  }
  autoLoop();
};
$("document").ready(start);