/*
 * Copyright 2006 OST-SYSTEMS. All rights reserved.
 */

function GlobalStorage() {
  this.global = null;
  if (window.globalStorage) {
    /*
    if (window.netscape) {
      netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    }
    */
    try {
      this.global = globalStorage[location.hostname];
    }
    catch (e) {
      //Fall back to KeyStorage
    }
  }
  this.reload();
}

GlobalStorage.prototype = new KeyStorage();

GlobalStorage.prototype.saveAll = function() {
  var result = this.saveArray(this.getStorage(), 2);
  if (this.global) {
    this.global.widgetopStorage = result;
  }  
}

GlobalStorage.prototype.saveArray = function(array, level) {
  var result = "["
  for (var key in array) {
    result += "\"" + key + "\",";
    if (level > 0) {
      result += this.saveArray(array[key], level - 1);
    }
    else {
      if (array[key] != null) {
        result += "\"" + array[key] + "\"";
      }
      else {
        result += "null";
      }  
    }
    result += ",";
  }
  result += "null]";
  return result;
}

GlobalStorage.prototype.reload = function() {
  if (this.global) {
    var value = this.global.widgetopStorage;
    if (value == null) {
      value = "new Array()";
    }
    try {
      var array = eval("" + value);
      this.setStorage(this.loadArray(array, 2));
    }
    catch (e) {
      addError("Reloading from GlobalStorage failed: " + e);
    }  
  }
  else {
    this.setStorage(new Array());    
  }
}

GlobalStorage.prototype.loadArray = function(array, level) {
  var result = new Array();
  for (var i = 0; i < array.length - 1; i += 2) {
    var key = array[i];
    if (level > 0) {
      result[key] = this.loadArray(array[i + 1], level - 1);
    }
    else {
      result[key] = array[i + 1];
    }  
  }
  return result;  
}
