/**
 * This is a static class.
 * i.e.: CookieUtils.getCookie('username');
 * Singleton-style implementation: CookieUtils = new CookieUtils();
 */

var CookieUtils = function(){
	var that = this;
	
	//Public Members
	//Get a cookie value
	this.getCookie = function(name) {
		var arg = name + '=';
		var alen = arg.length;
		var clen = document.cookie.length;
		var i = 0;
		while (i < clen) {
		  	var j = i + alen;
		  	if (document.cookie.substring(i, j) == arg) {
		    		return getCookieVal(j);	
			}
		  	i = document.cookie.indexOf(' ', i) + 1;
		  	if (i === 0) {
				break;	
			}
	 	}
		return null;
	}
	//Sets a cookie value
	this.setCookie = function(name, value) {
		var argv = arguments;
		var argc = arguments.length;
		var expires = (argc > 2) ? argv[2] : null;
		var path = (argc > 3) ? argv[3] : null;
		var domain = (argc > 4) ? argv[4] : null;
		var secure = (argc > 5) ? argv[5] : false;
		//var secure = true;  //make security always true
		var cookie_string = name + '=' + escape(value) +
			((expires === null) ? '' : ('; expires=' + expires.toGMTString())) +
			((path === null) ? '' : ('; path=' + path)) +
			((domain === null) ? '' : ('; domain=' + domain)) +
		  	((secure === true) ? '; secure' : '');
		document.cookie = cookie_string;
	}
	//Deletes a cookie value
	this.deleteCookie = function(name,path) {
		var exp = new Date();
		var cval = that.getCookie(name);
		if( !path ) {
			path = '';
		}
		document.cookie = name + '=' + cval + ((path === null) ? '' : ('; path=' + path)) + '; expires=' + exp.toGMTString();
	}
	
	//Private Members
	//Get cookie helper method
	function getCookieVal(offset) {
		var endstr = document.cookie.indexOf (";", offset);
		if (endstr == -1) {
	  		endstr = document.cookie.length;
		}
		return unescape(document.cookie.substring(offset, endstr));
	}
}
CookieUtils = new CookieUtils();
