// Requires:
// - mh_stat_ranks_shield.js
// - mh_stat_traps.js
// - mh_stat_locations_keys.js
// - mh_stat_mice.js
// - mh_stat_cheeses.js
// - mh_stat_loot.js

$(document).ready(function(){

  //Fill the divs
  var divTraps = "<select name='h_trap' id='trap'>";
  for (var i=0; i<trap_table.length; i++) {
    divTraps += "<option value="+trap_table[i][_TRAP_ID]+">" + trap_table[i][_TRAP_NAME] + "</option>";
  }
  divTraps += "</select>";
  $('#div_traps').html(divTraps);

  var divBases = "<select name='h_base' id='base'>";
  for (var i=0; i<base_table.length; i++) {
    divBases += "<option value="+base_table[i][_BASE_ID]+">" + base_table[i][_BASE_NAME] + "</option>";
  }
  divBases += "</select>";
  $('#div_bases').html(divBases);

  var divTitles = "<select name='h_title' id='huntertitle'>";
  for (var i=0; i<titles.length; i++) {
    divTitles += "<option value="+i+">" + titles[i] + "</option>";
  }
  divTitles += "</select>";
  $('#div_titles').html(divTitles);

  var divLocations = "<select name='h_location' id='location'>";
  for (var i=0; i<locations.length; i++) {
    divLocations += "<option value="+location_id[i]+">" + locations[i] + "</option>";
  }
  divLocations += "</select>";
  $('#div_locations').html(divLocations);

  var divCheeses = "<select name='h_cheese' id='cheese'>";
  for (var i=0; i<cheeses.length; i++) {
    divCheeses += "<option value="+cheese_id[i]+">" + cheeses[i] + "</option>";
  }
  divCheeses += "</select>";
  $('#div_cheeses').html(divCheeses);

  var divShields = "<select name='h_shield' id='shield'>";
  for (var i=0; i<shields.length; i++) {
    divShields += "<option value="+i+">" + shields[i] + "</option>";
  }
  divShields += "</select>";
  $('#div_shields').html(divShields);

  $('#summarize').click(function(){
    genoutput();
  });
  $('#reset').click(function(){
    $('#inputtext').val('');
  });

  $('#restore_journals').click(function(){
    //Restore input value to that of any input from a POST request
    $('#inputtext').val( $('#input_from_post').val() );
    return false;
  });

  //Disabled form
  //$('#data_form').html('<em class="red">Currently disabled. Please check back later</em>');
});

// Make sure the form is all filled
function validate() {
  var errorMsg = "";
  if ($('#trap').val() == 0)
    errorMsg += "Please select your trap\n";
  if ($('#base').val() == 0)
    errorMsg += "Please select your base\n";
  if ($('#huntertitle').val() == 0)
    errorMsg += "Please select your title\n";
  if ($('#location').val() == 0)
    errorMsg += "Please select your location\n";
  if ($('#cheese').val() == 0)
    errorMsg += "Please select your cheese\n";
  if (errorMsg != "") {
    alert("The following errors were found:\n\n" + errorMsg);
    return false;
  } else {
    // Remove the disable flags from the textareas before sending the post
    $('#data_form textarea').removeAttr('disabled');
    return true;
  }
}

//Globals
//var mouse=["Wound Up White", "Hapless Marionette", "Toy Sylvan", "Impersonator", "Lockpick", "Escape Artist", "Clockwork Samurai", "Flying", "Bandit", "Puppet Master", "Sock Puppet Ghost", "Fencer", "Page", "Stealth", "Cowbell", "Berserker", "Rogue", "Longtail", "Knight", "Phalanx", "Drummer", "Cavalier", "Dancer", "Black Mage", "Fiddler", "Necromancer", "Terra", "Ignis", "Guquin Player", "Zephyr", "Aquos", "Sacred Shrine", "White Mage", "Paladin", "Fiend", "Master Burglar", "Mutated Grey", "Abominable Snow", "Derr Lich", "Elub Lich", "Enslaved Spirit", "Nerg Lich", "Acolyte", "Alchemist", "Alnilam", "Alnitak", "Archer", "Assassin", "Bat", "Bear", "Beast Tamer", "Bionic", "Birthday", "Black Widow", "Bottled", "Briegull", "Brown", "Buccaneer", "Burglar", "Captain", "Caretaker", "Centaur", "Chameleon", "Conjurer", "Conqueror", "Cook", "Cupid", "Cyclops", "Diamond", "Dwarf", "Eagle Owl", "Elf", "Elven Princess", "Fairy", "Finder", "Foxy", "Frog", "Gargoyle", "Gate Guardian", "Ghost", "Glitchpaw", "Goblin", "Gold", "Golem", "Gorgon", "Granite", "Grandfather", "Grey", "Grunt", "Hapless", "Healer", "Harpy", "Hollowhead", "Hydra", "iTunes", "Keeper", "Keeper's Assistant", "Kung Fu", "Leprechaun", "Leviathan", "Lich", "Lycan",  "Master of the Cheese Belt", "Master of the Cheese Claw", "Master of the Cheese Fang", "Master of the Dojo", "Mermaid", "Mintaka", "Mobster", "Mole", "Monk", "Monster", "Moosker", "Mummy","Mutated White", "Mystic", "Narrator", "Nibbler", "Ninja", "Nomad", "Ooze", "Pack", "Pathfinder", "Pinchy", "Pirate", "Ravenous Zombie", "Reaper", "Renegade", "Salt Water Snapper", "Samurai", "Scavenger", "Scout", "Seer", "Shaman", "Shelder", "Shipwrecked", "Siren", "Skeleton", "Soothsayer", "Spectre", "Spellbinder", "Spider", "Squeaken", "Steel", "Student of the Cheese Belt", "Student of the Cheese Claw", "Student of the Cheese Fang", "Swabbie", "Sylvan", "Taleweaver", "Costumed Tiger", "Tiger", "Trailblazer", "Treant", "Troll", "Vampire", "Vanquisher", "Water Nymph", "White", "Wicked Witch of Whisker Woods", "Wiggler", "Wight", "Wordsmith", "Worker", "Zombie", "Aged", "Guardian", "Gladiator", "Derr Chieftain", "Defender", "Slayer", "Nerg Chieftain", "Elder", "Protector", "Champion", "Elub Chieftain", "Chitinous", "Fetid Swamp", "Jurassic", "Magma Carrier", "Primal", "Stonework Warrior", "Giant Snail", "Terror Knight", "Sorcerer", "Whelpling", "Dragon", "Draconic Warden", "Rockstar", "Candy Cane", "Christmas Tree", "Nutcracker", "Ornament", "Present", "Scrooge", "Stocking", "Toy", "Frozen", "Frosty Snow", "New Year's", "Hope", "Romeo", "Romeno", "Dumpling Chef", "Terrible Twos", "Dojo Sensei", "Curious Chemist", "Silth", "Nugget", "Core Sample", "Rock Muncher", "Industrious Digger", "Stone Cutter", "Demolitions", "Miner", "Lambent Crystal", "Itty-Bitty Burroughs", "Subterranean", "Big Bad Burroughs", "Pigmy Swarm", "Balack the Banished", "Brimstone", "Davy Jones", "Riptide", "Twisted Fiend", ""];

//Mouse catch and attract
var mouse_catches = new Array(n_mice);
var mouse_attractions = new Array(n_mice);

//Every loot item should have a corresponding value in the gold and point array
/*
var loot = [
"cheddar cheese", "marble cheese", "swiss cheese", "brie cheese",
"SUPER|brie", "radioactive blue cheese", "moon",
"lab research worth 500 bonus points",
"lab research worth 750 bonus points","lab research worth 1000 bonus points",
"combat research worth 750 bonus points",
"combat research worth 1250 bonus points",
"greater radioactive blue cheese curd potion", "radioactive blue cheese curd potion",
"greater brie alchemy potion", "brie alchemy potion", "Corrupted Radioactive Blue Potion",
"Gnawnia Map", "Burroughs Laboratory Map", "Key to the Town of Digby",
"Tattered Mousoleum Map", "Shredded Furoma Map Piece", "Ticket to the Burroughs Bazaar",
"token of the cheese claw", "token of the cheese fang", "token of the cheese belt",
"master fang shard", "master belt shard", "master claw shard", "onyx stone",
"ambush trap blueprints",
"magically wrapped gift", "gift",
"Satchel of Gold worth 250 gold","Satchel of Gold worth 500 gold",
"Satchel of Gold worth 750 gold","Satchel of Gold worth 1000 gold",
"splintered wood", "Scrap Metal", "coal", "stale cheese[s]*", "meteorite piece[s]*",
"birthday gift", "fancy birthday gift","keeper's candle", "rune", "Ancient Cheese Curd Potion",
"whisker woods clearing map piece", "Gnarled Tree Map Piece", "Gnarled Cheese Curd Potion",
"Mysterious Box",
"Compass", "Delicious Stone", "Ethereal Rope", "Rope", "Savoury Vegetables", "Seashell", "Sextant", "Telescope",
"Ancient Spear", "Bolt of Cloth", "Blue Pepper Seed", "Red Pepper Seed", "Yellow Pepper Seed", "thorned Vine", "Rhino Horn", "Stale super brie", "Ancient Frayed Blueprint", "Ancient Mangled Blueprint", "Ancient Ripped Blueprint", "Ancient Relic Staff", "Encrusted Metal of Time", "Engraved Solid Stone Slab", "Fire Salt", "Hinge of Eternity", "Timeless Mystic Gem",
"Ship Blueprints", "Runic Cheese Curd Potion", "Dragon's Chest", "Coconut , Milk", "piece[s]* of Rockforth cheese", "Ronza's Red Satchel of Surpise", "Ronza's Green Satchel of Surpise", "Ronza's Blue Satchel of Surpise", "Icing Sugar", "Candies", "Plank of Gingerbread",
"Satchel of Gold worth 5000 gold",
"Tiger Mask", "DLU+", "Ox Mask", "DHU-",
"Intimidating Pincher", "Nanny Bolts", "Timeout Hour Glass", "Wicked Gnarly Cheese Curd Potion", "Chrome Nanite Coating", "Superstar Nanny Glasses", "Living Shard", "piece[s]* of Limelight", "Monolith Base", "Onyx Mallet Blueprints",
"Vanilla Bean", "Dragon Ember", "Bottled-Up Rage", "Pinch of Annoyance", "Raisins of Wrath",
"Gilded cheese", "Crown Jewel", "Gauntlet Potion Tier 1", "Gauntlet Potion Tier 2", "Gauntlet Potion Tier 3", "Gauntlet Potion Tier 4", "Gauntlet Potion Tier 5", "Gauntlet Potion Tier 6", "Gauntlet Potion Tier 7", "Gauntlet Potion Tier 8"
];

var loot_point = [0,0,0,0,0,0,0, 500,750,1000,750,1250,0,0,0,0,0,  0,0,0,0,0,0, 0,0,0,0,0,0,0,0,        0,0,    0,0,0,0,                0,0,0,0,0,      0,0,0,0,0,      0,0,0,  0,      0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,  0,  0,0,0,0,    0,0,0,0,0,0,0,0,0,0,    0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0];
var loot_gold = [10,50,100,200,700,700,2000, 0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0, 0,0,0,0,0,0,0,0,        0,0,    250,500,750,1000,       150,0,0,0,0,    0,0,0,0,0,      0,0,0,  0,      0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0,0,  5000,  0,0,0,0,    0,0,0,0,0,0,0,0,0,0,    0,0,0,0,0,  0,0,0,0,0,0,0,0,0,0];
*/

var loot_collect = new Array(n_loots);

var kingsrew=["points", "gold", "piece[s]* of cheddar", "piece[s]* of marble", "piece[s]* of swiss", "piece[s]* of brie","piece[s]* of super brie", "piece[s]* of radioactive blue", "piece[s]* of gouda"];

var is_travel=false;
var is_loot=false;

function NormalP(x){
  // Abramowitz & Stegun 26.2.19
  var
  d1 = 0.0498673470,
  d2 = 0.0211410061,
  d3 = 0.0032776263,
  d4 = 0.0000380036,
  d5 = 0.0000488906,
  d6 = 0.0000053830;
  var a = Math.abs(x);
  var t = 1.0 + a*(d1+a*(d2+a*(d3+a*(d4+a*(d5+a*d6)))));
  // to 16th power
  t *= t;  t *= t;  t *= t;  t *= t;
  t = 1.0 / (t+t);  // the MINUS 16th
  if (x >= 0)  t = 1 - t;
  return t;
}// CI for proportions > http://davidmlane.com/hyperstat/B31421.html
function ci_proportion(p, N){
  var z = 1.96; // 95% CI
  var tmp = z*Math.sqrt( p*(1-p)/N ) + (0.5/N);
  if (p*N < 5 || (1-p)*N < 5)
  return " <span class='magenta'><em>(data not sufficient to calculate C.I.)</em></span>";
  return " <span class='magenta'>(&#177;" + fix2dp((tmp)*100) + "% C.I.)</span>";
}

function genoutput() {
  // Disable textareas in the data form
  $('#data_form textarea').attr('disabled','disabled');

  //Assign SB and RB loot value from user input
  loot_table[4][_LOOT_GOLD]=$("#rblootvalue").val()*1;
  loot_table[7][_LOOT_GOLD]=$("#rblootvalue").val()*1;

  //Output table
  output = "<table>";
  output += "<tr><th>Time</th><th>Location</th><th>Log</th><th>Event</th><th>Mouse</th><th>Points</th><th>Gold</th><th>Loot</th><th>Bait</th><th>Result</th></tr>";

  //Calculation variables
  hunts=0; hunts_horn=0; hunt_horn_self=0; attractions=0; catches=0; total_bait_used=0; bait_stale=0; bait_steals=0;
  net_points=0; net_gold=0; gross_points=0; gross_gold=0;
  points_stolen=0; gold_stolen=0; points_loot=0; gold_loot=0;
  is_error=false;

  //Default mouse attracts and catches to zero
  for (var i=0;i<n_mice;i++){
    mouse_attractions[i] = 0;
    mouse_catches[i] = 0;
  }

  //Default loot collects to zero
  for (var i=0;i<n_loots;i++){
    loot_collect[i]=0;
  }

  //First, get the textarea value
  var journals = $("#inputtext").val();
  //Remove occurences of all day names
  journals = journals.replace(/(Monday *|Tuesday *|Wednesday *|Thursday *|Friday *|Saturday *|Sunday *)/gi, "").replace(/,/g, "");;
  //Split the journals
  var split = journals.split(/\s*(?=(?:\b\d+:\d+|\*\*\*))/);

  //Log indexes
  _timestamp = 0;
  _location = 1;
  _event = 2;
  _mouse = 3;
  _points = 4;
  _gold = 5;
  _loot = 6;
  _bait = 7;
  _result = 8;
  _log = 9;

  _hi_event = 0;
  _hi_result = 1;
  _hi_location = 2;
  _hi_mouse = 3;
  _hi_weight = 4;
  _hi_points = 5;
  _hi_gold = 6;
  _hi_bait = 7;
  _hi_time = 8;
  _hi_log = 9;

  //To store the log entries
  var logs = new Array();
  // To store this hunt_log contents for this hunt
  var hunt_inst = new Array();
  // To store the output hunt_log string
  var hunt_log = "";
  for(i=0; i<=9; i++)
  logs[i] =  new Array();
  for(i=0; i<split.length; i++){
    var is_curr_error=false;
    output += "<tr>";
    var check_stat = true;
    var str;
    is_comment=false;

    // Empty instance at the start
    for(k=0; k<=9; k++)
    hunt_inst[k] = " ";

    //Event
    /* From db.hunt_event_type (id, name)
    0  Unknown
    1  Horn
    2  Hourly Check
    3  Travel
    4  King's Reward
    5  Tournament
    6  Rank
    21  Log Summary
    22  Comment
    23  Send to friend
    24  Paypal Donation
    25  Trade SB+
    41  Crafting
    42  Trapsmith
    43  Cheese Shoppe
      */
    logs[_event][i] = "";
    
    // We'll only fill if event type is useful - 1, 2, 4 for now

    if(split[i].indexOf('***') != -1){
      logs[_event][i] += "<span class='blue'>Comment</span>";
      check_stat = false;
      is_comment=true;
    }

    else if(split[i].indexOf('I checked') != -1){
      hunts++;
      logs[_event][i] += "Trap check";
      hunt_inst[_hi_event] = 2;
    }

    else if(split[i].indexOf('I returned to check') != -1){
      hunts++;
      logs[_event][i] += "Trap check";
      hunt_inst[_hi_event] = 2;
    }

    else if(split[i].indexOf('I sounded') != -1){
      hunts++; hunts_horn++; hunt_horn_self++;
      logs[_event][i] += "Horn - self";
      hunt_inst[_hi_event] = 1;
    }

    else if(split[i].indexOf('I went on a hunt with') != -1){
      hunts++; hunts_horn++;
      logs[_event][i] += "Horn - by friend";
      hunt_inst[_hi_event] = 1;
    }

    else if(split[i].indexOf('I traveled') != -1){
      logs[_event][i] += "<span class='blue'>Travel</span>";
      check_stat = false;
      is_travel = true;
    }
    else if(split[i].indexOf('I was guided') != -1){
      logs[_event][i] += "<span class='blue'>Free Travel</span>";
      check_stat = false;
      is_travel = true;
    }
    else if(split[i].indexOf('I sent') != -1){
      logs[_event][i] += "<span class='blue'>Send to friend</span>";
      check_stat = false;
    }
    else if(split[i].indexOf('I received') != -1){
      logs[_event][i] += "<span class='blue'>Received from friend/item</span>";
      check_stat = false;
    }
    else if(split[i].indexOf('I crafted') != -1){
      logs[_event][i] += "<span class='blue'>Crafting</span>";
      check_stat = false;
    }
    else if(split[i].indexOf('I purchased') != -1){
      logs[_event][i] += "<span class='blue'>Purchase</span>";
      check_stat = false;
    }
    else if(split[i].indexOf('I sold') != -1){
      logs[_event][i] += "<span class='blue'>Sale</span>";
      check_stat = false;
    }
    else if(split[i].indexOf('Hunters\' Hammer') != -1){
      logs[_event][i] += "<span class='blue'>Hunters' Hammer</span>";
      check_stat = false;
    }
    else if(split[i].indexOf('donation') != -1){
      logs[_event][i] += "<span class='blue'>Donation</span>";
      check_stat = false;
    }
    else if(split[i].indexOf('King\'s Reward') != -1){
      logs[_event][i] += "<span class='blue'>King's Reward</span>";
      check_stat = false;
      hunt_inst[_hi_event] = 4;
    }
    else if(split[i].indexOf('I concocted') != -1){
      logs[_event][i] += "<span class='blue'>Gauntlet concoction.</span>";
      check_stat = false;
    }
    else if(split[i].indexOf('I created') != -1){
      logs[_event][i] += "<span class='blue'>Crafting.</span>";
      check_stat = false;
    }
    else if(split[i].indexOf('I claimed my order') != -1){
      logs[_event][i] += "<span class='blue'>Cartographer</span>";
      check_stat = false;
    }
    else{
      is_curr_error = true;
      is_error = true;
      check_stat = false;
    }

    logs[_timestamp][i] ="&nbsp;";
    logs[_location][i] ="&nbsp;";

    if(!is_comment){
      //Timestamp - from beinning of entry to " -"
      logs[_timestamp][i] = split[i].substring(0, split[i].indexOf("-")).trim();
      hunt_inst[_hi_time] = logs[_timestamp][i];
      //Location - from "-" until end of line
      logs[_location][i] = split[i].substring(split[i].indexOf("-")+2, split[i].indexOf("\n") ).trim();
      // Use the location string to match the entry in locations[]
      for (var l=0; l<locations_raw.length; l++) {
        if (locations_raw[l][1] == logs[_location][i]) {
          hunt_inst[_hi_location] = l;
          break;
        }
      }
    }

    //Mouse, points, gold, loot, bait, result
    logs[_mouse][i] = "&nbsp;";
    var points= "&nbsp;";
    var gold = "&nbsp;";
    var this_loot = "&nbsp;";
    var bait = "&nbsp;";
    var result = "&nbsp;";
    // Loot list contains array of [loot_id, quantity]
    var loot_list = [];

    if(check_stat){

      //Mice - if mouse name from mice[] is present - reference backwards so that the newer mice with more complicated names are checked before White, Grey, Brown etc.
      for (var j=n_mice-1; j>=0; j--){
        if (mice[j] != "Empty") {
          if (split[i].indexOf(mice[j]) != -1) {
            logs[_mouse][i] = mice[j];
            hunt_inst[_hi_mouse] = j; // Get the index
            mouse_attractions[j]++;
            if(split[i].indexOf('caught') != -1)
            mouse_catches[j]++;
            break;
          }
        }
      }

      //Points and gold
      if(split[i].indexOf('caught') != -1){

        str = String( split[i].match(/worth \d+ points/) );
        points = String(str.match(/\d+/)) * 1;

        str= String( split[i].match(/points and \d+ gold/) );
        gold = String(str.match(/\d+/)) * 1;

      }
      else if(split[i].indexOf('crippled my courage') != -1){

        str = String( split[i].match(/setting me back \d+ points/) );
        points = String(str.match(/\d+/)) * -1;

        points_stolen += points;
      }
      else if(split[i].indexOf('the fiend pillaged') != -1){

        str = String( split[i].match(/pillaged \d+ gold/) );
        gold = String(str.match(/\d+/)) * -1;

        gold_stolen += gold;
      }

      //Loot
      if(split[i].indexOf('dropped the following loot:') != -1){
        var sent_len = 'dropped the following loot:'.length;
        this_loot = split[i].substring( split[i].indexOf('dropped the following loot:') + sent_len );

        //Loot arrays
        for (var j=0;j<n_loots;j++){
          loot_regex = loot_table[j][_LOOT_REGEX];

          if (loot_regex.search("potion")>=0 || loot_regex.search("gift")>=0)
          var regexS = "([0-9]+) "+loot_regex;
          else
          var regexS = "([0-9]*) "+loot_regex;

          var regex = new RegExp(regexS);

          var tmp_loot = regex.exec(this_loot.toLowerCase());

          if (tmp_loot==null)
          continue;

          is_loot = true;

          if (tmp_loot[1]=="")
          tmp_loot = 1;
          else
          tmp_loot=tmp_loot[1]*1;

          if(isFinite(tmp_loot)) {
            loot_collect[j] += tmp_loot;
            // Add loot to the loot_list
            loot_list.push([loot_table[j][_LOOT_ID], tmp_loot]); 
          }

          //output += " +"+loot[j]+"("+tmp+") "; //For debugging

        }

      }

      //Result
/* - From DB
(1,'Caught mouse'),
(10,'Failed to catch'), (11,'FTC - Pillage Gold'), (12,'FTC - Pillage Points'), (13,'FTC - Pillage Cheese'),
(20,'Failed to attract'), (21,'FTA - Stale Cheese');
*/
      if(split[i].indexOf('caught') != -1){
        attractions++; catches++;
        result = "Attracted, caught";
        bait = -1;
        hunt_inst[_hi_result] = 1;
        str = String( split[i].match(/ \d+ oz./) );
        hunt_inst[_hi_weight] = String(str.match(/\d+/)) * 1;
      }
      else if(split[i].indexOf('ate a piece of cheese') != -1 || split[i].indexOf('had eaten a piece of cheese') != -1){
        attractions++;
        result = "Attracted, didnt catch";
        bait = -1;

        if(split[i].indexOf('crippled my courage') != -1){
          result = "Attracted, didnt catch, points stolen";
          hunt_inst[_hi_result] = 12;
        }
        else if(split[i].indexOf('pillaged') != -1){
          result = "Attracted, didnt catch, gold stolen";
          hunt_inst[_hi_result] = 11;
        }
        else if(split[i].indexOf('crafty mouse managed') != -1){
          result = "Attracted, didnt catch, cheese stolen";
          str = String( split[i].match(/steal an additional \d+ piece/) );
          bait_steals += String(str.match(/\d+/)) * 1;;
          bait = bait -  String(str.match(/\d+/)) * 1;
          hunt_inst[_hi_result] = 13;
        }
        else {
          hunt_inst[_hi_result] = 10;
        }
      }
      else if(split[i].indexOf('seemed to be stale') != -1){
        result = "Didnt attract, cheese became stale";
        bait = -1;
        bait_stale --;
        hunt_inst[_hi_result] = 21;
      }
      else if(split[i].indexOf('failed to attract a mouse.') != -1){
        result = "Didn't attract";
        bait = 0;
        hunt_inst[_hi_result] = 20;
      }

      //Convert to numbers if required, and add to variable.
      if(points != "&nbsp;"){
        points=parseInt(points);
        net_points += points;
        hunt_inst[_hi_points] = points;
      }
      if(gold != "&nbsp;"){
        gold=parseInt(gold);
        net_gold += gold;
        hunt_inst[_hi_gold] = gold;
      }

      //Calculation variables

      if(points > 0)
      gross_points += points;
      if(gold > 0)
      gross_gold += gold;

      total_bait_used += bait;
    }

    logs[_points][i] = points;
    logs[_gold][i] = gold;
    logs[_loot][i] = this_loot;
    logs[_bait][i] = bait;
    logs[_result][i] = result;

    hunt_inst[_hi_bait] = bait;

    if(is_curr_error){
      logs[_result][i] = "<span class='red'>ERROR!!!</span>";
    }

    //Logs
    if(!is_comment){
      var posn_of_locn = split[i].indexOf( logs[_location][i] ) + logs[_location][i].length;
      logs[_log][i] = split[i].substring( posn_of_locn );
    }
    else{
      logs[_log][i] = split[i].substring( split[i].indexOf( "***" ) +3 );
    }
    hunt_inst[_hi_log]=logs[_log][i];

    output += "<td>" +  logs[_timestamp][i] + "</td>";
    output += "<td>" +  logs[_location][i] + "</td>";
    output += "<td>" +  logs[_log][i] + "</td>";
    output += "<td>" +  logs[_event][i] + "</td>";
    output += "<td>" +  logs[_mouse][i] + "</td>";
    output += "<td>" +  logs[_points][i] + "</td>";
    output += "<td>" +  logs[_gold][i] + "</td>";
    output += "<td>" +  logs[_loot][i] + "</td>";
    output += "<td>" +  logs[_bait][i] + "</td>";
    output += "<td>" +  logs[_result][i] + "</td>";
    output += "</tr>";

    if (hunt_inst[_hi_event] != " ") {
      // This event is to be logged
      // All logs separated by $log$
      if (hunt_log.length>0) hunt_log += "$log$";
      for (var instctr = 0; instctr<=9; instctr++) {
        hunt_log += hunt_inst[instctr];
        // Initial 9 items separated by |
        if (instctr<9) hunt_log += "|";
      }
      for (var lootctr = 0; lootctr < loot_list.length; lootctr++) {
        // Each loot item starts with $loot$, then loot_id | quantity
        hunt_log += "$loot$" + loot_list[lootctr][0] + "|" + loot_list[lootctr][1];
      }
    }
  }

  output += "</table>";
  $('#outputtable').html(output);
  if(is_error){
    $('#outputstat').html('<span class="red">Errors detected! Please copy the error rows below and report it to us.</span>');
    return;
  }
  for (var i=0;i<n_loots;i++)  {
    //tmp = loot_collect[i]*loot_point[i];
    tmp = loot_collect[i]*loot_table[i][_LOOT_POINTS];
    points_loot += tmp;
    //point += tmp;
    //tmp = loot_collect[i]*loot_gold[i];
    tmp = loot_collect[i]*loot_table[i][_LOOT_GOLD];
    gold_loot += tmp;
    //gold += tmp;
  }

  total_bait_used = total_bait_used * -1; //Convert to positive
  bait_stale = bait_stale * -1; //Convert to positive
  var cheese_cost_pp = $('#cheese_cost').val() * 1;
  var total_cheese_cost =  cheese_cost_pp * total_bait_used;
  var total_profit = net_gold - total_cheese_cost;

  output = "";
  output += "<table width='100%' cellspacing='0' cellpadding='0'>";
  output += "<tr><td colspan='3'>";
  output += "<em class='green'>C.I. = 95% <a href='http://en.wikipedia.org/wiki/Confidence_interval'>Confidence Interval</a>. For instance, if you have a catch rate of ";
  output += "74% &#177; 5% then you are 95% confident that the catch rate falls between 69% and 79%. ";
  output += "<br />NaN = Not a Number (resulted from zero divided by zero). It is not an error.</em></td></tr>";
  if (is_error) {
    output += "<tr><td colspan='3'>";
    output += "<span class='red'>ERRORS DETECTED</span>";
    output += "<br />Please reload this page or clean your web brower's cache and try again.";
    output += "<br />If the problem persists, please copy the error rows from the table below and post it on our discussion forums</td></tr>";
    output += "</table>";
    $("#outputstat").html(output);
    return;
  }
  if(is_travel){
    output += "<tr><td colspan='3'>";
    output += "<span class='red'>WARNING: TRAVELING DETECTED</span>";
    output += "<br /><em class='red'>Statistics are not meaningful when aggregated from several different locations.</em></td></tr>";
  }
  if(hunts == 0){
    output += "<tr><td colspan='3'>";
    output += "<span class='red'>NO HUNTS DETECTED</span>";
    output += "<br /><em class='red'>The summarizer could not find any event in your journal that resemble hunts.</em></td></tr>";
    $("#outputstat").html(output);
    return;
  }

  /*===============FIRST COLUMN===============*/
  output += "<tr><td>";
  output += "<span class='blue'>Inputs</span>";
  output += "<br />Log size = " + split.length;
  output += "<br />Cheese cost(pp) = " + cheese_cost_pp;

  output += "<br /><br /><span class='blue'>Key statistics</span>";
  output += "<br /><span class='darkish'>Number of hunts = " + hunts + "</span>";
  output += "<br />&nbsp;&rarr;Trap checks = " + (hunts - hunts_horn) + "";
  output += "<br />&nbsp;&rarr;Hunters Horn = " + hunts_horn +" (" + hunt_horn_self +" by self, " + (hunts_horn - hunt_horn_self) + " by friends)";
  output += "<br /><span class='darkish'>Cheese used = " + total_bait_used + "</span>";
  output += "<br />&nbsp;&rarr;Total cheese cost = " + total_cheese_cost;
  output += "<br />&nbsp;&rarr;Cheese used per hunt = " + fix2dp(total_bait_used/hunts);
  output += "<br />&nbsp;&rarr;Cheese cost per hunt = " + fix2dp(total_cheese_cost/hunts);
  output += "<br /><span class='darkish'>Total attractions = " + attractions + "</span>";
  output += "<br />&nbsp;&rarr;Attraction rate = " + fix2dp(attractions/hunts*100) + "%" +  ci_proportion(attractions/hunts, hunts);
  output += "<br /><span class='darkish'>Total catches = " + catches + "</span>";
  output += "<br />&nbsp;&rarr;Catch rate per attraction = " + fix2dp(catches/attractions*100) + "%" +  ci_proportion(catches/attractions, attractions);
  output += "<br /><span class='darkish'>Gross points = " + gross_points + "</span>";
  output += "<br />&nbsp;&rarr;Per hunt = " + fix2dp(gross_points/hunts);
  output += "<br />&nbsp;&rarr;Per cheese = " + fix2dp(gross_points/total_bait_used);
  output += "<br /><span class='darkish'>Net points = " + net_points + "</span>";
  output += "<br />&nbsp;&rarr;Per hunt = " + fix2dp(net_points/hunts);
  output += "<br />&nbsp;&rarr;Per cheese = " + fix2dp(net_points/total_bait_used);
  output += "<br /><span class='darkish'>Gross earnings = " + gross_gold + "</span>";
  output += "<br />&nbsp;&rarr;Per hunt = " + fix2dp(gross_gold/hunts);
  output += "<br />&nbsp;&rarr;Per cheese = " + fix2dp(gross_gold/total_bait_used);
  output += "<br /><span class='darkish'>Net earnings (before cheese cost) = " + net_gold + "</span>";
  output += "<br />&nbsp;&rarr;Per hunt = " + fix2dp(net_gold/hunts);
  output += "<br />&nbsp;&rarr;Per cheese = " + fix2dp(net_gold/total_bait_used);
  output += "<br /><span class='darkish'>Net Profit (after cheese cost)= " + total_profit + "</span>";
  output += "<br />&nbsp;&rarr;Per hunt = " + fix2dp(total_profit/hunts);
  output += "<br />&nbsp;&rarr;Per cheese = " + fix2dp(total_profit/total_bait_used);

  output += "<br /><br /><span class='blue'>Point Statement</span>";
  output += "<table width='100%' cellspacing='0' cellpadding='0'>";
  output += "<tr class='green'><th>Item</th><th>Total</th><th>Per hunt</th><th>Per cheese</th><th>Per catch</th><th>%</th></tr>";
  output += "<tr><td>Gross points</td><td>"+gross_points
  + "</td><td>"+fix2dp(gross_points/hunts)
  + "</td><td>"+fix2dp(gross_points/total_bait_used)
  + "</td><td>"+fix2dp(gross_points/catches)
  + "</td><td>100%</td>";
  output += "</tr><tr><td>Less: Point steals</td><td>"+points_stolen
  + "</td><td>"+fix2dp(points_stolen/hunts)
  + "</td><td>"+fix2dp(points_stolen/total_bait_used)
  + "</td><td>"+fix2dp(points_stolen/catches)
  + "</td><td>"+fix2dp(points_stolen/gross_points*100)+"%</td>";
  output += "</tr><tr><td class='red'>You get: Net points (excluding loot)</td><td>"+net_points
  + "</td><td>"+fix2dp(net_points/hunts)
  + "</td><td>"+fix2dp(net_points/total_bait_used)
  + "</td><td>"+fix2dp(net_points/catches)
  + "</td><td>"+fix2dp(net_points/gross_points*100)+"%</td></tr>"
  output += "</tr><tr><td>Loot value - points</td><td>"+points_loot
  + "</td><td>"+fix2dp(points_loot/hunts)
  + "</td><td>"+fix2dp(points_loot/total_bait_used)
  + "</td><td>"+fix2dp(points_loot/catches)
  + "</td><td>"+fix2dp(points_loot/gross_points*100)+"%</td>";
  var points_withloot_tmp = points_loot + net_points;
  output += "</tr><tr><td class='red'>You get: Net points (including loot)</td><td>"+points_withloot_tmp
  + "</td><td>"+fix2dp(points_withloot_tmp/hunts)
  + "</td><td>"+fix2dp(points_withloot_tmp/total_bait_used)
  + "</td><td>"+fix2dp(points_withloot_tmp/catches)
  + "</td><td>"+fix2dp(points_withloot_tmp/gross_points*100)+"%</td>";
  output += "</table>";

  output += "<br /><br /><span class='blue'>Income Statement</span>";
  output += "<table width='100%' cellspacing='0' cellpadding='0'>";
  output += "<tr class='green'><th>Item</th><th>Total</th><th>Per hunt</th><th>Per cheese</th><th>Per catch</th><th>%</th></tr>";
  output += "<tr><td>Gross earnings</td><td>"+gross_gold
  + "</td><td>"+fix2dp(gross_gold/hunts)
  + "</td><td>"+fix2dp(gross_gold/total_bait_used)
  + "</td><td>"+fix2dp(gross_gold/catches)
  + "</td><td>100%</td>";
  output += "</tr><tr><td>Less: Gold steals</td><td>"+gold_stolen
  + "</td><td>"+fix2dp(gold_stolen/hunts)
  + "</td><td>"+fix2dp(gold_stolen/total_bait_used)
  + "</td><td>"+fix2dp(gold_stolen/catches)
  + "</td><td>"+fix2dp(gold_stolen/gross_gold*100)+"%";
  output += "</tr><tr><td>You get: Net earnings</td><td>"+net_gold
  + "</td><td>"+fix2dp(net_gold/hunts)
  + "</td><td>"+fix2dp(net_gold/total_bait_used)
  + "</td><td>"+fix2dp(net_gold/catches)
  + "</td><td>"+fix2dp(net_gold/gross_gold*100)+"%";
  output += "</tr><tr><td>Less: Cheese cost</td><td>"+(-total_cheese_cost)
  + "</td><td>"+fix2dp(-total_cheese_cost/hunts)
  + "</td><td>"+fix2dp(-total_cheese_cost/total_bait_used)
  + "</td><td>"+fix2dp(-total_cheese_cost/catches)
  + "</td><td>"+fix2dp(-total_cheese_cost/gross_gold*100)+"%</td></tr>";
  tmp = net_gold - total_cheese_cost;
  output += "<tr><td class='red'>You get: Net profit (excluding loot)</td><td>"+tmp
  + "</td><td>"+fix2dp(tmp/hunts)
  + "</td><td>"+fix2dp(tmp/total_bait_used)
  + "</td><td>"+fix2dp(tmp/catches)
  + "</td><td>"+fix2dp(tmp/gross_gold*100)+"%</td>";
  output += "</tr><tr><td>Loot value - gold</td><td>"+gold_loot
  + "</td><td>"+fix2dp(gold_loot/hunts)
  + "</td><td>"+fix2dp(gold_loot/total_bait_used)
  + "</td><td>"+fix2dp(gold_loot/catches)
  + "</td><td>"+fix2dp(gold_loot/gross_gold*100)+"%</td>";
  var gold_withloot_tmp = gold_loot + tmp;
  output += "</tr><tr><td class='red'>You get: Net gold (including loot)</td><td>"+gold_withloot_tmp
  + "</td><td>"+fix2dp(gold_withloot_tmp/hunts)
  + "</td><td>"+fix2dp(gold_withloot_tmp/total_bait_used)
  + "</td><td>"+fix2dp(gold_withloot_tmp/catches)
  + "</td><td>"+fix2dp(gold_withloot_tmp/gross_gold*100)+"%</td>";
  output += "</tr></table>";

  output += "<br /><br /><span class='blue'>Loot Breakdown</span>";
  if (is_loot){
    output += "<table width='100%' cellspacing='0' cellpadding='0'>";
    output += "<tr class='green'><th>Item</th><th>Total</th><th>Per hunt</th><th>Per cheese</th><th>Per catch</th></tr>";
    for (var i=0;i<n_loots;i++){
      if (loot_collect[i]>0)
      output += "<tr><td>" +loot_table[i][2]+"</td><td>"+loot_collect[i] +
      "</td><td>"+ fix2dp(loot_collect[i]/hunts) +
      "</td><td>"+ fix2dp(loot_collect[i]/total_bait_used) +
      "</td><td>"+ fix2dp(loot_collect[i]/catches);
    }
    output += "</td></tr></table>";
  }
  else
  output += "<br /><em>No loot collected.</em>";

  output += "</td>";

  /*===============// FIRST COLUMN===============*/

  /*===============BREAKING COLUMN===============*/
  output += "<td>&nbsp;</td>";
  /*===============// BREAKING COLUMN===============*/

  /*===============SECOND COLUMN===============*/
  output += "<td>";
  output += "<span class='blue'>Hunt & cheese Analysis</span>";
  output += "<table width='100%' cellspacing='0' cellpadding='0'>";
  output += "<tr class='green'><th colspan='2'>Hunt outcome</th><th colspan='2'>Cheese usage</th><th colspan='2'>Cheese per hunt</th></tr>";
  tmp = hunts-attractions;
  output += "<tr><td>Failed to attract</td><td>"+tmp +fix2dp_percent(tmp/hunts*100);
  output += "</td><td>Went stale</td><td>"+bait_stale +fix2dp_percent(bait_stale/total_bait_used*100);
  output += "</td><td>Stale rate<td>"+fix2dp(bait_stale/tmp);
  tmp = attractions-catches;
  output += "</td></tr><tr><td rowspan='2'>Did attract but<br />failed to catch</td><td rowspan='2'>"+tmp +fix2dp_percent(tmp/hunts*100);
  output += "</td><td>Bait pieces stolen</td><td>"+ tmp +fix2dp_percent(tmp/total_bait_used*100);
  var rm_temp = fix2dp(1+(bait_steals/tmp));
  if( isNaN(rm_temp)) rm_temp="0";
  output += "</td><td rowspan='2'>Steal rate</td><td rowspan='2'>"+ rm_temp;
  output += "</td></tr><tr><td>Extra pieces stolen</td><td>"+bait_steals +fix2dp_percent(bait_steals/total_bait_used*100);
  output += "</td></tr><tr><td>Did attract and did catch</td><td>"+catches +fix2dp_percent(catches/hunts*100);
  output += "<td>Fruitful hunts</td><td>"+catches +fix2dp_percent(catches/total_bait_used*100);
  output += "</td><td colspan='2'><em>always equal to 1</em></tr></tr>";
  output += "<tr class='red'><th>Number of hunts</th><th>"+hunts +" (100%)</th><th>Cheese used</th><th>"+total_bait_used +" (100%)</th>";
  output += "<th>Overall</th><th>"+fix2dp(total_bait_used/hunts);
  output += "</th></tr></table>";

  output += "<br /><span class='blue'>Mouse Breakdowns</span>";
  output += "<table width='100%' cellspacing='0' cellpadding='0'>";
  output += "<tr class='green'><th>Mouse</th><th>Catch</th><th>%</th><th>Attract</th><th>%</th><th>Catch rate (%)</th><th>Catch per hunts</th><th>Attract per hunts</th></tr>";
  for (var i=0;i<n_mice;i++){
    if (mouse_attractions[i]>0)  {
      var catch_percent=fix2dp(mouse_catches[i]/hunts)*100;
      catch_percent+="";
      if(catch_percent.length>4)
      catch_percent=catch_percent.substring(0,4);
      var att_percent=fix2dp(mouse_attractions[i]/hunts)*100;
      att_percent+="";
      if(att_percent.length>4)
      att_percent=att_percent.substring(0,4);
      output += "<tr><td>"+mice[i]+"</td><td>"+mouse_catches[i]+ "</td><td>"+
      fix2dp(mouse_catches[i]/catches*100) +
      "</td><td>" +mouse_attractions[i] + "</td><td>"+
      fix2dp(mouse_attractions[i]/attractions*100)+
      "</td><td><span class='blue'>" +
      fix2dp(mouse_catches[i]/mouse_attractions[i]*100)+"</span>"+
      "<td>" +fix2dp(mouse_catches[i]/hunts)+ ' ('+ catch_percent +'% )'+
      "</td><td>" +fix2dp(mouse_attractions[i]/hunts)+ ' ('+ att_percent +'% )';
    }
  }
  output += "</td></tr><tr class='red'><th>Total</th><th>"+catches +"</th><th>100</th><th>"+attractions+"</th><th>100</th><th>"+
  fix2dp(catches/attractions*100)+"</th><th>"+fix2dp(catches/hunts)+"</th><th>"+fix2dp(attractions/hunts)+"</th></tr></table>";

  output += "<span class='blue'>King's reward summary</span>";
  output += "<br />Coming soon...";

  /*===============// SECOND COLUMN===============*/

  output +="</table>";

  $('#outputstat').html(output);
  //Disabled journals
  $('#h_journal').html(journals);
  //Disabled output table
  $('#h_table').html(output);
  //Disabled hunts
  $('#h_hunts').html(hunts);
  //Disabled hunt list
  $('#h_hunt_log').html(hunt_log);

  /*
    var temp_str = "Total hunts= "+ hunts;
  temp_str += "<br />--Hunters horn= "+hunts_horn+" ("+hunt_horn_self+" by self, "+(hunts_horn - hunt_horn_self)+" by friend)";
  temp_str += "<br />--trap checks= "+(hunts - hunts_horn);
  temp_str += "<br />Attractions= "+attractions;
  temp_str += "<br />Catches= "+catches;
  temp_str += "<br />Total bait used="+total_bait_used+" ("+bait_stale+" pieces stale)";
  temp_str += "<br />Gross Points= "+gross_points;
  temp_str += "<br />Points stolen= "+points_stolen;
  temp_str += "<br />Net points= "+net_points;
  temp_str += "<br />Gross gold= "+gross_gold;
  temp_str += "<br />Gold stolen= "+gold_stolen;
  temp_str += "<br />Net gold= "+net_gold;
    $('#outputstat').prepend(temp_str +"<br /><br /><br />");
    */

}

function fix2dp_percent(x){
  return " ("+fixDP(x, 2)+"%)";
}function fix2dp(x){
  return fixDP(x, 2);
}