/**
 * @fileOverview This javascript is a collection of tools to read and manipulate cookies.
 * 
 * @author Lorenzo Cavina (l.cavina@tecla.it)
 */
CookieTools = {	
		
	logger:new Logging("CookieTools"),
	
	getCookie:function(name) {
	    var sPos = document.cookie.indexOf(name + "=");
	    var len = sPos + name.length + 1;
	    if((!sPos) && (name != document.cookie.substring(0, name.length))){
	        return null;
	    }
	    if(sPos == -1){
	        return null;
	    }
	    var ePos = document.cookie.indexOf(';', len);
	    if(ePos == -1) ePos = document.cookie.length;
	    return unescape(document.cookie.substring(len, ePos));
	},
	
	/**
	 * Read the value of a cookie by name.
	 * 
	 * @param name
	 * @return The value of the cookie, null otherwise.
	 */
	getCookieValue:function(name) {
		
		if (name == "" || name == null) 
			return null; 
		
		var cookieList = this.getAllCookies();
		
		if (cookieList == null) 
			return null;

		return cookieList[name];
	},
	
	/**
	 * Read all cookies.
	 * 
	 * @return
	 */
	getAllCookies:function() {
		var cookies = { };

	    if (document.cookie && document.cookie != '') {
	        var split = document.cookie.split(';');
	        for (var i = 0; i < split.length; i++) {
	            var name_value = split[i].split("=");
	            name_value[0] = name_value[0].replace(/^ /, '');
	            cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
	        }
	    }

	    return cookies;

	},

	/**
	 * Create a new cookie.
	 * 
	 * @param name
	 * @param value
	 * @param days
	 * @return
	 */
	createCookie:function(name, value, expires, path, domain, secure) {
		
		this.logger.log("createCookie", "Now creating cookie " + name + " setting it to " + value + " for " + expires + " days");
		
		// set time, it's in milliseconds
		var today = new Date();
		today.setTime(today.getTime());

		/*
		if the expires variable is set, make the correct
		expires time, the current script below will set
		it for x number of days, to make it for hours,
		delete * 24, for minutes, delete * 60 * 24
		*/
		if (expires)
			expires = expires * 1000 * 60 * 60 * 24;
		
		var expires_date = new Date( today.getTime() + (expires) );

		document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
		( ( path ) ? ";path=" + path : "" ) +
		( ( secure ) ? ";secure" : "" );
	},
	
	deleteCookie:function( name, path, domain ) {
		if (this.getCookie(name)) 
			document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	} 
}
