/***********************************  Cakeless Cookie  ***************************************	

	Based on original source written by Jason McCreary
			http://jason.pureconcepts.net/articles/javascript_cookie_object
			
	Revised for the Cakeless framework by Jarvis Badgley (cakeless@chipersoft.com)
	
*********************************************************************************************/

var Cookie = {
	data: {},
	options: {name: 'frontporch', expires: 365, domain: "", path: "/", secure: false},
	initOK: false,

	init: function(options, data) {
		Cookie.options = Object.extend(Cookie.options, options || {});

		var payload = Cookie._retrieve();
		
		if(payload) Cookie.data = payload.evalJSON();
		else Cookie.data = data || {};
		
		Cookie._store();
	},
	
	
	getData: function(key) {
		if (!Cookie.initOK) Cookie.init();
		return Cookie.data[key];
	},
	setData: function(key, value) {
		if (!Cookie.initOK) Cookie.init();
		Cookie.data[key] = value;
		Cookie._store();
	},
	removeData: function(key) {
		if (!Cookie.initOK) Cookie.init();
		delete Cookie.data[key];
		Cookie._store();
	},
	erase: function() {
		document.cookie = Cookie.options.name + '=' + Cookie.getOptions() + ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	},
	getOptions: function() {
		return (Cookie.options.path ? ';path=' + Cookie.options.path : '') + (Cookie.options.domain ? ';domain=' + Cookie.options.domain : '') + (Cookie.options.secure ? ';secure' : '');		
	},
	
	_retrieve: function() {
		var start = document.cookie.indexOf(Cookie.options.name + "=");

		if(start == -1) {
			return null;
		}
		if(Cookie.options.name != document.cookie.substr(start, Cookie.options.name.length)) {
			return null;
		}

		var len = start + Cookie.options.name.length + 1;	
		var end = document.cookie.indexOf(';', len);

		if(end == -1) {
			end = document.cookie.length;
		} 
		return unescape(document.cookie.substring(len, end));
	},
	_store: function() {
		var expires = '';

		if (Cookie.options.expires) {
			var today = new Date();
			expires = Cookie.options.expires * 86400000;
			expires = ';expires=' + new Date(today.getTime() + expires);
		}

		document.cookie = Cookie.options.name + '=' + escape(Object.toJSON(Cookie.data)) + Cookie.getOptions() + expires;
	}
	
};
