/**
 * いいかも順選択フォーム Class
 */
var IikamoSelect = Class.create({
	// class 共通のメンバ変数
	formId    : 'fcIikamoSelect',
	form      : null,
	listeners : null, 
	defaultValue : -1,
	cookieName : 'IIKAMO_SELECT_VALUE',

	// 初期化
	initialize: function(listeners) {
		var $this = this;

		// フォームの初期化
		if(!this.form) {
			var form = $(this.formId);
			if(form.tagName != 'FORM') {
				form = form.select('form')[0];
			}
			this.form = form;
			this.form.onsubmit = function() {return false};

			var cookieName = this.cookieName;
			var defaultValue = this.defaultValue;

			// load
			var loadValue = function() {
				var value = defaultValue;
				if(cookieName) {
					value = parseInt(getCookie(cookieName));
					if(!value) {
						value = defaultValue;
					}
				}
				return parseInt(value);
			};
			// save
			var saveValue = function(value) {
				if(cookieName) {
					setCookie(cookieName, new String(value));
				}
			}
			// ハンドラを呼び出す関数
			var callHandler = function(name) {
				if($this.listeners && $this.listeners[name]) {
					$this.listeners[name].apply($this, []);
				}
			}
			// フォーム要素にイベントハンドラを設定
			var els = form.elements;
			var fnc = function() {
				saveValue(this.value);
				callHandler('change');
			};
			var value = loadValue();
			for(var i=0; i<els.length; i++) {
				var el = els[i];
				el.checked = (el.value == value);
				$(el).observe('click', fnc);
			}
		}
		// ハンドラをアクティブにする
		this.activate = function() {
			$this.listeners = listeners;
		}
		// 選択された値を取得
		var form = this.form;
		this.getValue = function() {
			var els = form.elements;
			for(var i=0; i<els.length; i++) {
				var el = els[i];
				if(el.checked) {
					return el.value;
				}
			}
			return null;
		}
	}
});

