
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 obj = JSON.parse(data);
  obj[1].variables.currentGameDate = 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) );
        } 
    });


  function selectThought(e){

    let used_thoughts = geth("used_thoughts");
    if(!used_thoughts.includes(e.name+"/"+geth("target"))) used_thoughts.push(e.name+"/"+geth("target"));
    console.log(e.name+"/"+geth("target"));

    seth("thought",e.name);
    seth("action","think");
    seth("think_time",0);
    seth("actionSequence",0);
    let passage = geth("basePassage");
    goToPassage(passage + " Thought");

    $('#modal-container').addClass('out');
    $('body').removeClass('modal-active');
  }
  window.selectThought = selectThought;

  function selectItem(e){
    seth("item",e.name);
    seth("action","item");
    seth("think_time",0);
    seth("actionSequence",0);
    let passage = geth("basePassage");
    goToPassage(passage + " Item");

    $('#modal-container').addClass('out');
    $('body').removeClass('modal-active');
  }
  window.selectItem = selectItem;

  function dropItem(e){
    seth("item",e.name);
    seth("think_time",0);
    goToPassage("Drop Item");

    $('#modal-container').addClass('out');
    $('body').removeClass('modal-active');
  }
  window.dropItem = dropItem;


  function populateThoughts(){
    $("#modal-prompt").html("Choose a thought:");
    $("#list-things").html("");
    let to_append = "";
    let thoughts = geth("thoughts");
    let used_thoughts = geth("used_thoughts");
    let target = geth("target");

    thoughts.forEach(function (item, index) {
      if(used_thoughts.includes(item+"/"+target) && item != "I should take this.")
        to_append += "<i style='color: darkslategray;'><a name=\""+item+"\" onclick='selectThought(this)' class='inv-item-header cast-spell' style='color: darkslategray;'>"+item+"</a> / tried</i><br><br>";
      else
        to_append += "<a name=\""+item+"\" onclick='selectThought(this)' class='inv-item-header cast-spell'>"+item+"</a><br><br>";
    });
    if(thoughts.length == 0) to_append = "<i>I am not thinking anything of note.</i><br><br><br><br>";
    $("#list-things").append(to_append);
  }


  function populateItems(){
    $("#modal-prompt").html("Choose an item:");
    $("#list-things").html("");
    let to_append = "";
    let thoughts = geth("items");
    thoughts.forEach(function (item, index) {
      to_append += "<a name=\""+item+"\" onclick='selectItem(this)' class='inv-item-header cast-spell'>"+item+"</a> / <a name=\""+item+"\" onclick='dropItem(this)' class='inv-item-header cast-spell'>put back</a><br><br>";
    });
    if(thoughts.length == 0) to_append = "<i>I have nothing.</i><br><br><br><br>";
    if(thoughts.length != 0){
      to_append += "<a id='drop-everything' onclick='confirm(\"drop-everything\")' class='inv-item-header cast-spell'>put everything back</a>";
      to_append += "<a id='drop-everything-confirm' onclick='goToPassage(\"Drop Everything\")' class='inv-item-header cast-spell' style='display: none; color: green;'>confirm</a> ";
      to_append += "<a id='drop-everything-cancel' onclick='cancelConfirm(\"drop-everything\")' class='inv-item-header cast-spell' style='display: none; color: red;'>cancel</a><br><br>";
    }
    $("#list-things").append(to_append);
  }


  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 getResume(){
  var canResume = getraw("CanResume"); 
  if(canResume == "TRUE") return true;
  else return false;
}
window.getResume = getResume;

function setResume(canResume){
  if(canResume){
    saveraw("CanResume","TRUE");
    setHarloweVariable("CanResume",true);
  }else{
    saveraw("CanResume","FALSE");
    setHarloweVariable("CanResume",false);
  }
}
window.setResume = setResume;


function savegame(title,name) {

    var today = new Date();
    var todayString = today.toLocaleString();
    seth("currentGameDate",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"){
          setHarloweVariable("MenuSave",name);
          setResume(true);
        }
        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();
        loadBackground();
        loadHUD();

        
        _engine.goToPassage(_state.passage);

    } 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 + " shewaitsbelow " + _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)  {    return string.charAt(0).toUpperCase() + string.slice(1); }
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","");

}

function changeBackgroundHtml(image,reference,back){
  if(image == "") { $("html,body").css("background",""); }
  else if(image == "below-title-spider"){ $(back).css("background-size","100% 100%").css("background-position","right bottom").css("background-repeat",""); }
  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('./below/" + image + ext + "')";

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

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

  } else if(back_2_op == 0){
    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("."));
    changeBackgroundHtml(old_image,old_ref,"#back1");
    $("#back1").css("opacity", 1);

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

  }else {
    $("#back1").css("opacity", 0);
    $("#back2").css("opacity", 1);
    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("DisplayFullHealth")) perm += "DisplayFullHealthTrue"; else perm += "DisplayFullHealthFalse";
  if(getHarloweVariable("SoundEffects")) perm += "SoundEffectsTrue"; else perm += "SoundEffectsFalse";
  if(getHarloweVariable("Music")) perm += "MusicTrue"; else perm += "MusicFalse";
  if(getHarloweVariable("WordSearches")) perm += "WordSearchesTrue"; else perm += "WordSearchesFalse";
  if(getHarloweVariable("PhilosophyDisplay")) perm += "PhilosophyDisplayTrue"; else perm += "PhilosophyDisplayFalse";

  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("DisplayFullHealthTrue")) setHarloweVariable("DisplayFullHealth",true); else setHarloweVariable("DisplayFullHealth",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("WordSearchesFalse")) setHarloweVariable("WordSearches",false); else setHarloweVariable("WordSearches",true); 
    if(perm.includes("PhilosophyDisplayFalse")) setHarloweVariable("PhilosophyDisplay",false); else setHarloweVariable("PhilosophyDisplay",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");

  if(achievements.includes(achievement) == false){
    displayAlertSpeed("Achievement: " + achievement,1000,2000);
    playAudio("aa_chime");
    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(){
  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.goToInventory = function(){ 
  savegame("MenuSave","currentPassage");
  var ReturnFlag = geth("ReturnFlag");
  if(ReturnFlag == "BLANK"){
    var thoughts_inventory = geth("thoughts_inventory");
    if(thoughts_inventory) goToPassage("Menu_Thoughts");
    else goToPassage("Menu_Inventory");
  }
  savegame("ReturnFlag","BLANK");
}

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",14);
  goToPassage("Absence Intro");
}




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();
  }

}


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.loadHUD = function(){
  $("#game-frame").css("z-index","10");
  $("#game-frame").css("opacity","1");
  $("#area-description").append($("tw-story"));

  refreshHUD();
}





window.refreshHUD = function(){

  let hide_hud = geth("hide_hud");

  if(hide_hud){
    toggleDisplay("area-memory",false);
    toggleDisplay("area-health",false);
    toggleDisplay("area-self",false);
    toggleDisplay("button-think",false);
    toggleDisplay("button-items",false);
    toggleDisplay("button-notes",false);
    toggleDisplay("location",false);
    toggleDisplay("time-limit",false);
    toggleDisplay("area-navigation",false);



  }else {


    toggleDisplay("area-navigation",true);

    toggleDisplay("menu-contents",!geth("noMenu"));

    toggleDisplay("area-memory",geth("navigation_display"));

    toggleDisplay("area-memory",geth("memory_display"));
    $('#stat-memory .bar').css("width", geth("memory")+"%");
    $("#label-memory").html(geth("memoryText"));
    toggleDisplay("area-health",geth("health_display"));
    $('#stat-health .bar').css("width", geth("health")+"%");
    toggleDisplay("area-self",geth("self_display"));
    $('#stat-self .bar').css("width", geth("self")+"%");


    toggleDisplay("button-think",geth("button_think_display"));
    if(geth("button_think_display")){
      let think_time = geth("think_time");
      if(think_time == 0) $("#button-think").css("opacity","0.25");
      else $("#button-think").css("opacity","1");
    }

    toggleDisplay("button-items",geth("button_items_display"));
    if(geth("button_items_display")){
      let think_time = geth("think_time");
      if(think_time == 0) $("#button-items").css("opacity","0.25");
      else $("#button-items").css("opacity","1");
    }

    toggleDisplay("button-notes",geth("button_notes_display"));
    if(geth("button_notes_display")){
      let think_time = geth("think_time");
      if(think_time == 0) $("#button-notes").css("opacity","0.25");
      else $("#button-notes").css("opacity","1");
    }

    let location_name = geth("location_name");
    seth("location_name","")
    if(location_name !== "") $("#current-location").html(location_name);

    $("#north-btn").html(geth("north_text"));
    if(geth("north_text") == "") $("#north-btn").css("opacity","0");
    else if(location_name == "") $("#north-btn").css("opacity","0.25");
    else $("#north-btn").css("opacity","1");
    
    $("#south-btn").html(geth("south_text"));
    if(geth("south_text") == "") $("#south-btn").css("opacity","0");
    else if(location_name == "") $("#south-btn").css("opacity","0.25");
    else $("#south-btn").css("opacity","1");

    $("#west-btn").html(geth("west_text"));
    if(geth("west_text") == "") $("#west-btn").css("opacity","0");
    else if(location_name == "") $("#west-btn").css("opacity","0.25");
    else $("#west-btn").css("opacity","1");

    $("#east-btn").html(geth("east_text"));
    if(geth("east_text") == "") $("#east-btn").css("opacity","0");
    else if(location_name == "") $("#east-btn").css("opacity","0.25");
    else $("#east-btn").css("opacity","1");


    if(geth("$memory") == 100 && geth("$game_phase") == "Searching for her"){
      if(!$("#stat-memory").hasClass("pulse-animation")) $("#stat-memory").addClass("pulse-animation");
    } else{
      if($("#stat-memory").hasClass("pulse-animation")) $("#stat-memory").removeClass("pulse-animation");
    }



  

    toggleDisplay("time-limit",geth("time_limit_display"));
    $("#time-limit").html(geth("$time_limit_text"));



  }

  let area_picture = geth("area_picture");
  if(area_picture != "" && area_picture != undefined)  $('#area-picture').css("background-image", "url('./absenceImages/" + area_picture + ".jpg')");


  var vertical_scroll = checkScrollBar("area-description", 'vertical');
  if(vertical_scroll) $("#scroll-cue").css("display","block"); else $("#scroll-cue").css("display","none");

  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");
  if(in_intro) {
    $("#skip-intro").css("display","block");
    $("#menu-button").css("display","none");
  }
  else { $("#skip-intro").css("display","none"); $("#menu-button").css("display","block"); }

  var display_resume = geth("display_resume");
  seth("display_resume",false);
  if(display_resume) $("#resume-game").css("display","block"); else $("#resume-game").css("display","none");

}

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

window.unloadHUD = function(){
  $("#game-frame").css("z-index","-10");
  $("#game-frame").css("opacity","0");
  $("body").append($("tw-story"));
}

window.updateImage = function(newImage){
  seth("area_picture",newImage);
}

window.hoverButton = function(button,hovering){
  let id = button.id;

  if(hovering){

    let alert_text = "";

    if(id.includes("-think")){
      let think_time = geth("think_time");
      if(think_time == 0) alert_text = "Not now.";
      else alert_text = "Should I think about this?";
    } 

    if(id.includes("-items")){
      let think_time = geth("think_time");
      if(think_time == 0) alert_text = "Not now.";
      else alert_text = "Should I use something?";
    } 

    if(id.includes("-notes")){
      let think_time = geth("think_time");
      if(think_time == 0) alert_text = "Not now.";
      else alert_text = "I could consult my notes.";
    } 

    $("#alert-tools").html(alert_text);
    $("#alert-tools").css("opacity","1");

  } else {
    $("#alert-tools").css("opacity","0");
  }

}


window.clickButton = function(button){
  let id = button.id;


  if(id.includes("-btn")){

    let direction = id.replace("-btn","");
    seth("sequence",0);

    if(id === direction+"-btn" && $("#"+direction+"-btn").css("opacity") == "1")
      goToPassage(geth(direction+"_text"))


  } 
  else if(id.includes("-think")){
    let think_time = geth("think_time");

    if(think_time != 0){
      populateThoughts();
      $('#modal-container').removeAttr('class').addClass('two');
      $('body').addClass('modal-active');
    }
  }else if(id.includes("-items")){
    let think_time = geth("think_time");

    if(think_time != 0){
      populateItems();
      $('#modal-container').removeAttr('class').addClass('two');
      $('body').addClass('modal-active');
    }
  }else if(id.includes("-notes")){
    let think_time = geth("think_time");

    if(think_time != 0){
      goToPassage("Current Notes");
    }
  }

  button.blur();
  $("#alert-tools").css("opacity","0");

}







 





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



function showTime(h,m){
  var session = "AM";
  
  if(h == 0){ h = 12; }
  if(h > 12){ h = h - 12; session = "PM"; }
  
  h = (h < 10) ? "0" + h : h;
  m = (m < 10) ? "0" + m : m;
  
  var time = h + ":" + m + " " + session;
  $("#clock").html(time);
  
}
window.showTime = showTime;

window.addMinutes = function(min){
  addMinutesSilent(min);

  let clock_tick = geth("clock_tick");
  playAudio("aa_clock_tick" + clock_tick);
  clock_tick++;
  if(clock_tick>3) clock_tick = 1;
  seth("clock_tick",clock_tick);
}
window.addMinutes = addMinutes;


window.addMinutesSilent = function(min){
  let clock_hour = geth("clock_hour");
  let clock_minute = geth("clock_minute");

  clock_minute += min;
  while(clock_minute > 59){
    clock_minute -= 60;
    clock_hour++;
    if(clock_hour > 24) clock_hour = 0;
  }
  seth("clock_hour",clock_hour);
  seth("clock_minute",clock_minute);
}
window.addMinutes = addMinutes;



function installHUD(){


  let insert_code = `
<div id='game-frame'>
   <div id='area-sidebar'>
      <div id='area-picture'></div>
      <div id='area-fill'> </div>
      <div id='area-navigation'>
         <div id='current-location'></div>
         <button id='north-btn' class='ui button nav-text' onclick='clickButton(this)' onmouseover='hoverButton(this,true)' onmouseout='hoverButton(this,false)'></button>
         <button id='south-btn' class='ui button nav-text' onclick='clickButton(this)' onmouseover='hoverButton(this,true)' onmouseout='hoverButton(this,false)'></button>
         <button id='east-btn' class='ui button nav-text' onclick='clickButton(this)' onmouseover='hoverButton(this,true)' onmouseout='hoverButton(this,false)'></button>
         <button id='west-btn' class='ui button nav-text' onclick='clickButton(this)' onmouseover='hoverButton(this,true)' onmouseout='hoverButton(this,false)'></button>
         
      </div>
   </div>
   <div id='area-scene'>
      <div id='area-text' >
          <div id='scroll-cue'>⌄</div>
          <div id='area-description'>  </div>
      </div>
      <div id='area-stats'>
        <div id='area-tools'>
          <div id='alert-tools'></div>
          <div class='button-tools'><button id='button-think' class='ui button' onclick='clickButton(this)' onmouseover='hoverButton(this,true)' onmouseout='hoverButton(this,false)'>THINK</button></div>
          <div class='button-tools'><button id='button-items' class='ui button' onclick='clickButton(this)' onmouseover='hoverButton(this,true)' onmouseout='hoverButton(this,false)'>ITEMS</button></div>
          <div class='button-tools'><button id='button-notes' class='ui button' onclick='clickButton(this)' onmouseover='hoverButton(this,true)' onmouseout='hoverButton(this,false)'>NOTES</button></div>
          <div class='button-tools'><button id='button-wait' class='ui inverted button'>WAIT</button></div>
        </div>
        <div id='area-memory'>
          <div id='label-memory' class='text-shimmer'>I remember my brother</div>
          <div id='stat-memory' class='ui black inverted progress' data-percent='34' >
             <div class='bar'>
                <div class='progress'></div>
             </div>
          </div>
        </div>
      </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\");'>Main Menu</a></div>
      <div id='skip-intro' class='menu-item'><a class='clickable nav_button' onClick='skipIntro();'>Skip Intro</a></div>
   </div>
</span>
</div>
<div id='resume-game' class='hud'><a class='clickable' onClick='resumeGame();'> Resume Game</a></div>
<div id='modal-container'>
   <div class='modal-background'>
      <div class='modal'>
         <h2 id='modal-prompt'>Choose a thought:</h2>
         <div id='list-things'></div>
         <div class='actions'>
            <div id='stop-think-button' class='ui red basic cancel button'> Cancel</div>
         </div>
      </div>
   </div>
</div> `;


  $("body").append(insert_code);

$('#stop-think-button').click(function(){

  $('#modal-container').addClass('out');
  $('body').removeClass('modal-active');
});

$('.modal-background').click(function(e){

  if($(e.target).attr('class') == "modal-background"){
    $('#modal-container').addClass('out');
    $('body').removeClass('modal-active');
  }
});

$( "#area-description" ).on( "scroll", function() {

  var element = $( "#area-description" );

    let scrollTop = $("#area-description").scrollTop();
    let areaHeight = $("#area-description").height();
    let storyHeight = $("tw-story").height();
    if(scrollTop + areaHeight > storyHeight + 34)
        $("#scroll-cue").css("display","none");

  
});

}
window.installHUD = installHUD;






var images = new Array();
var audios = new Array();
var fonts = new Array();
var preloadImages = [
  "./menu/menuAbsence.jpg",
  "./absenceImages/anthony.jpg",
  "./absenceImages/bedroom0.jpg",
  "./absenceImages/bedroom1_shape.jpg",
  "./absenceImages/bedroom1_void.jpg",
  "./absenceImages/birdSketch1.jpg",
  "./absenceImages/black.jpg",
  "./absenceImages/bookshelf1.jpg",
  "./absenceImages/death-screamOutOfTheLight.jpg",
  "./absenceImages/hallway6_dark.jpg",
  "./absenceImages/hallway5_lit.jpg",
  "./absenceImages/kitchen1.jpg",
  "./absenceImages/livingroom2.jpg",
  "./absenceImages/miriamAsleep.jpg",
  "./absenceImages/miriamAwake1.jpg",
  "./absenceImages/miriamAwake2.jpg",
  "./absenceImages/office1.jpg",
  "./absenceImages/office1_missing_person.jpg",
  "./absenceImages/piano.jpg",
  "./absenceImages/plants.jpg",
  "./absenceImages/sewingMachine.jpg",
  "./absenceImages/sewingRoom3.jpg",
  "./absenceImages/sky1.jpg",
  "./absenceImages/sparrow1.jpg",
  "./absenceImages/sparrow2.jpg",
  "./absenceImages/sparrow3.jpg",
  "./absenceImages/street1.jpg",
  "./absenceImages/white.jpg",
  "./absenceImages/yard2.jpg"
];
var preloadAudio = [
  "./sounds/aa_clue.ogg",
  "./sounds/aa_damage.ogg",
  "./sounds/aa_chime.ogg",
  "./sounds/aa_lightswitch.ogg",
  "./sounds/aa_rumble.ogg",
  "./sounds/env_nothing_left.ogg",
  "./sounds/env_soft_wail.ogg"
];
var preloadFonts = [
  "./fonts/Wisper-Regular.woff",
  "./fonts/Domestic_Manners.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]);
  }
}
preload();
