/* Most of this code was taken from http://www.quirksmode.org/js/cookies.html
 * I just wrapped it in a class, and added some caching */

function Cookie()
{
  this.cookie_array = null;

  this.write = function(name, value, days)
  {
    var expires = '';
    if (days)
    {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      var expires = '; expires=' + date.toGMTString();
    }
    
    document.cookie = name + '=' + value + expires + '; path=/';

    // invalidate the cookie array cache;
    this.cookie_array = null;
  }

  this.read = function(name)
  {
    var nameEQ = name + '=';

    if (this.cookie_array == null)
    {
      this.cookie_array = document.cookie.split(';');
    }

    for (var i = 0; i < this.cookie_array.length; ++i)
    {
      var c = this.cookie_array[i];
      while (c.charAt(0) == ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }

    return null;
  }

  this.erase = function(name)
  {
    this.write(name, '', -1);
  }
}

Cookie.sharedCookie = function() {
	if (!this.__sharedCookie) {
		this.__sharedCookie = new Cookie();
	}
	return this.__sharedCookie;
}

Cookie.read = function() {
	return this.sharedCookie().read.apply(
		this.sharedCookie,
		arguments);
}

Cookie.write = function() {
	return this.sharedCookie().write.apply(
		this.sharedCookie,
		arguments);
}

Cookie.erase = function() {
	return this.sharedCookie().erase.apply(
		this.sharedCookie,
		arguments);
}

