/*
 * Client-side JavaScript API for Cookie
 */

/*
 * Bake a cookie.
 *   [Input]  (String) name    : cookie name
 *            (String) sValue  : cookie value
 *              (Date) dExpires: the term of validity(option)
 *            (String) sDomain : cookie's domain(option)
 *            (String) sPath   : cookie's path(option)
 *           (boolean) bSecure : cookie security flag(option)
 *  [Output] nothing
 *  [detail] set a cookie.
 *           cookie scope is sDomain(default is current site).
 */
function setCookie(sName, sValue, dExpires, sDomain, sPath, bSecure) {
	var sStr = "";

	/* cock */
	sStr += sName;
	sStr += "=";
	sStr += escape(sValue);
	if(dExpires != null){ sStr += "; expires=" + dExpires.toGMTString(); }
	if(sDomain != null){ sStr += "; domain=" + domain; }
	if(sPath != null){ sStr += "; path=" + sPath; }
	if(bSecure == true){ sStr += "; secure"; }

	/* bake */
	document.cookie = sStr;
}

/*
 * Eat a cookie.
 *   [Input] (String) name: cookie name
 *  [Output] cookie named "name"
 *  [detail] get a cookie.
 *           if name is undefined, return null.
 */
function getCookie(sName) {
	var nLen = ("" + sName).length + 2;
	var sCookie = " " + document.cookie;
	var nStart = sCookie.indexOf(" " + sName + "=");
	var nEnd = sCookie.indexOf(";", nStart + nLen);

	/* name is nothing */
	if(nStart == -1){ return null; }

	/* search end point */
	if(nEnd == -1){ nEnd = sCookie.length; }

	/* eat and return */
	return unescape(sCookie.substring(nStart + nLen, nEnd));
}

/*
 * abandon a cookie.
 *   [Input] (String) name: cookie name
 *  [Output] nothing
 *  [detail] remove a cookie.
 */
function removeCookie(sName) {
	var dExpires = new Date();
	var sValue = getCookie(sName);

	// HTTP protocol judgment!!
	var bSecure = false;
	if (window.location.protocol.indexOf( "https") != -1){
		bSecure = true;
	}

	/* set expire to past */
	if(sValue != null){ setCookie(sName, sValue, dExpires,null,null,bSecure); }
}

/* End of File */
