/************************************************************
 * AUTHOR: Royston Tong
 ************************************************************
 * This object is used to create a HashMap. It can also
 * create a HashMap from delimited string like 
 * document.cookie and window.location.search.
 ************************************************************/

function HashMap(str, separator, keySeparator) {
  // PRIVATE VARIABLES
  separator = separator || ',';
  keySeparator = keySeparator || '=';
  var keys = new Array();
  var values = new Array();

  // CONSTRUCTOR
  if (str != null && str != "") {
    var aryA = str.split(separator);
    for (var i = 0; i < aryA.length; i++) {
      var aryB = aryA[i].split(keySeparator);
      if (aryB[0] != '') {
        keys.push(trim(aryB[0]));
        values.push(aryB[1]);
      }
    }
  }

  // PUBLIC VARIABLES
  this.encodeValue = false;

  // PUBLIC FUNCTIONS
  this.size = function() {
    return keys.length;
  }
  this.containsKey = function(key) {
    var i = getIndex(key, keys);
    if (i < 0) return false;
    return true;
  }
  this.containValue = function(value) {
    var i = getIndex(value, values);
    if (i < 0) return false;
    return true;
  }
  this.set = function(key, value) {
    var i = getIndex(key, keys);
    if (i < 0) {
      keys.push(key);
      values.push(value);
    } else {
      values[i] = value;
    }
    return true;
  }
  this.get = function(key) {
    var i = getIndex(key, keys);
    if (i < 0) return null;
    return values[i];
  }
  this.remove = function(key) {
    var i = getIndex(key, keys);
    if (i < 0) return false;
    keys.splice(i, 1);
    values.splice(i, 1);    
    return true;
  }
  this.getKeys = function() {
    return keys;
  }
  this.getValues = function() {
    return values;
  }
  this.toString = function() {
    if (keys.length == 0) return '';
    var str = '';
    for (var i = 0; i < keys.length; i++) {
      str += keys[i] + keySeparator;
      str += (this.encodeValue) ? escape(values[i]) : values[i];
      if (i+1 < keys.length) str += separator;
    }
    return str;
  }
  // PRIVATE FUNCTIONS
  function getIndex(str, ary) {
    for (var i = 0; i < ary.length; i++) {
      if (ary[i] == str) return i;
    }
    return -1;
  }
  function trim(line) {
    while (line.length > 0 && line.substr(line.length-1, 1) == " ") {
      line = line.substr(0, line.length-1);  
    }
    while (line.length > 0 && line.substr(0, 1) == " ") {
      line = line.substr(1);
    }
    return line;
  }
}