/* $Id: Cookie.js 84386 2009-10-01 11:47:48Z k.reimer $
 * Copyright (C) 2006 IP Labs GmbH <http://www.iplabs.de/>
 * All rights reserved.
 */
 
 /**
 * @fileoverview
 *
 * Contains the Cookie class.
 *
 * @author Andreas Kornetka <a.kornetka@iplabs.de>
 * @version $Revision: 84386 $
 */

/**
 * Constructor for Cookie Object.
 *
 * @class <p>This classprovides cookie handling.</p>
 *
 * @constructor
 * @param {String} name
 *            The cookie name (id) to be reffered to. Inevitable parameter!
 * @param {Integer} years
 *			  Set expiration date in years. If zero or undefined, the cookie will be stored temporary. Optional parameter.
 */
function Cookie(name, years) {
	this.__name       = name + '=';
	this.__persistant = false;
	this.__expires    = new Date();
	this.setExpire(years);
}

/**
 * Set the expiration date.
 * 
 * @param {Integer} years
 *			  Set expiration date in years. If zero or undefined, the cookie will be stored temporary. 
 */
Cookie.prototype.setExpire = function(years) {
	var currentDate = new Date();
	if(typeof(years) != 'undefined') {
		this.__persistant = true;
		this.__expires    = currentDate.setFullYear(currentDate.getFullYear() + years);
	}
}

/**
 * Get the cookie data.
 * 
 * @return {String}
 *            Returns the cookie data as a string.  
 */
Cookie.prototype.get = function() {
	var start, end = -1, data = new String();
    start = document.cookie.indexOf(this.__name);
    if(start != -1) {
        start += this.__name.length;
        end = document.cookie.indexOf(';', start);
        if(end == -1) {end = document.cookie.length;}
        data = document.cookie.substring(start, end);
    }
    return unescape(data);
}

/**
 * Set the cookie content.
 * 
 * @param {String} data
 *			  Write the data in the cookie. Inevitable parameter!
 * @return {Boolean} 
 *            True if cookie was written, else false. 
 */
Cookie.prototype.set = function(data) {
    try {document.cookie = this.__name + data + ';' + (this.__persistent ? ' expires=' + this.__expires.toGMTString() : '');}
    catch(e) {return false;}
    return true;
}

/**
 * Add data to cookie content.
 * 
 * @param {String} data
 *			  Add data to the cookie. Inevitable parameter!
 * @return {Boolean} 
 *            True if additional cookie data was written or already existent, else false.   
 */
 Cookie.prototype.add = function(data) {
 	if(this.get().indexOf(data) < 0) {return this.set(this.get() + data);} 
 	else {return true;}
 }
 
 /**
  *  Singleton class for cookie checking.
  */
 var CookieChecker = new function()
 {
	 /**
	  * Checks if cookies are currently enabled.
	  * @return {Boolean} 
	  * 			True if cookies are enabled, else false.
	  */
	 this.isCookieEnabled = function()
	 {
			var cookie = new Cookie("JSESSIONID");
		 	var data = cookie.get();
		 	if(data.length == 0) 
		 	{	
		 		cookie.set("0");
		 		data = cookie.get();
		 		if(data.length == 0)
		 			return false;
		 	}
		 	return true;	
	 } 
 }
