/*  
 *  Members data class
 * 以下のライブラリに依存します。
 * xlib.js, json.js
 *--------------------------------------------------------------------------*/

// Member data.
var Member = function() {
	this.initialize();
};
Member.prototype = {
	data: null,
	logout: null,
	initialize: function() {
		var c = xGetCookie('member');
		if (!c) {
			this.data = new Object();
			this.data.category = new Array();
		} else {
			try {
				this.data = c.parseJSON();
			} catch (e) {
				this.data = new Object();
				this.data.category = new Array();
			}
		}
	},
	onLoad: function() {
		this.logout = xGetElementById('logout');
		if (this.logout != null) {
			var opt = {
			  method: 'get'
			, onSuccess: this.setLogin.bind(this)
			};
			new Ajax.Request('/jp/members/check_login.cgi', opt);
		}
	},
	saveData: function() {
		var json = this.toJSON();
		xSetCookieEx('member', json, 365, '/');
	},
	getCategoryList: function() {
		return this.data.category;
	},
	setCategoryList: function(list) {
		this.data.category = list;
		this.saveData();
	},
	toJSON: function() {
		if (!this.data) this.data = new Object();
		if (!this.data.category) this.data.category = new Array();
		var s = '{"category":[' + this.data.category.join(',') + ']';
		if (this.data.foot_url) {
			s += ',"foot_url":"' + this.data.foot_url + '"';
		}
		if (this.data.foot_title) {
			s += ',"foot_title":"' + this.data.foot_title + '"';
		}
		s += '}';
		return s;
	},
	setLogin: function(req) {
		if (this.logout == null) return;
		var txt = decodeURIComponent(req.responseText);
		var res = txt.parseJSON();
		if (res.chk == 1) {
			xDisplay(this.logout, 'inline');
		} else {
			xDisplay(this.logout, 'none');
		}
	},
	setFootPrint: function(url, title) {
		if (url) {
			this.data.foot_url   = escape(url);
		} else {
			this.data.foot_url   = null;
		}
		if (title) {
			this.data.foot_title = escape(title);
		} else {
			this.data.foot_title = null;
		}
		this.saveData();
	},
	getFootURL: function() {
		if (this.data.foot_url) {
			return unescape(this.data.foot_url);
		} else {
			return null;
		}
	},
	getFootTitle: function() {
		if (this.data.foot_title) {
			return unescape(this.data.foot_title);
		} else {
			return null;
		}
	}
};

var mem = new Member();
xAddEventListener(window, 'load', mem.onLoad.bind(mem), true);
