/*:._.:*:._.:*:._.:*:._.:*:._.:*:._.

Basic Cookie Object

(c)2004 Polychrome Studio, Inc.
http://www.polychrome.com/
- - - - - - - - - - - - - - - -
Date:     2004/08/09 13:19:04
Author:   Christian Rocha
File:     cookie.js
- - - - - - - - - - - - - - - -

Todo:
- Add functionality for the domain name in bake() (domain='...')

*:._.:*:._.:*:._.:*:._.:*:._.:*:._.:*/

/**
 * Constructor
 *
 * Returns: nothing
 * Parameters:
 *   optional string cookie name (default: 'cookie')
 *
*/
function Cookie(name) {
	
	this.name = name || 'cookie';
	
};

Cookie.prototype = {

	/**
	 * Create cookie
	 * 
	 * Returns: nothing
	 * Parameters:
	 *   string cookie's value
	 *   string cookie's lifetime (milliseconds)
	 *   string cookie's path
	*/
	bake : function(value, expires, path)
	{

		// Cookie strings look like:
		// CookieName=ChocolateChip; expires=Wed, 31 Dec 2003 00:00:00 UTC; path=/; domain=polychrome.com

		if(!expires) expires = 1000*60*60*24*365; //1 year lifetime by default
		if(!path) path = '/'; //domain's root path by default
		var myDate = new Date();
		myDate.setTime(myDate.getTime()+expires);
		document.cookie = this.name+'='+value+'; expires='+myDate.toGMTString()+'; path='+path;
	},

	bake_session : function(value)
	{
		document.cookie = this.name+'='+value+'; path=/';
	},

	bake_session_domain : function(value, domain)
	{
		document.cookie = this.name+'='+value+'; path=/; domain=' + domain;
	},

	/**
	 * Deletes a cookie
	 * 
	 * Returns: nothing
	*/
	eat : function()
	{
		//document.cookie = this.name+'=deleted; expires=Jan 01 1970 00:00:00 UTC; path=/'; //not ie-safe!
		document.cookie = this.name+'=; expires=Jan 01 1970 00:00:00 UTC; path=/';
	},

	/**
	 * Reads a cookie
	 * You can think of it as getting a cookie out of the jar.
	 * 
	 * Returns: nothing
	*/
	get : function()
	{
		var nameEQ = this.name + '=';
		var cookie = document.cookie;
		var cookies = cookie.split(';');
		for(var i=0; i<cookies.length; i++) {
			var cookie = cookies[i];
			while(cookie.charAt(0) == ' ')
				cookie = cookie.substring(1, cookie.length);
			if(cookie.indexOf(nameEQ) == 0)
				return cookie.substring(nameEQ.length, cookie.length);
		}
		return null;
	},

	/**
	 * Checks whether or not a cookie exists.
	 * You can think of it as peeking into the cookie jar.
	 * 
	 * Returns: boolean
	*/
	look : function()
	{
		var cookie = document.cookie;
		if(cookie.indexOf(this.name + '=') != -1) return true;
		return false;
	}	

};
