

















function setupSaves(){
  
  for (var i = 1; i < 101; i++) clearSave("Save "+i,"DELETED");
  clearSave("Autosave","DELETED");
  clearSave("Quicksave","DELETED");
}
window.setupSaves = setupSaves;

function clearSave(title,d){
  var test = localStorage.getItem(storagePrefix("Saved Game") + title);
    if(test == null){
      localStorage.setItem(storagePrefix("Saved Game") + title, "");
      localStorage.setItem(storagePrefix("Saved Game Filename") + title, d);
  }
  
}

function geth(e) { return getHarloweVariable(e); }
window.geth = geth;

function seth(e,a) { return setHarloweVariable(e,a); }
window.seth = seth;


function getSeaSaves(){
  var saves = [];
  for (var i = 1; i < 101; i++) { 
    var saveFilename = localStorage.getItem(storagePrefix("Saved Game Filename") + "Save " + i);
    saves[i] = saveFilename;

  }
  return saves;

}
window.getSeaSaves = getSeaSaves;

function getSeaDates(){
  var saves = [];
  for (var i = 1; i < 101; i++) { 
    var data = localStorage.getItem(storagePrefix("Saved Game") + "Save " + i);
    var extracted = "";

    try {
      var obj = JSON.parse(data);
      extracted = obj[1].variables.currentGameDate;
      if(isEmpty(extracted)) extracted = "";
    } catch (e) { }

    saves[i] = extracted;
  }
  return saves;

}
window.getSeaDates = getSeaDates;



function getMenuSaveTitle(){
  return localStorage.getItem(storagePrefix("Saved Game Filename") + "MenuSave"); 
}
window.getMenuSaveTitle = getMenuSaveTitle;


function replaceSaveWithMenuSave(slotName){

  var data = localStorage.getItem(storagePrefix("Saved Game") + "MenuSave");
  var fileName = localStorage.getItem(storagePrefix("Saved Game Filename") + "MenuSave");

  var today = new Date();
  var todayString = today.toLocaleString();
  var dayString = "Day " + geth("day") + ", ";
  var obj = JSON.parse(data);
  obj[1].variables.currentGameDate = dayString+todayString;
  data = JSON.stringify(obj);
  localStorage.setItem(storagePrefix("Saved Game") + slotName,data);
  localStorage.setItem(storagePrefix("Saved Game Filename") + slotName,fileName);
  localStorage.setItem("saveFlag", "save");
  
}
window.replaceSaveWithMenuSave = replaceSaveWithMenuSave;


function getAutosave(){
  var autosaveName = localStorage.getItem(storagePrefix("Saved Game Filename") + "Autosave");
  return autosaveName;
}
window.getAutosave = getAutosave;
function autosave(){
  savegame("Autosave",getHarloweVariable("currentPassage"));
  savegame("MenuSave","currentPassage");
  saveraw("AutoInv",getraw("inv_commands"));
  displayAlert("Autosaving...");
}
window.autosave = autosave;
function autosaveEnter(){

  var autosavePassage = geth("autosavePassage");
  var currentPassage = geth("currentPassage");

  if(autosavePassage != currentPassage){
    seth("autosavePassage",currentPassage);
    autosave();
  }

}
window.autosaveEnter = autosaveEnter;


function getQuicksave(){
  var quicksaveName = localStorage.getItem(storagePrefix("Saved Game Filename") + "Quicksave");
  return quicksaveName;
}
window.getQuicksave = getQuicksave;
function quicksave(){
  var allowQuicksave = geth("allowQuicksave");
  if(allowQuicksave){
    savegame("Quicksave",getHarloweVariable("currentPassage"));
    saveraw("QuickInv",getraw("inv_commands"));
    displayAlert("Quicksaving...");
  }
}
window.quicksave = quicksave;
function quickload(){
  var allowQuicksave = geth("allowQuicksave");
  if(allowQuicksave){
    saveraw("ReturnFlag","RETURNING");
    saveraw("inv_commands",getraw("QuickInv"));
    loadgame("Quicksave");
    displayAlert("Quickloading...");
  }
}
window.quickload = quickload;


$(document).keydown(function(e) {
        if ($('#menu-button').length && e.keyCode == 83 && e.ctrlKey) {
            e.preventDefault();
            quicksave();
        } else if ($('#menu-button').length && e.keyCode == 76 && e.ctrlKey) {
            e.preventDefault();
            quickload();
        } else if(e.keyCode == 38){
          $(".go_north").first().find("*").click();
        } else if(e.keyCode == 37){
          $(".go_west").first().find("*").click();
        } else if(e.keyCode == 39){
          $(".go_east").first().find("*").click();
        } else if(e.keyCode == 40){
          $(".go_south").first().find("*").click();
        } /*else if(e.keyCode >= 65 && e.keyCode <= 90){
          $("#answer").html( $("#answer").html() + String.fromCharCode(e.keyCode).toLowerCase() );
        } else if(e.keyCode == 32){
          $("#answer").html( $("#answer").html() + " " );
          e.preventDefault();
        } else if(e.keyCode == 8){
          $("#answer").html( $("#answer").html().slice(0, -1) );
        } */
    });


  window.confirm = function(id) {
    $("#"+id).css("display","none");
    $("#"+id+"-confirm").css("display","inline");
    $("#"+id+"-cancel").css("display","inline");
  }

  window.cancelConfirm = function(id) {
    $("#"+id).css("display","inline");
    $("#"+id+"-confirm").css("display","none");
    $("#"+id+"-cancel").css("display","none");
  }

function savegame(title,name) {

    var today = new Date();
    var todayString = today.toLocaleString();
    var dayString = "Day " + geth("day") + ", ";
    seth("currentGameDate",dayString+todayString);
    var save_object = compressJSON(_state.serialise());

    if(name == "currentPassage"){
      name = geth("currentPassage");
      if(name == "The Abyssal Plain"){
        var location_name = geth("location_name");
        if(location_name != "" && location_name != 0) name = location_name;
      }
      if(name == "Create" && geth("m_spells_state") == "complete")
        name = "Enchant";
      if(name == "Seethe")
        name = geth("m_anger_state");
      if(name == "Despair")
        name = geth("m_sad_state");
      if(name == "Not Unhappy")
        name = geth("m_happy_state");

    }

    try {
        if(title == "MenuSave"){
          seth("MenuSave",name);
        }
        if(title == "ReturnFlag") setHarloweVariable("ReturnFlag",name);
        localStorage.setItem(storagePrefix("Saved Game") + title, save_object);
        localStorage.setItem(storagePrefix("Saved Game Filename") + title, name);


        localStorage.setItem("saveFlag", "save");
    } catch (e) {
        alert("error saving game");
    }
}
function saveraw(title,name) {

    if(title == "MenuSave") setHarloweVariable("MenuSave",name);
    if(title == "ReturnFlag") setHarloweVariable("ReturnFlag",name);
    localStorage.setItem(storagePrefix("Saved Game") + title, name);
    localStorage.setItem(storagePrefix("Saved Game Filename") + title, name);
}
function getraw(title) {
    var data = localStorage.getItem(storagePrefix("Saved Game") + title);
    if(typeof(data) == "undefined") data = "";
    return data;
}
function loadgame(title) {
  try {    


        var permSettings = getHarloweVariable("PermSettings");
        var achievements = getHarloweVariable("Achievements");
        var puzzles_complete = getHarloweVariable("puzzles_complete");
        var MenuSave = getHarloweVariable("MenuSave");
        var ReturnFlag = getHarloweVariable("ReturnFlag");

        var data = localStorage.getItem(storagePrefix("Saved Game") + title);
        _state.deserialise(data);

        setHarloweVariable("PermSettings",permSettings);
        setHarloweVariable("Achievements",achievements);
        setHarloweVariable("puzzles_complete",puzzles_complete);
        setHarloweVariable("MenuSave",MenuSave);
        setHarloweVariable("ReturnFlag",ReturnFlag);

        saveraw("PermSettings",permSettings);
        saveraw("Achievements",achievements);
        saveraw("puzzles_complete",puzzles_complete);
        saveraw("ReturnFlag",ReturnFlag);

        var background_image = geth("background_image");
        var background_ext = geth("background_ext");
        resetScreen();
        seth("background_image",background_image);
        seth("background_ext",background_ext);

        loadPermSettings();
        loadAchieve();
        loadPuzzles();

        _engine.goToPassage(_state.passage);
        loadBackground();


    } catch (e) {
        alert("error loading game");
        //console.log(e);
    }  
}
function fixArray(array_name){

  var inv_array = window.getHarloweVariable(array_name);

  if (typeof inv_array != 'undefined'){
    var inv_map = new Map();
    for (var inv_item of inv_array) {
      var item_map = new Map();
      for (var entry of inv_item[1])
        item_map.set(entry[0],entry[1]);
      inv_map.set(inv_item[0],item_map);
    }

    window.setHarloweVariable(array_name,inv_map);
  }
  else{
    window.setHarloweVariable(array_name,[]);
  }
}

function fixFlatArray(array_name){
  var inv_array = window.getHarloweVariable(array_name);

  var inv_map = new Map();
  for (var inv_item of inv_array) {
    inv_map.set(inv_item[0],inv_item[1]);
  }
  window.setHarloweVariable(array_name,inv_map);

}
function compressJSON(file){

  try {

    var variable_map = new Map();
    var last_passage = "";
    var arr_from_json = JSON.parse(file);
    for (var passage_count = 0; passage_count < arr_from_json.length; passage_count++) { 
      last_passage = arr_from_json[passage_count].passage;
      var keys = Object.keys(arr_from_json[passage_count].variables);
      var variables = arr_from_json[passage_count].variables;
      for (var var_count = 0; var_count < keys.length; var_count++) { 
        variable_map.set(keys[var_count], variables[keys[var_count]]);
      }
    }

    var final_json = '[{"passage":"first technology","variables":{}},{"passage":"' + last_passage + '","variables":{';

    var keys = Object.keys(variable_map);

    var mapIter = variable_map.keys();
    for (var count = 0; count < variable_map.size; count++) { 

        var key = mapIter.next().value;
        var value = variable_map.get(key);

        final_json += '"' + key + '":';


        if(typeof value === "string" && value.includes('"')){
          value = replaceAll(value, '"',"'");
        }


        if(key == "formatted_dream"){

          
          value= '""';

        }
        else if(Array.isArray(value)){
          
          if(value.length == 0)
            value = '[]';
          else{
            value = JSON.stringify(value);

          }

        }
        else if (typeof value === "string" &&  value == false){
          value = '""';

        }
        else if(value == true || value == false){
        }
        else if(value == ""){
          value = '""';
        }
        else if(!value){
          value = '""';
        }
        else if(Number.isInteger(value)){
        }
        else if(Array.isArray(value)){
          var array_assembly = "[";
          
          for (var arr_count = 0; arr_count < value.length; arr_count++)
            array_assembly += '"' + value[arr_count] + '",';
          if(array_assembly != "[")
            array_assembly = array_assembly.substring(0, array_assembly.length - 1);
          array_assembly += "]"
          value = array_assembly;
        }
        else if (typeof value === "string"){
          
          var numberOfLineBreaks = (value.match(/\n/g)||[]).length;
          if(numberOfLineBreaks > 0)
            value = value.split("\n").join("\\n");
          value = '"' + value + '"';

        }
        else if (!isNaN(value) && value.toString().indexOf('.') != -1){
        
        }
        else {
            var datamap = value["(datamap:)"];

            if(datamap.length == 0) {
              value = "[]";
            } else{
              value = jsonFromDatamap(datamap);

            }

        }
        final_json += value + ',';
    }

    final_json = final_json.substring(0, final_json.length - 1);
    final_json += '}}]';

    return final_json;

  } catch (e) {

    return "";
  }


}


function jsonFromDatamap(datamap){


  var array_assembly = "[";
  for (var arr_count = 0; arr_count < datamap.length; arr_count++){

    array_assembly += "["
    var item = datamap[arr_count];
    var key = item[0];
    var value = item[1];


    array_assembly += '"' + key + '"' + ",";

    if(value["(datamap:)"] != null){
      array_assembly +=jsonFromDatamap(value["(datamap:)"]);
    }
    else if (typeof value === "string" &&  value == false){
      array_assembly += '""';
    }
    else if(value == "true" || value == "false" || value == true || value == false || Number.isInteger(value)){
      array_assembly += value;
    }
    else if(Array.isArray(value)){
      if(value.length == 0)
        array_assembly += '[]';
      else{
        array_assembly += JSON.stringify(value);
      }
    }
    else if(value == "" || !value){
      array_assembly += '""';
    }
    else{
      array_assembly += '"' + value + '"';
    }

    array_assembly += "],"


  }
  if(array_assembly != "[")
    array_assembly = array_assembly.substring(0, array_assembly.length - 1);
  array_assembly += "]"
  return array_assembly;

}
window.savegame = savegame, window.saveraw = saveraw, window.getraw = getraw, window.loadgame = loadgame,window.compressJSON = compressJSON;

function arrayUpdate(id, oldValue, newValue, array){
  for (var j = 0; j < array.length; j += 2) { 
        var currentId = array[j];
        var currentValue = array[j+1];
    
    if(currentId == id && (currentValue == oldValue || oldValue == "any")){
      array[j+1] = newValue;
        }  
    }
}

function arrayCheck(id, array){
  var retVal = "";
  for (var j = 0; j < array.length; j += 2) { 
        var currentId = array[j];
        if(currentId == id){
          retVal = array[j+1];
        }  
    }
  return retVal;
}

function clickCyclingLink(e, a) {

    var t = JSON.parse($(e).attr("data-cycling-texts"));
    var f = $(e).html();
    if(f.includes("<"))
      f = $(f).html();

    while(t[0] != f)
      t.push(t.shift());

    if (!("undefined" == typeof t || t.length < 2)) {
        t.push(t.shift());
        var i = t[0];
        if ("$" === i[0]) i = getHarloweVariable(i);
        else if ("out" === i) $(e).remove();
        else if ("end" === i) {
            var n = t[t.length - 1];
            t = "$" === n[0] ? [getHarloweVariable(n)] : [t[t.length - 1]], $(e).hasClass("endedCyclingLink") || $(e).addClass("endedCyclingLink")
        } else if ("goto " === i.slice(0, 5)) {
            var l = i.slice(5, i.length);
            "$" === l[0] && (l = l.slice(1, l.length));
            var s = parseInt(l.trim());
            if (isNaN(s)) {
                var r = $("tw-storydata > tw-passagedata[name=" + l + "]");
                "undefined" != typeof r && r.length >= 1 && _engine.goToPassage($(r).attr("pid"))
            } else {
                var r = $("tw-storydata > tw-passagedata[pid=" + s + "]");
                "undefined" != typeof r && r.length > 1 && _engine.goToPassage(s)
            }
        }
        setHarloweVariable(a, t[0]), $(e).text(i), $(e).attr("data-cycling-texts", JSON.stringify(t))
    }
}
window.clickCyclingLink = clickCyclingLink;


function storagePrefix(text) {
  return "(" + text + " silence " + _engine.options.ifid + ") "
}
window.storagePrefix = storagePrefix;


function fixFlatArray(array_name){
  var inv_array = window.getHarloweVariable(array_name);

  var inv_map = new Map();
  for (var inv_item of inv_array) {
    inv_map.set(inv_item[0],inv_item[1]);
  }
  window.setHarloweVariable(array_name,inv_map);

}



function replaceAll(str, find, replace) { return str.replace(new RegExp(find, 'g'), replace); }
window.replaceAll = replaceAll;

function ucfirst(string)  { 
  if(string) return string.charAt(0).toUpperCase() + string.slice(1); 
  else return "";
}
window.ucfirst = ucfirst;

function removeFromArray(array,item)  {    
   var pos = array.indexOf(item);
   array.splice(pos, 1);
}
window.removeFromArray = removeFromArray;

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
window.getRandomInt = getRandomInt;


window.blankBackground = function() {

  $("#back1").fadeTo("fast",0);
  $("#back2").fadeTo("fast",0);

}

window.changeBackground = function(image) {
  changeBackgroundExt(image,".jpg");
}

window.resetBackground = function() {
  $("html,body").css("background","");
  $("#back1, #back2").css("background-size","").css("background-position","").css("background-repeat","");
  $("tw-story").css("max-width","");


}


function changeBackgroundHtml(image,reference,back){


  if(image == "") { resetBackground(); }
  else if(image.includes("coffinFrame")){
    $(back).css("background-size","auto").css("background-position","center top").css("background-repeat","");
    $("tw-story").css("max-width","1200px");
  }
  else if(image.includes("Frame")){
    $(back).css("background-size","auto 100%").css("background-position","center bottom").css("background-repeat","");
    $("tw-story").css("max-width","1200px");
  }
  else if(image.includes("hallwaySpike")){
    $(back).css("background-size","auto 100%").css("background-position","right top").css("background-repeat","");
    $("tw-story").css("max-width","");
  }
  else if(image.includes("kennel")){
    $(back).css("background-size","auto 100%").css("background-position","left top").css("background-repeat","");
    $("tw-story").css("max-width","");
  }
  else if(image == "hallway"){
    $(back).css("background-size","auto 100%").css("background-position","center bottom").css("background-repeat","");
    $("tw-story").css("max-width","1200px");
  }
  else if(image == "dormitory"){
    $(back).css("background-size","auto 100%").css("background-position","center bottom").css("background-repeat","");
    $("tw-story").css("max-width","1200px");
  }
  else if(image == "favor"){
    $(back).css("background-size","auto 100%").css("background-position","center bottom").css("background-repeat","");
    $("tw-story").css("max-width","1200px");
  }
  else if(image == "ballroom"){
    $(back).css("background-size","auto 100%").css("background-position","center top").css("background-repeat","");
    $("tw-story").css("max-width","1200px");
  }
  else if(image.includes("wall")){
    $(back).css("background-size","auto 100%").css("background-position","left top").css("background-repeat","");
    $("tw-story").css("max-width","1200px");
  }
  else if(image.includes("gargoyle")){
    $(back).css("background-size","auto 100%").css("background-position","left top").css("background-repeat","");
    $("tw-story").css("max-width","1200px");
  }
  else resetBackground();

  $(back).css("background-image", reference);

}

window.changeBackgroundExt = function(image,ext) {

  if(typeof(image) == "undefined") image = "";



  var back_2_op = $("#back2").css("opacity");
  var reference = "url('./silenceImages/" + image + ext + "')";

  $("#back1").stop();
  $("#back2").stop();

  if(image == ""){
    $("#back1").fadeTo("fast",0);
    $("#back2").fadeTo("fast",0);
    resetBackground();

  } else if(back_2_op == 0){
    //console.log("from 1");
    changeBackgroundHtml(image,reference,"#back1, #back2");
    $("#back2").fadeTo("fast",1);

  } else if(back_2_op == 1){
    var old_ref = $("#back2").css("background-image");
    //var old_image = old_ref.substring(old_ref.indexOf("/backgrounds/") + 13);
    //old_image = old_image.substring(0,old_image.indexOf("."));
    var old_image = old_ref;



    //console.log("from 2");
    changeBackgroundHtml(old_image,old_ref,"#back1");
    $("#back1").css("opacity", 1);

    //console.log("from 3");
    changeBackgroundHtml(image,reference,"#back2");
    $("#back1").fadeTo("fast",0);

  }else {
    $("#back1").css("opacity", 0);
    $("#back2").css("opacity", 1);
    //console.log("from 4");
    changeBackgroundHtml(image,reference,"#back1, #back2");    
  }

  seth("background_image",image);
  seth("background_ext",ext);


}

window.loadBackground = function() {
  var image = geth("background_image");
  var ext = geth("background_ext");

  changeBackground(image,ext);

}


function savePermSettings(){

  var savePage = getHarloweVariable("SavePage");
  if(savePage == "" || savePage == null) savePage = 1;
  saveraw("SavePage",savePage);

  var perm = "";

  if(getHarloweVariable("SeenTimedIntro")) perm += "SeenTimedIntroTrue"; else perm += "SeenTimedIntroFalse";
  if(getHarloweVariable("TimedSequence")) perm += "TimedSequenceTrue"; else perm += "TimedSequenceFalse";
  if(getHarloweVariable("SpeedRun")) perm += "SpeedRunTrue"; else perm += "SpeedRunFalse";
  if(getHarloweVariable("SpeedRunDisplay")) perm += "SpeedRunDisplayTrue"; else perm += "SpeedRunDisplayFalse";
  if(getHarloweVariable("ColorBlind")) perm += "ColorBlindTrue"; else perm += "ColorBlindFalse";
  if(getHarloweVariable("TextToSpeech")) perm += "TextToSpeechTrue"; else perm += "TextToSpeechFalse";
  if(getHarloweVariable("TravelAnimation")) perm += "TravelAnimationTrue"; else perm += "TravelAnimationFalse";
  if(getHarloweVariable("Fullscreen")) perm += "FullscreenTrue"; else perm += "FullscreenFalse";
  if(getHarloweVariable("SoundEffects")) perm += "SoundEffectsTrue"; else perm += "SoundEffectsFalse";
  if(getHarloweVariable("Music")) perm += "MusicTrue"; else perm += "MusicFalse";
  if(getHarloweVariable("Quickstart")) perm += "QuickstartTrue"; else perm += "QuickstartFalse";
  if(getHarloweVariable("IntroComplete")) perm += "IntroCompleteTrue"; else perm += "IntroCompleteFalse";
  if(getHarloweVariable("AgreementMade")) perm += "AgreementMadeTrue"; else perm += "AgreementMadeFalse";
  if(getHarloweVariable("LastDifficulty")) perm += "LastDifficultyTrue"; else perm += "LastDifficultyFalse";

  if(getHarloweVariable("philosophy_unlocked")) perm += "philosophy_unlockedTrue"; else perm += "philosophy_unlockedFalse";
  perm += "TextToSpeechSpeed" + getHarloweVariable("TextToSpeechSpeed");
  perm += "FontSize" + getHarloweVariable("FontSize");

  setHarloweVariable("PermSettings",perm);
  saveraw("PermSettings",perm);

}
window.savePermSettings = savePermSettings;

function loadPermSettings(){

  var savePage = localStorage.getItem(storagePrefix("Saved Game") + "SavePage");
  if(savePage == "" || savePage == null) savePage = 1;
  setHarloweVariable("SavePage",savePage);
  
  var perm = localStorage.getItem(storagePrefix("Saved Game") + "PermSettings");
  if(perm != null){
    setHarloweVariable("PermSettings",perm);

    if(perm.includes("TimedSequenceTrue")) setHarloweVariable("TimedSequence",true); else setHarloweVariable("TimedSequence",false); 
    if(perm.includes("SpeedRunTrue")) setHarloweVariable("SpeedRun",true); else setHarloweVariable("SpeedRun",false); 
    if(perm.includes("SpeedRunDisplayTrue")) setHarloweVariable("SpeedRunDisplay",true); else setHarloweVariable("SpeedRunDisplay",false); 
    if(perm.includes("ColorBlindTrue")) setHarloweVariable("ColorBlind",true); else setHarloweVariable("ColorBlind",false); 
    if(perm.includes("TextToSpeechTrue")) setHarloweVariable("TextToSpeech",true); else setHarloweVariable("TextToSpeech",false); 
    if(perm.includes("TravelAnimationTrue")) setHarloweVariable("TravelAnimation",true); else setHarloweVariable("TravelAnimation",false); 
    if(perm.includes("FullscreenTrue")) setHarloweVariable("Fullscreen",true); else setHarloweVariable("Fullscreen",false); 
    if(perm.includes("SoundEffectsFalse")) setHarloweVariable("SoundEffects",false); else setHarloweVariable("SoundEffects",true); 
    if(perm.includes("MusicFalse")) setHarloweVariable("Music",false); else setHarloweVariable("Music",true); 
    if(perm.includes("QuickstartFalse")) setHarloweVariable("Quickstart",false); else setHarloweVariable("Quickstart",true); 
    if(perm.includes("IntroCompleteFalse")) setHarloweVariable("IntroComplete",false); else setHarloweVariable("IntroComplete",true); 
    if(perm.includes("AgreementMadeFalse")) setHarloweVariable("AgreementMade",false); else setHarloweVariable("AgreementMade",true); 
    if(perm.includes("LastDifficultyFalse")) setHarloweVariable("LastDifficulty",false); else setHarloweVariable("LastDifficulty",true); 

    if(perm.includes("philosophy_unlockedTrue")) setHarloweVariable("philosophy_unlocked",true); else setHarloweVariable("philosophy_unlocked",false);

    var fontSize = "NORMAL";
    if(perm.includes("FontSizeHUGE")) fontSize = "HUGE";
    else if(perm.includes("FontSizeLARGE")) fontSize = "LARGE";
    else fontSize = "NORMAL";
    seth("FontSize",fontSize);





  }

}
window.loadPermSettings = loadPermSettings;










function addAchieve(achievement){

  var achieve = "";
  var achievements = getHarloweVariable("Achievements");
  var dark = getHarloweVariable("Dark");

  if(isEmpty(achievements)) achievements = " ";
  if(isEmpty(dark)) dark = " ";


  var achievementIsDark = false;
  for (var i = dark.length - 1; i >= 0; i--) {
    if(dark[i].includes(achievement)) achievementIsDark = true;
  }


  if(achievements.includes(achievement) == false){

    if(achievementIsDark) playAudio("aa_dark_chime3");
    else playAudio("aa_tap2");
    
    achievements += achievement;
    seth("Achievements",achievements);
    saveraw("Achievements",achievements);
  }
  triggerAchievement(achievement);
}
window.addAchieve = addAchieve;


function saveAchieve(){
  var achievements = geth("Achievements");
  if(isEmpty(achievements)) achievements = "";
  saveraw("Achievements",achievements);

}
window.saveAchieve = saveAchieve;

function loadAchieve(){
  var achievements = getraw("Achievements");
  if(isEmpty(achievements)) achievements = "";
  seth("Achievements",achievements);

}
window.loadAchieve = loadAchieve;


function triggerAchievement(achName) {
    
        var underline_name = replaceAll(achName, " ","_");
        try{
          if(greenworks_working) greenworks.activateAchievement(underline_name, function(){});
        } catch(e){ alert(e); }
    }
window.triggerAchievement = triggerAchievement;

function loadPuzzles(){
  var puzzles = localStorage.getItem(storagePrefix("Saved Game") + "PuzzleComplete");
  if(puzzles == null) setHarloweVariable("puzzles_complete","default~puzzle");
  else setHarloweVariable("puzzles_complete",puzzles);
}
window.loadPuzzles = loadPuzzles;

function addPuzzle(puzzle){
  var puzzles = localStorage.getItem(storagePrefix("Saved Game") + "PuzzleComplete");
  if(puzzles == null) puzzles = "default~puzzle";
  if(puzzles.includes(puzzle) == false) puzzles += puzzle;
  
  setHarloweVariable("puzzles_complete",puzzles);
  saveraw("PuzzleComplete",getHarloweVariable("puzzles_complete"));
}
window.addPuzzle = addPuzzle;





function installExtraHtml(){

  if($("#canv").length == 0) {
    installCanvas();
    installBackgroundLayers();
    installHUD();
  }


}
window.installExtraHtml = installExtraHtml;

function installCanvas(){$("body").append("<canvas id='canv'></canvas><canvas id='forceRefreshCanvas' width='1' height='1'></canvas>");} window.installCanvas = installCanvas;
function installBackgroundLayers(){$("body").append("<div id='back1'></div><div id='back2'></div><div id='spider-area'></div>");} window.installBackgroundLayers = installBackgroundLayers;



function clearCanvas(){
  var canvas = document.getElementById('canv');
  var context2D = canvas.getContext('2d');
  context2D.clearRect(0, 0, canvas.width, canvas.height);
}
window.clearCanvas = clearCanvas;



function resetScreen(){
  blankBackground("");
  resetBackground();
  seth("background_image","");
  seth("background_ext","");
  clearCanvas();
  $("#back1, #back2").css("background-size","").css("background-position","");
  $("html").css("background","");
  $("body").css("opacity",1);
  $("#stat-memory .bar").css("background-color","");
  $("#area-description").css("background-color","transparent");
  $("#area-description").css("color","white");
  $("#game-frame").css("background","black");
  $("#area-description").removeClass("bright-pulse");
  
}
window.resetScreen = resetScreen;









window.displayHUD = function(id){
  if(id == "speed-run-toggle")
    if(geth("SpeedRun")) $("#speed-text").html("ON");
    else $("#speed-text").html("OFF");

  $("#"+id).css("display","block");
}

window.hideHUD = function(id){ $("#"+id).css("display","none"); }

window.toggleSpeedrun = function(id){ 
  var SpeedRun = geth("SpeedRun");
  if(SpeedRun){ seth("SpeedRun",false); $("#speed-text").html("OFF"); }
  else { seth("SpeedRun",true); $("#speed-text").html("ON"); }
  savePermSettings();
}




window.goToMenu = function(menuPassage){ 
  savegame("MenuSave","currentPassage");
  var ReturnFlag = geth("ReturnFlag");

  if(ReturnFlag == "BLANK"){
    unloadHUD();
    goToPassage(menuPassage);
  }
  savegame("ReturnFlag","BLANK");
}


window.isUndefined = function(data){   
  if(typeof(data) == "undefined") return true;
  else return false;
}

window.isEmpty = function(data){   
  if(typeof(data) == "undefined" || data == 0 || data == "" || data == null) return true;
  else return false;
}

window.checkScrollBar = function(id, dir){   
  var element = document.getElementById(id);
  dir = (dir === 'vertical') ? 'scrollTop' : 'scrollLeft';
    
  var res = !! element[dir];
    
  if (!res) {
      element[dir] = 1;
      res = !!element[dir];
      element[dir] = 0;
  }
  return res;
}




window.skipIntro = function(){
  seth("sequence",0);
  goToPassage("Act 1");
}




window.getInvCommand = function(){   
  var inv_commands_raw = getraw("inv_commands");
  var inv_commands = [];
  if(!isUndefined(inv_commands_raw) && inv_commands_raw != "" && inv_commands_raw != null && inv_commands_raw != "null") inv_commands = inv_commands_raw.split(",");
  return inv_commands;
}


window.addInvCommand = function(command,data,type){   

  var inv_commands = getInvCommand();

  var found_entry = false;
  if(type == "replace")
    for (var i = 0; i < inv_commands.length; i += 2) {
      
      if(inv_commands[i] == command){
        found_entry = true;
        inv_commands[i+1] = data;

      }
    }
  
  if(found_entry == false){
    inv_commands.push(command);
    inv_commands.push(data);
  }

  saveraw("inv_commands",inv_commands);
}



window.setFullscreen = function(full) {
  
  if (typeof nw != 'undefined') {

    var win = nw.Window.get();
    if(full == "ON")
      win.enterFullscreen();
    else
      win.leaveFullscreen();
    win.focus();
  }

}


function updateValueHealth(value,maxValue) {

    var hundredValue = Math.round((100*value)/maxValue);
    var inverseValue = 100-hundredValue;
    $("#bar1Health").css("width", inverseValue*5+"px");
    $("#text1").html(value+"/"+maxValue);

    if(hundredValue == 0) $("#left1").removeClass("after-left-brightred").addClass("after-left-darkred");
    else $("#left1").removeClass("after-left-darkred").addClass("after-left-brightred");

    if(hundredValue == 100) $("#right1").removeClass("after-right-darkred").addClass("after-right-brightred");
    else $("#right1").removeClass("after-right-brightred").addClass("after-right-darkred");

}

function updateEnemyHealth(value,maxValue) {

    var hundredValue = Math.round((100*value)/maxValue);
    var inverseValue = 100-hundredValue;
    $("#bar2Health").css("width", inverseValue*5+"px");
    $("#textEnemyHealth").html(value+"/"+maxValue);

    if(hundredValue == 0) $("#left2").removeClass("after-left-brightred").addClass("after-left-darkred");
    else $("#left2").removeClass("after-left-darkred").addClass("after-left-brightred");

    if(hundredValue == 100) $("#right2").removeClass("after-right-darkred").addClass("after-right-brightred");
    else $("#right2").removeClass("after-right-brightred").addClass("after-right-darkred");

}

function updateValueEnergy(value,maxValue) {

  var hundredValue = Math.round((100*value)/maxValue);
  var newWidth = Math.round((540*hundredValue)/100);

  $("#bar2").css("width", newWidth+"px");
  $("#text2").html(value);

  if(value == 0) $("#text2").css("visibility","hidden");
  else $("#text2").css("visibility","visible");

}

function updateValueLearn(value,maxValue) {

  var hundredValue = Math.round((100*value)/maxValue);
  var newWidth = Math.round((540*hundredValue)/100);

  $("#bar3").css("width", newWidth+"px");
  $("#text3").html(value + "/" + maxValue);

  if(value == 0 || newWidth < 40) $("#text3").css("right","-36px").css("color","#C29539");
  else $("#text3").css("right","2px").css("color","black");

}


function updateEmotion(emotion,value) {


  var happy_value = geth("happy_value");
  var calm_value = geth("calm_value");
  var curious_value = geth("curious_value");
  var astarion_mood = geth("astarion_mood");
  var interaction_to_trust = geth("interaction_to_trust");
  var astarion_trust = geth("astarion_trust");

  if(emotion == "happy"){
    happy_value += value;

    if(happy_value > 9){
      if(astarion_mood == "frightened" || astarion_mood == "tense"){
        astarion_mood = "calm";
      } else{
        astarion_mood = "happy";
      }

      happy_value = 0;
      interaction_to_trust++;
    }
  }else if(emotion == "calm"){
    calm_value += value;

    if(calm_value > 9){
      if(astarion_mood != "happy" && astarion_mood != "excited") astarion_mood = "calm";
      
      calm_value = 0;
      if(astarion_trust < 12) interaction_to_trust++
    }
  }else if(emotion == "curious"){
    curious_value += value;

    if(curious_value > 9){
      if(astarion_mood == "frightened") astarion_mood = "tense";
      else if(astarion_mood != "happy" && astarion_mood != "calm" && astarion_mood != "excited") astarion_mood = "curious";
      
      curious_value = 0;
      if(astarion_trust < 6) interaction_to_trust++
    }
  }

  var interactions_needed = 1;
  if(astarion_trust > 15) interactions_needed = 4;
  if(astarion_trust > 10) interactions_needed = 3;
  if(astarion_trust > 5) interactions_needed = 2;


  if(interaction_to_trust > interactions_needed){
    interaction_to_trust = 0;
    astarion_trust++;
  }


  if(astarion_trust > 20) astarion_trust = 20;

  seth("astarion_trust",astarion_trust);
  seth("interaction_to_trust",interaction_to_trust);
  seth("astarion_mood",astarion_mood);
  seth("happy_value",happy_value);
  seth("calm_value",calm_value);
  seth("curious_value",curious_value);
}






function markupEnergyActions(){

  var energyLinks = $('.energy-link');

  for(var i = 0; i < energyLinks.length; i++){
    
    var currentLink = energyLinks[i];
    var linkId = $(currentLink).attr('id');
    var content = $(currentLink).data('content');
    var contentAr = content.split("/");
    var text = contentAr[0];
    var requiredSkill = contentAr[1];
    var requiredSkillValue = parseInt(contentAr[2]);

    var energy = parseInt(geth("energy"));
    var energyValue = 1;
    if(contentAr.length > 4){
      if(contentAr[4] == "all") contentAr[4] = energy;
      energyValue = parseInt(contentAr[4]);
    }




    
    var type = contentAr[5];


    var html = "";
    var currentSkillValue = parseInt(geth(requiredSkill.toLowerCase()));
    text = text.replaceAll("`","\'");

    var enemyNameText = geth("enemyNameText");
    text = text.replaceAll("$enemy",enemyNameText);

    

    if(currentSkillValue < requiredSkillValue){
      
      html += "<a id='"+linkId+"LinkGray' class='gray' onclick='activateGray(this)'>"+text+" </a><span id='"+linkId+"Gray' class='hidden'><i>Requires "
        +requiredSkill+" "+requiredSkillValue+"</i></span>";

    }else if(energy < energyValue){
      html += "<a id='"+linkId+"LinkGray' class='gray' onclick='activateGray(this)'>"+text+" </a><span id='"+linkId+"Gray' class='hidden'><i>Not enough energy.</i></span>";

    }else if(requiredSkill == "Dialog"){
      var playerName = geth("player_name");
      html += "<a id='"+linkId+"Link' onclick='activateEnergyLink(this)' " + "data-content='"+content+"'>"+playerName+ ": "+text+" </a>";

    }else if(requiredSkill == "DialogGray"){
      var playerName = geth("player_name");
      html += "<a id='"+linkId+"LinkGray' onclick='activateGray(this)' " + "data-content='"+content+"'>"+playerName+ ": "+text+" </a><span id='"+linkId+"Gray' class='hidden'><i>You don't have something you need.</i></span>";

    }else if(requiredSkill == "Gray"){
      html += "<a id='"+linkId+"LinkGray' class='gray' onclick='activateGray(this)'>"+text+" </a><span id='"+linkId+"Gray' class='hidden'><i>You don't have something you need.</i></span>";

    }else if(requiredSkill == "Draw"){
      var draw_attention_blocked = geth("draw_attention_blocked");
      if(draw_attention_blocked == "blocked")
        html += "<a id='"+linkId+"LinkGray' class='gray' onclick='activateGray(this)'>"+text+" </a><span id='"+linkId+"Gray' class='hidden'><i>Astarion is distracted.</i></span>";
      else{
        html += "<a id='"+linkId+"Link' onclick='activateEnergyLink(this)' " + "data-content='"+content+"'>"+text+" <i>";
        if(energyValue > 0) html += "<span class='energy'>"+energyValue+"</span>";
        html += "</i></a>";
      }
      
    }else{
      html += "<a id='"+linkId+"Link' onclick='activateEnergyLink(this)' " + "data-content='"+content+"'>"+text+" <i>";
      if(energyValue > 0) html += "<span class='energy'>"+energyValue+"</span>";
      html += "</i></a>";

    }
    $("#"+linkId).html(html);
  }
}


function activateGray(e){
  var linkId = $(e).attr('id').toString().replace("LinkGray","");
  $("#"+linkId+"Gray").removeClass("hidden");

}

function activateEnergyLink(e){
  var linkId = $(e).attr('id').toString().replace("Link","");

  var contentAr = $(e).data('content').split("/");
  var text = contentAr[0];
  var requiredSkill = contentAr[1];
  var requiredSkillValue = parseInt(contentAr[2]);

  var currentSequence = geth("sequence");
  var sequenceValue = currentSequence + 1;
  if(contentAr.length > 3){
    var sequenceRaw = contentAr[3];
    if(sequenceRaw != "+1") sequenceValue = parseInt(sequenceRaw);
  }


  var energy = parseInt(geth("energy"));
  var energyValue = 1;
  if(contentAr.length > 4){
    if(contentAr[4] == "all") contentAr[4] = energy;
    energyValue = parseInt(contentAr[4]);
  } 

  var type = contentAr[5];

  var justSaid = linkId;
  if(justSaid.includes("-")) justSaid = justSaid.substring(0,justSaid.indexOf("-"));
  if(justSaid.includes("_")) justSaid = justSaid.replaceAll("_"," ");





  if(energyValue != 0) updateEnergy(0-energyValue);
  seth("sequence",sequenceValue);
  seth("just_said",justSaid);
  var day = geth("day");

  if(type == "surpriseCheck" && day < 163){
    var astarion_interacted = geth("astarion_interacted");
    seth("astarion_interacted",true);
    if(astarion_interacted == false) goToPassage("I Don't Like Surprises");
    else goToPassage(geth("currentPassage"));
  }
  else if(typeof(type) != "undefined" && type.includes("passage:")){
    var passage = type.replace("passage:","");
    goToPassage(passage);
  }
  else{
    goToPassage(geth("currentPassage"));
  }
}


function reduceEnergy(){
  updateEnergy(-1);

}


function updateEnergy(amount){
  var energy = geth("energy");
  var maxEnergy = geth("$maxEnergy");
  energy = energy+amount;
  if(energy < 0) energy = 0;
  if(energy > maxEnergy) energy = maxEnergy;
  seth("energy",energy);
  playAudio("aa_clock_tick1");

}

function updateTrust(amount){
  var astarion_trust = geth("astarion_trust");
  astarion_trust = astarion_trust+amount;
  if(astarion_trust < 0) astarion_trust = 0;
  if(astarion_trust > 20) astarion_trust = 20;
  seth("astarion_trust",astarion_trust);

  if(astarion_trust > 9) addAchieve("Astarion Approves");
  if(astarion_trust > 14) addAchieve("Astarion Approves More");
}

function updateAttention(amount){
  var his_attention = geth("his_attention");
  var his_attention_max = geth("his_attention_max");
  his_attention = his_attention+amount;
  if(his_attention < 0) his_attention = 0;
  if(his_attention > his_attention_max) his_attention = his_attention_max;
  seth("his_attention",his_attention);
  playAudio("aa_attention");
}

function updateEscape(amount){
  var escape = geth("escape");
  var escape_max = geth("escape_max");
  escape = escape+amount;
  if(escape < 0) escape = 0;
  if(escape > escape_max) escape = escape_max;
  seth("escape",escape);
  playAudio("aa_tap2");
}



window.capitalizeFirstLetter = function(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }


window.sequence = function(num,passage) {
  seth("sequence",num);
  goToPassage(passage);
}


window.resumeGame = function(e) {
    savegame("ReturnFlag","RETURNING");
    window.loadgame("MenuSave");
}





window.refreshHUD = function(){
  var test_mode = geth("test_mode");
  if(test_mode) $("#elsewhere-item").css("display","block"); else $("#elsewhere-item").css("display","none");

  var in_intro = geth("in_intro");
  var no_menu = geth("no_menu");
  var display_resume = geth("display_resume");

  var menuSave = geth("MenuSave");
  if(menuSave == "DELETED") display_resume = false;

  if(in_intro) {
    $("#skip-intro").css("display","block");
    $("#menu-button").css("display","none");
    $("#resume-game").css("display","none");
  }
  else if(display_resume) {
    $("#skip-intro").css("display","none");
    $("#menu-button").css("display","none");
    $("#resume-game").css("display","block");
  }
  else if(no_menu) {
    $("#skip-intro").css("display","none");
    $("#menu-button").css("display","none");
    $("#resume-game").css("display","none");
  }
  else {
    $("#skip-intro").css("display","none");
    $("#menu-button").css("display","block");
    $("#resume-game").css("display","none");
  }

  seth("display_resume",false);


  var healthDisplay = geth("healthDisplay");
  var health = geth("health");
  var maxHealth = geth("maxHealth");
  if(healthDisplay) { $("#healthBar").css("display","block");  setTimeout(function(){ updateValueHealth(health,maxHealth); }, 200); }
  else { $("#healthBar").css("display","none"); updateValueHealth(health,maxHealth); }

  var enemyHealthDisplay = geth("enemyHealthDisplay");
  var enemyHealth = geth("enemyHealth");
  var enemyMaxHealth = geth("enemyMaxHealth");
  if(enemyHealthDisplay) { $("#enemyHealthBar").css("display","block");  setTimeout(function(){ updateEnemyHealth(enemyHealth,enemyMaxHealth); }, 200); }
  else { $("#enemyHealthBar").css("display","none"); updateEnemyHealth(enemyHealth,enemyMaxHealth); }

  var enemyName = geth("enemyName");
  $("#nameEnemy").html(enemyName);


  var energyDisplay = geth("energyDisplay");
  var energy = geth("energy");
  var maxEnergy = geth("maxEnergy");
  if(energyDisplay) { $("#energyBar").css("display","block"); updateValueEnergy(energy,maxEnergy); }
  else { $("#energyBar").css("display","none"); updateValueEnergy(energy,maxEnergy); }

  setDayDisplay();
  setLevelDisplay("sight");
  setLevelDisplay("speech");
  setLevelDisplay("touch");


  var in_act3 = geth("in_act3");

  if(in_act3){
    var sight = parseInt(geth("sight"));
    $("#mood-level").html("");
    $("#mood-text").css("display","block");
    
    $("#enrich-level").html("");
    $("#enrich-text").css("display","none");

    $("#silence-text").html("").css("opacity","100%");
    $("#silence-text").html("").css("opacity","50%");

    $("#trust-text").css("display","none");
    $("#calm-text").css("display","none");
    $("#happy-text").css("display","none");

    setInfoDisplay("trust-act3","astarion_trust",20,2);
    if(geth("his_attention_display") == true) setInfoDisplay("his-attention","his_attention",geth("his_attention_max"),0);
    else $("#his-attention-text").css("display","none");
    if(geth("escape_display") == true) setInfoDisplay("escape","escape",geth("escape_max"),0);
    else $("#escape-text").css("display","none");
    
    setLinkDisplay("astarion");
    setLinkDisplay("tomb");
    setLinkDisplay("practice");
    $("#astarion-link").html("Watch");
    $("#tomb-link").html("Explore");
    $("#practice-link").html("Inventory");

    $("#learnBar").css("display","none");


  } else {
    var mood = ucfirst(geth("astarion_mood"));
    var sight = parseInt(geth("sight"));
    $("#mood-level").html(mood);
    if(sight >= 3) $("#mood-text").css("display","block");
    else $("#mood-text").css("display","none");


    var enrich = geth("vampire_enrichment_score");
    $("#enrich-level").html(enrich);
    if(sight >= 5) $("#enrich-text").css("display","block");
    else $("#enrich-text").css("display","none");

    var astarion_interacted = geth("astarion_interacted");
    if(astarion_interacted) $("#silence-text").html("Silence Broken").css("opacity","100%");
    else $("#silence-text").html("Silent").css("opacity","50%");

    $("#trust-act3-text").css("display","none");
    $("#his-attention-text").css("display","none");
    $("#escape-text").css("display","none");

    setInfoDisplay("trust","astarion_trust",20,2);
    setInfoDisplay("calm","calm_value",10,4);
    setInfoDisplay("happy","happy_value",10,4);

    setLinkDisplay("astarion");
    setLinkDisplay("tomb");
    setLinkDisplay("practice");
    $("#astarion-link").html("Find Astarion");
    $("#tomb-link").html("Explore Tomb");
    $("#practice-link").html("Practice Existing");


    var learnDisplay = geth("learnDisplay");
    var currentLearning = geth("currentLearning");
    var maxLearning = geth("maxLearning");
    if(learnDisplay) { $("#learnBar").css("display","block"); updateValueLearn(currentLearning,maxLearning); }
    else $("#learnBar").css("display","none");

    var currentStat = geth("currentStat");
    var learnType = geth("learnType");
    $("#learn-level").html("Lv.  " + currentStat);
    $("#learn-type").html(learnType);
  }







}

function setDayDisplay(){
  var day = geth("day");
  $("#day-level").html(day);
  if(day > 151) $("#day-stat-text").css("display","block");
  else $("#day-stat-text").css("display","none");
}

function setLevelDisplay(type){
  var level = geth(type);
  $("#"+type + "-level").html("Lv. "+level);
  if(level > 0) $("#"+type + "-text").css("display","block");
  else $("#"+type + "-text").css("display","none");
}

function setInfoDisplay(name,variable,max,sightRequired){
  var sight = parseInt(geth("sight"));
  var value = geth(variable);

  var text = value + "/" + max;

  var astarion_mood = geth("astarion_mood");
  if(name == "calm" && astarion_mood == "calm") text = max + "/" + max;
  if(name == "calm" && astarion_mood == "happy") text = max + "/" + max;
  if(name == "happy" && astarion_mood == "happy") text = max + "/" + max;

  $("#"+name + "-level").html(text);
  if(sight >= sightRequired) $("#"+name + "-text").css("display","block");
  else $("#"+name + "-text").css("display","none");
}

function setLinkDisplay(name){
  var display = geth(name+"_link_display");
  if(display) $("#"+name + "-link").css("cursor","pointer").css("opacity","1");
  else $("#"+name + "-link").css("cursor","default").css("opacity","0");
  seth(name+"_link_display",false)
}

function navigateTo(name,e){


  if($(e).css("opacity") == 1){
    var day = geth("day");
    var in_act3 = geth("in_act3");
    var currentArea = geth("currentArea");


    if(name == "practice" && in_act3 == true){
      seth("sequence",0);
      seth("basePassage",geth("currentPassage"));
      goToPassage("Player Inventory");
    }
    else if(name == "astarion" && in_act3 == true){
      seth("sequence",0);
      if(currentArea == "Chamberlain Office") currentArea = "Office";
      goToPassage(currentArea + " Watch");
    }
    else if(name == "tomb" && in_act3 == true){
      seth("sequence",0);
      if(currentArea == "Office") currentArea = "Chamberlain Office";
      goToPassage(currentArea);
    }
    else if(name == "practice"){
      if(day == 151) { seth("sequence",0); goToPassage("Darkness"); }
      else { seth("sequence",0); goToPassage("Practice Existing"); }
    }
    else if(name == "astarion"){
      if(day == 151) { seth("sequence",4); goToPassage("Exploring The Tomb"); }
      else { seth("sequence",0); goToPassage("Astarion"); }
    }
    else if(name == "tomb"){
      if(day == 151) {
        seth("sequence",0);
        if(geth("sight") > 0) goToPassage("Exploring The Tomb");
        else if(geth("touch") > 0) goToPassage("Blind In The Tomb");
        else goToPassage("A Voice In The Dark");
      }
      else { seth("sequence",0); goToPassage("The Tomb"); }
    }
  }


}

function toggleDisplay(id,displayValue){
  if(displayValue) $("#"+id).css("opacity","1");
  else $("#"+id).css("opacity","0");
}


function resetEverything(){
  localStorage.clear();
  saveraw("Achievements","");
}
window.resetEverything = resetEverything;



function installHUD(){


  let insert_code = `

  <div class="prg-border" id="healthBar">
    <div class="prg-bar" id="bar1Health"></div>
    <div class="prg-text" id="text1">25/52</div>
    <div class="prg-name-text" id="nameText1">Astarion <span class="prg-level-text">Lv. 7</span></div>
    <div class="prg-right-end after-right-darkred" id="right1"></div>
    <div class="prg-left-end after-left-brightred" id="left1"></div>

    <div class="prg-info-text" id="infoText2">
      <span id="mood-text" class="prg-info-stats-single"><span id="mood-level" class="prg-stat-level">Bored</span></span>
      <span id="trust-text" class="prg-info-stats-single">Trust <span id="trust-level" class="prg-stat-level">1/20</span></span>
      <span id="calm-text" class="prg-info-stats-single">Calm <span id="calm-level" class="prg-stat-level">0/10</span></span>
      <span id="happy-text" class="prg-info-stats-single">Happy <span id="happy-level" class="prg-stat-level">0/10</span></span>


      <span id="trust-act3-text" class="prg-info-stats-single">Trust <span id="trust-act3-level" class="prg-stat-level">1/20</span></span>
      <span id="his-attention-text" class="prg-info-stats-single">His Attention <span id="his-attention-level" class="prg-stat-level">0/20</span></span>
      <span id="escape-text" class="prg-info-stats-single">Escape <span id="escape-level" class="prg-stat-level">0/20</span></span>


      <span id="enrich-text" class="prg-info-stats-single">Vampire Enrichment <span id="enrich-level" class="prg-stat-level">0</span></span>
      <span id="silence-text" class="prg-info-stats-single">Silent</span>
    </div>
  </div>

  <div class="prg-border" id="enemyHealthBar">
    <div class="prg-bar" id="bar2Health"></div>
    <div class="prg-text" id="textEnemyHealth">25/52</div>
    <div class="prg-name-text" id="nameEnemy">Vengeful Ghost</div>

    <div class="prg-info-text" id="infoEnemy">
      <span id="status1-text" class="prg-info-stats-single"><span id="status1-text" class="prg-stat-level"></span></span>
      <span id="status2-text" class="prg-info-stats-single">Trust <span id="status2-level" class="prg-stat-level"></span></span>
      <span id="status3-text" class="prg-info-stats-single">Calm <span id="status3-level" class="prg-stat-level"></span></span>
      <span id="status4-text" class="prg-info-stats-single">Happy <span id="status4-level" class="prg-stat-level"></span></span>
    </div>
  </div>

  <div class="prg-border" id="energyBar">
    <div class="prg-black-box">
      <div class="prg-inner-bar-small"></div>
      <div class="prg-bar-small" id="bar2"><div class="prg-text-small" id="text2">10</div></div>
    </div>
    <div class="prg-right-end" id="right2"></div>
    <div class="prg-left-end" id="left2"></div>
    <div class="prg-stats-text" id="statsText2">
      <span id="day-stat-text" class="prg-stats-single">Day <span id="day-level" class="prg-stat-level">151</span></span>
      <span id="sight-text" class="prg-stats-single">Sight <span id="sight-level" class="prg-stat-level">Lv. 1</span></span>
      <span id="speech-text" class="prg-stats-single">Speech <span id="speech-level" class="prg-stat-level">Lv. 1</span></span>
      <span id="touch-text" class="prg-stats-single">Touch <span id="touch-level" class="prg-stat-level">Lv. 1</span></span>
    </div>

    <div class="prg-link-movement" id="linkMoveArea">
      <span id="astarion-link" class="prg-link-button" onClick='navigateTo(\"astarion\",this)'>Find Astarion</span>
      <span id="tomb-link" class="prg-link-button" onClick='navigateTo(\"tomb\",this)'>Explore Tomb</span>
      <span id="practice-link" class="prg-link-button" onClick='navigateTo(\"practice\",this)'>Practice Existing</span>
    </div>
    
  </div>


    <div class="prg-black-box" id="learnBar">
      <div class="prg-inner-bar-small"></div>
      <div class="prg-bar-small" id="bar3"><div class="prg-text-small" id="text3">1</div></div>
      <div class="prg-learn-text" id="learnText3">
        <span id="learn-type" class="prg-learning-stat">Sight</span>
        <span id="learn-level" class="prg-learning-level">Lv. 1</span>
      </div>
    </div>

    

  <span id='nav-container' class='nav_button hud'>
   <div id='menu-contents'>
      <div id='elsewhere-item' class='menu-item'><a class='clickable nav_button' onClick='goToPassage(\"Elsewhere\")'>Elsewhere</a></div>
      <div id='menu-button' class='menu-item'><a class='clickable nav_button' onClick='goToMenu(\"Menu_Restore\");'>Menu</a></div>
      <div id='skip-intro' class='menu-item'><a class='clickable nav_button' onClick='skipIntro();'>Skip Intro</a></div>
      <div id='resume-game' class='menu-item'><a class='clickable nav_button' onClick='resumeGame();'>Resume</a></div>
   </div>
</span> `;
  $("body").append(insert_code);
}
window.installHUD = installHUD;

window.unloadHUD = function(){
  $("body").append($("tw-story"));
}







var images = new Array();
var audios = new Array();
var fonts = new Array();
var preloadImages = [
  "./silenceImages/columnsTeethFrame.jpg",
  "./silenceImages/columnsTeethFrameCold.jpg",
  "./silenceImages/columnsTeethFrameVeryCold.jpg",
  "./silenceImages/coffinFrame.jpg",
  "./silenceImages/crestFrame.jpg",
  "./silenceImages/crestFrameCold.jpg",
  "./silenceImages/crestFrameVeryCold.jpg",
  "./silenceImages/widesmile.jpg",
  "./silenceImages/columnsFrame.jpg",
  "./silenceImages/columnsFrameCold.jpg",
  "./silenceImages/columnsFrameVeryCold.jpg",
  "./silenceImages/hallwaySpike.jpg",
  "./silenceImages/hallwaySpikeBroken.jpg",
  "./silenceImages/SilenceTitle.png"
];
var preloadAudio = [
  "./sounds/aa_clue.ogg",
  "./sounds/aa_damage.ogg",
  "./sounds/aa_chime.ogg",
  "./sounds/aa_clock_ticks.ogg",
  "./sounds/aa_clock_tick3.ogg",
  "./sounds/aa_clock_tick2.ogg",
  "./sounds/aa_clock_tick1.ogg",
  "./sounds/aa_tap2.ogg",
  "./sounds/aa_tap.ogg"
];
var preloadFonts = [
  "./fonts/Wisper-Regular.woff",
  "./fonts/Domestic_Manners.woff",
  "./fonts/AlegreyaRegular.woff"
];
function preload() {
  for (var i = 0; i < preloadImages.length; i++) {
    images[i] = new Image();
    images[i].src = preloadImages[i];
  }
  for (var i = 0; i < preloadAudio.length; i++) {
    audios[i] = new Audio(preloadAudio[i]);
  }
  for (var i = 0; i < preloadFonts.length; i++) {
    fonts[i] = new Audio(preloadFonts[i]);
  }
}


document.onreadystatechange = function() {
    if (document.readyState !== "interactive" && document.querySelector("#loader") != null) {
        document.querySelector("#loader").style.visibility = "visible";
    } else if (document.querySelector("#loader") != null) {
        document.querySelector("#loader").style.display = "none";
    }
};