window.historyStorage = {
  storageHash: new Object(),
  hashLoaded: false, 
  storageField: null,
  put: function(key, value) {
   this.assertValidKey(key);
   if (this.hasKey(key)) {
     this.remove(key);
   }
   this.storageHash[key] = value;
   this.saveHashTable(); 
  },
  get: function(key) {
    this.assertValidKey(key);
    this.loadHashTable();
    var value = this.storageHash[key];
    if (value == undefined)
      return null;
    else
      return value; 
  },
  remove: function(key) {
    this.assertValidKey(key);
    this.loadHashTable();
    delete this.storageHash[key];
    this.saveHashTable();
  },
  reset: function() {
    this.storageField.value = "";
    this.storageHash = new Object();
  },
  hasKey: function(key) {
    this.assertValidKey(key);
    this.loadHashTable();
    if (typeof this.storageHash[key] == "undefined")
      return false;
    else
      return true;
  },
  isValidKey: function(key) {
    return (typeof key == "string");
  },
  init: function() {
    this.storageField = document.getElementById("historyStorageField");
  },
  assertValidKey: function(key) {
    if (this.isValidKey(key) == false)
      throw "Please provide a valid key for window.historyStorage, key = " + key;
  },
  loadHashTable: function() {
    if (this.hashLoaded == false) {
      var serializedHashTable = this.storageField.value;
      if (serializedHashTable != "" && serializedHashTable != null) {
        //this.storageHash = new Object();
        var arr = serializedHashTable.split('|');
        for (i = 0; i < arr.length; i++) {
          var item = arr[i].split('%');
          this.storageHash[item[0]] = item[1];
        }
      }
      this.hashLoaded = true;
    }
  },
  saveHashTable: function() {
    this.loadHashTable();
    var serializedHashTable = '';
    var arr = this.storageHash;
    for (i in arr)
      serializedHashTable += (serializedHashTable == '' ? '' : '|') + i + '%' + arr[i];
    this.storageField.value = serializedHashTable;
  }
};

var _firstLoad = false;

function initPageHistory() {
  historyStorage.init();
  if (!historyStorage.hasKey('_pageLoaded')) {
    historyStorage.put('_pageLoaded', true);
    _firstLoad = true;
  }
  else
    _firstLoad = false;
}

function isFirstLoad() {
  return _firstLoad;
}