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

  Cookie

  Copyright (c) 2004 - 2011 Christian Rocha. All Rights Reserved.

  Author: Roshambo <ro@roshambo.la>
  Created: 09 August 2004 01:19:04 PM PST
  In: Los Angeles, United States

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

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

function Cookie(name) {
	
	this.name = name || 'cookie';
	
	/**
	 * Creates a cookie.
	 */
	this.bake = function(value, expires, path) {
		
		// Cookie strings look like this:
		// CookieName=ChocolateChip; expires=Wed, 31 Dec 2003 00:00:00 UTC; path=/; domain=polychrome.com
		
		expires = expires || 1000*60*60*24*365; // 1 year lifetime by default
		path = path || '/';
		var date = new Date();
		date.setTime(date.getTime() + expires);
		document.cookie = this.name + '=' + value + '; expires=' + date.toGMTString() + '; path=' + path;
		
		return this;
	}
	
	/**
	 * Deletes a cookie.
	 */
	this.eat = function() {
		return this.bake('', -1000*60*60*24, '/');
	}
	
	/**
	 * Reads a cookie.
	 * You can think of it as getting a cookie out of the jar.
	 */
	this.get = function() {
		var name = this.name + '=';
		var cookie;
		var cookies = document.cookie.split(';');
		
		for(var i = 0; i < cookies.length; i++) {
			cookie = cookies[i];
			
			while(cookie.charAt(0) == ' ') {
				cookie = cookie.substring(1, cookie.length);
			}
			
			if(cookie.indexOf(name) == 0) {
				return cookie.substring(name.length, cookie.length);
			}
		}
		
		return null;
	}
	
	/**
	 * Checks whether or not a cookie exists. You can think of it as peeking
	 * info the cookie jar.
	 */
	this.exists = function() {
		if(document.cookie.indexOf(this.name + '=') != -1) return true;
		return false;
	}
	
	/**
	 * Aliases
	 */
	this.destroy = this.erase = this.eat;
	this.save = this.bake;
}

