/**
 * Extends the WWE object to provide cookie handling 
 * capabilities.
 * 
 * @author kgordon<kirk7880[at]gmail.com>
 * @copyright 2009 World Wrestling Entertainment. All Rights Reserved.
 * @package cookies
 */

var WWECookies = Class.create({
	name: null,
	path: null,
	domain: null,
	time: null, 
	secure: null,
	cookie: null,
	document: null,
	constants: null,
	
	initialize: function (document, name, path, domain, time, secure) {
		var defaults = this.defaultValues();
		var date = new Date();
		date.setDate(date.getDate() + (!isNaN(time) ? time : defaults._TIME_));
		this.name = name;
		this.path = '; path=' + escape((typeof (path) != 'undefined') ? path : defaults._PATH_);
		this.domain = escape((typeof(domain) != 'undefined') ? domain : defaults._DOMAIN_);
		this.time = (isNaN(time)) ? '' : ('; expires=' + date.toGMTString());
		this.secure = ';' + escape((typeof (secure) != 'undefined') ? secure : defaults._SECURE_) ;
		this.document = (typeof (document) != 'undefined') ? document : defaults._DOCUMENT_;
		this.cookie = defaults._COOKIE_;
		if (!this.load()) {this.store();}
		return this.cookie;
	},
	
	defaultValues: function() {
		return {
			_NAME_:'',
			_PATH_:'/',
			_DOMAIN_:'.wwe.com',
			_TIME_:1,
			_SECURE_:false,
			_COOKIE_:{},
			_DOCUMENT_:document
		}
	},
	
	store: function () {
		var temp = Object.toJSON(this.cookie);
		this.document.cookie = this.name + '=' + escape(temp) + this.time + ((this.domain != 'localhost') ? ('; domain=' + this.domain) : '') + this.path + this.secure;
	},
	
	load: function () {
		var tmp = this.get();
		if (!tmp) { return false; }
		try {
			this.cookie = (unescape(tmp)).evalJSON(true);
		} catch (e) { return false; }
	},
	
	get: function() {
		if (this.document.cookie.length <= 0) { return false; }
		var cookies = (this.document.cookie.substring(this.document.cookie.indexOf(this.name+'=')));
		var start = cookies.indexOf('=')+1;
		var end = cookies.indexOf(';');
		start = (start != -1) ? start : 0;
		end = (end != -1) ? end : cookies.length;
		return cookies.substring(start, end);
	}
});

