/**	@file
 *	@brief CookieManager クラスの定義
 *
 *	このファイルで CookieManager クラスを定義しています。
 *	このファイルは単独で使用できます。
 *
 *	@author bgvur
 *	@date   06/09/13
 */

/**
 *	CookieManager のコンストラクタです。
 *
 *	CookieManager の使い方 :
 *
 *	function loadCookie()
 *	{
 *		var cookieManager = new CookieManager();
 *		cookieManager.loadCookie();
 *		var value0 = cookieManager.getValue("value0");
 *		var value1 = cookieManager.getValue("value1");
 *		var value2 = cookieManager.getValue("value2");
 *	}
 *
 *	function saveCookie()
 *	{
 *		var cookieManager = new CookieManager();
 *		cookieManager.setValue("value0", value0);
 *		cookieManager.setValue("value1", value1);
 *		cookieManager.setValue("value2", value2);
 *		cookieManager.saveCookie(-1);
 *	}
 */
function CookieManager()
{
	/**
	 *	値のリストです。
	 */
	this.valueList = new Array();

	/**
	 *	値を取得します。
	 */
	this.getValue = function(name)
	{
		return this.valueList[name];
	}

	/**
	 *	値を設定します。
	 */
	this.setValue = function(name, value)
	{
		this.valueList[name] = value;
	}

	/**
	 *	Cookie から値を読み込みます。
	 */
	this.loadCookie = function()
	{
		var cookie = unescape(document.cookie);
		var length = cookie.length;

		var array = cookie.split(';');

		for (var i in array)
		{
			var array2 = array[i].split('=');

			if (array2.length == 2)
			{
				var name = this.trim(array2[0]);
				var value = this.trim(array2[1]);

				this.valueList[name] = value;
			}
		}
	}

	/**
	 *	Cookie に値を保存します。
	 *	expires に -1 を指定すると、有効期限を 2030 年に設定します。
	 */
	this.saveCookie = function(expires, path)
	{
		if (expires == -1)
			expires = "Tue, 1-Jan-2030 00:00:00 GMT";

		for (var i in this.valueList)
			this.saveValue(i, this.valueList[i], expires, path);
	}

	/**
	 *	補助関数です。
	 *	指定された文字列の先頭と末尾の空白を取り除いた新たな文字列を返します。
	 */
	this.trim = function(string)
	{
		return string.replace(/^\s+|\s+$/g, "");
	}

	/**
	 *	補助関数です。
	 *	指定された値を Cookie に保存します。
	 */
	this.saveValue = function(name, value, expires, path)
	{
		var cookie = name + '=' + escape(value) +';';

		if (expires != undefined)
			cookie += 'expires=' + expires + ';';

		if (path != undefined)
			cookie += 'path=' + path + ';';

		document.cookie = cookie;
	}
}
