// $Id: homes_ctrl.js,v 1.14 2011/09/16 02:20:25 shimamut Exp $

/*##################################################################################################*/
/**
 * ブラウザに依存せずにname属性からelementリストを取得
 */
function getElementsByName (name, doc) {
	var _list;
	
	obj = (doc ? doc : document);
	if (obj.all) _list = obj.all.item(name);
	if (obj.getElementsByName) _list = obj.getElementsByName(name);
	return _list;
}

/**
 * ブラウザに依存せずにid属性からelementリストを取得
 */
function getElementById (id, doc) {
	var _id;
	
	doc = (doc ? doc : document);
	if (doc.all) _id = doc.all(id);
	if (doc.getElementById) _id = doc.getElementById(id);
	return _id;
}

/**
 * INPUTへの擬似CLICKイベント（Safari用）
 */
function doClick (node) {
	if (node.tagName.toLowerCase() != 'input') return;
	var type = node.type.toLowerCase();
	if (type == 'checkbox') node.checked = !node.checked;
	if (type == 'radio') node.checked = true;
}

/**
 * 大文字/小文字を区別せずに文字列比較
 * 但しCのそれとは違い、一致したらTRUE、不一致ならFALSEを返すことに注意
 */
function strComp (s1, s2) {
	return (s1.toLowerCase() == s2.toLowerCase());
}

/**
 * NODEが、あるIDを持つNODEの子孫であるかを判定
 *   node :
 *     チェック対象のNODE。
 *   id :
 *     チェック対象のID。
 */
function isDescendantById (node, id) {
	var is_match = false;
	var pointer = node;
	while (pointer) {
		if (pointer.id) {
			is_match = strComp(pointer.id, id);
			if (is_match) break;
		}
		pointer = pointer.parentNode;
	}
	return (is_match);
}

/**
 * NODEが、あるタグの子孫であるかを判定
 *   node :
 *     チェック対象のNODE。
 *   tag :
 *     チェック対象のタグ。
 */
function isDescendantByTag (node, tag) {
	var is_match = false;
	var pointer = node;
	while (pointer) {
		if (pointer.tagName && strComp(pointer.tagName, tag)) {
			is_match = true;
			break;
		}
		pointer = pointer.parentNode;
	}
	return (is_match);
}

/**
 * Window Open
 */
var win = window;
function OpenWin(url,w,h,sc){
	if ((win == window) || win.closed) {
		settings ='width='+w+',height='+h+',scrollbars='+sc+',resizable=yes';
		win=window.open(url,"Wexplanation",settings);
	} else {
		win.location.replace(url);
		win.focus();
	}
}

/**
 *	ページの飛ばし先URLの切り替え(SSL / 非SSL)
 *	2006.02.10 S.Misu
*/
function cChangeAction( submit_name, check_id, form, obj, servername, filename ) {
	this.form = form;
	this.obj = obj;
	this.submit = submit_name;			/*submitのname*/
	this.chk_id = check_id;
	this.servername = servername;
	this.filename = filename;

	this.eClick = function (node) {
		var node_name = node.name;		/*押されたname="~"を取得*/
		if(this.submit != node_name)	return(true);
		if(!this.chk_id) return(true);
		
		if(document.getElementById(this.chk_id).checked){
			this.form.action = 'https://'+ servername + filename;
		} else {
			this.form.action = 'http://'+ servername + filename;
		}
		return true;
	}
	return true;
}
/**
 *	ページの飛ばし先URLの切り替え(SSL / 非SSL)
 */
function cChangeActionOnSubmit(submit_name, checkbox_id) {
	this.submit_name = submit_name;
	this.checkbox_id = checkbox_id;

	this.eClick = function (node) {
		if (this.submit_name != node.name) return(true);
		
		var protocol = null;
		var position = node.form.action.indexOf('://') + 3;
		if(document.getElementById(this.checkbox_id).checked){
			protocol = 'https://';
		} else {
			protocol = 'http://';
		}
		node.form.action = protocol + node.form.action.substr(position);
		return true;
	}
	return true;
}

/**
 *	連続ボタン押下制御
 *  （str_submitをロックし、id_eleのテキストにstr_msgを設定（追記）し、obj_formをsubmitする）
 *	2006.02.14 T.Komoto
 */
function cChangeDisabled(str_submit, obj_form, id_ele, str_msg) {
	this.submit = str_submit;
	this.form = obj_form;
	this.ele = document.getElementById(id_ele);
	this.eClick = function (node) {
		var node_name = node.name;
		if(this.submit!=node_name)	return(true);
		if (!node.disabled) {
			node.disabled = true;
			if (str_msg) {
				myText=document.createTextNode(str_msg);
				this.ele.appendChild(myText);
			}
			this.form.submit();
		}
		return true;
	}
	return true;
}

/**
 * ユーザー応答を求め、スマートフォンサイトに遷移させる。
 */
function confirmSmartphoneTransition(url) {
    if (url && window.confirm("スマートフォン用のサイトがあります。表示しますか？")) {
        window.location.href = url;
        return false;
    } else {
        return true;
    }
}

/*##################################################################################################*/
/**
 * BGカラーを変える
 */
function cChangeBgColor(ele_name,change_bgcolor_id,default_color,cheked_color){
	this.eClick = function (node) {
		var node_id = node.id;
		var node_name = node.name;
		if (!node_id) return (true);
		if (node_name != ele_name) return (true);
		if(document.getElementById(node_id).checked){
			document.getElementById(change_bgcolor_id+node.value).style.backgroundColor = cheked_color;
		} else {
			document.getElementById(change_bgcolor_id+node.value).style.backgroundColor = default_color;
		}
		return true;
	}
	this.eLoad = function (node) {
		list = getElementsByName (ele_name);
		for (var i = 0; i < list.length; ++i) {
			this.eClick (list[i]);
		}
		return true;
	}
}

/**
 * LABELタグに対し、マウスが乗った際のハイライト動作を指定
 */
function cHighlightLabel (on_class) {
	this.on_class = on_class;
	this.setExcept = function (regext_except) {
		this.except = new RegExp (regext_except.toLowerCase(), "i");
	}
	this.eMouseOver = function (node) {
		if (!strComp(node.tagName, 'label')) return (true);
		node_id = node.id;
		node.style.cursor = (document.all ? 'hand' : 'pointer');
		change_color = true;
		if (this.except) {if (node_id.match(this.except)) {change_color = false}};
		if (change_color && this.on_class) {
			this.org_class = node.className;
			node.className = this.on_class + ' ' + this.org_class;
		}
	}
	this.eMouseOut = function (node) {
		if (!strComp(node.tagName, 'label')) return (true);
		if (this.on_class) {
			node.className = this.org_class;
		}
	}
}

/**
 * CHECKBOXのグルーピングを行う
 *   parent_id :
 *     グループの親となるチェックボックスのID。このボックスが常にトリガとなる。
 *   children_name :
 *     グループの子供たちの名前。こちらはNAME属性であることに注意。
 *     これらの子らが、親と連動してチェックされたり外されたりする。
 *   children_id_regexp :
 *     同一名の子供たちを別々の親に紐付けたい場合などに、ID属性を正規表現で記述。
 */
function cCheckGroup (parent_id, children_name, children_id_regexp) {
	this.pid     = parent_id;
	this.cname   = children_name.toLowerCase();
	this.usecid  = (children_id_regexp ? true : false);
	this.cexp    = new RegExp (children_id_regexp.toLowerCase(), "i");
	this.checked = false;
	this.syncObj = new Array();
	this.getTime = function () {
		dd = new Date();
		return dd.getTime();
	}
	this.etime  = this.getTime();
	this.setSync = function (obj) {
		this.syncObj.push(obj);
	}
	this.sync = function (checked) {
		this.checked = checked;
		target = getElementById(this.pid);
		target.checked = checked;
	}
	this.eClick = function (node) {
		if (!strComp(node.tagName, 'input')) return (true);
		var node_id = node.id;
		if (!node_id) return (true);
		if (node_id.toLowerCase() != this.pid.toLowerCase()) return (true);
		var list = getElementsByName (this.cname);
		var is_target;
		this.checked = !this.checked;
		var now = this.getTime();
		if (now && (this.etime + 100) >= now) this.checked = node.checked;
		this.etime = now;
		for (var i = 0; i < list.length; ++i) {
			is_target = true;
			if (this.usecid) {
				id = list[i].id;
				is_target = id.match(this.cexp);
			}
			if (is_target) list[i].checked = this.checked;
		}
		for (var i = 0; i < this.syncObj.length; ++i) {
			this.syncObj[i].sync(this.checked);
		}

		return (true);
	}
	this.eLoad = function () {
		var ua = navigator.userAgent;
		if (ua.indexOf("Safari") == -1) {
			// ブラウザの戻る時にバッファがクリアされるため、初期値を設定
			var node = document.getElementById (parent_id);
			this.checked = node.checked;
		}
		if (ua.indexOf("Safari") != -1) {
			// Safari用の特別初期化処理
			var pnode = document.getElementById(parent_id);
			this.checked = pnode.checked;
			pnode['onclick'] = function() {homesCtrl._eClick(pnode);};
		}
		if (ua.indexOf("Opera 7") != -1) {
			// Opera 7用の特別初期化処理
			list = document.getElementsByTagName('label');
			for (i=0;i<list.length;++i) {
				trg=list[i].attributes.getNamedItem('for');
				if (trg) {
					if (trg.value==parent_id) {
						var pnode = document.getElementById(parent_id);
						list[i]['onclick'] = function() {homesCtrl._eClick(pnode);};
						return;
					}
				}
			}
		}
	}
}

/**
 * ブロックをクリック可能にし、リンクを設定する
 */
function cClickableBlock (id, url, blank, target) {
	this.id  = id.toLowerCase();
	this.url = url;
	this.blank  = blank;
	this.target = (target ? target : window.self);
	this.setHighlightClass = function (class_name) {
		this.highlight = class_name;
	}
	this.eMouseOver = function (node) {
		if (!isDescendantById(node, this.id)) return (true);
		window.status = this.url;
		node.style.cursor = (document.all ? 'hand' : 'pointer');
		if (this.highlight) {
			var p = getElementById (id);
			this.org_class = p.className;
			p.className = this.highlight + ' ' + this.org_class;
		}
	}
	this.eMouseOut = function (node) {
		if (!isDescendantById(node, this.id)) return (true);
		window.status = '';
		if (this.highlight) {
			var p = getElementById (id);
			p.className = this.org_class;
		}
	}
	this.eClick = function (node) {
		if (!isDescendantById(node, this.id)) return (true);
		if (isDescendantByTag(node, 'A')) return (true);
		win = (this.blank ? window.open() : this.target);
		win.location.href = this.url;
		return true
	}
}

/**
 * Aタグでのポップアップを実現
 */
function cPopUpAnchor (id, w, h, sc ,name) {
	this.id  = id;
	this.w   = (w ? w : 650);
	this.h   = (h ? h : 620);
	this.sc  = (sc ? sc : 'yes');
	this.win = null;
	this.name = (name ? name : null);
	this.eClick = function (node) {
		if (!isDescendantById(node, this.id)) return (true);
		anchor = getElementById(this.id);

		var jaref = anchor.getAttribute('jaref');
		if(jaref){
			href = jaref;
		}else{
			href = anchor.href;
		}

		if (this.win == null || this.win.closed == undefined || this.win.closed) {
			settings ='width='+this.w+',height='+this.h+',scrollbars='+this.sc+',resizable=yes';
			this.win=window.open(href,this.name,settings);
			this.win.focus();
		} else {
			this.win.location.replace (href);
			this.win.focus();
		}
		return (false);
	}
}

/**
 * LOAD時に指定コントロールへフォーカスを当てる
 */
function cSetFocusOnLoad (name) {
	this.name = name;
	this.eLoad = function (node) {
		var ctrl = getElementsByName (this.name);
		ctrl[0].focus();
		return true;
	}
}

/**
 * イメージボタンに対して、通常のsubmitボタン同様にクリックされたボタンの名前へ値を入れる
 */
function cSubmitTracer () {
	this.form  = null;
	this.name  = "";
	this.value = null;
	this.eClick = function (node) {
		if (node.tagName == 'INPUT') {
			if (strComp(node.type, 'submit') || strComp(node.type, 'image')) {
				this.form  = node.form;
				this.name  = node.name;
				this.value = node.value;
			}
		}
		return true;
	}
}

/**
 * 指定画像の自動サイズ縮小
 */
function cFixImage (id_exp, max_width, max_height) {
	this.id_exp     = new RegExp (id_exp, "i");
	this.max_width  = max_width;
	this.max_height = max_height;
	this.eLoad = function (node) {
		for (i = 0; i < document.images.length; ++i) {
			img = document.images[i]
			if (img.id) {
				if (img.id.match(this.id_exp)) {
					img_width  = img.width;
					img_height = img.height;
					img_scale  = img_width / img_height;
					if (img_height > this.max_height) {
						img_width  = img_scale * this.max_height;
						img_height = this.max_height;
					}
					if (img_width > this.max_width) {
						img_height = img_scale * this.max_width;
						img_width  = this.max_width;
					}
					if (img_width != img.width || img_height != img.height) {
						img.width  = img_width;
						img.height = img_height;
					}
				}
			}
		}
		return true;
	}
}

/**
 * JavaScriptで値を変えている変数を、Load時に元へ戻す
 */
function cResetValue (form, key, value) {
	this.form  = form;
	this.key   = key;
	this.value = value;
	this.eLoad = function (node) {
		form.elements[key].value = this.value;
		return true;
	}
}

/*##################################################################################################*/
/**
 *	zip_codeからaddressを取得
 *	2005.12.20 S.Misu
 */
function cZipToAddress(id, zip1_id, zip2_id) {
	this.id   = id;
	this.zip1 = getElementById(zip1_id);
	this.zip2 = getElementById(zip2_id);
	this.win  = null;
	this.eClick = function(node) {
		if (!isDescendantById(node, this.id)) return (true);
		var anchor = getElementById(this.id);
		var post1 = this.zip1.value;
		var post2 = this.zip2.value;
		if (!post1 || !post2) {
			alert('まず郵便番号を入力してください');
			return false;
		}
		var href = anchor.href + "?post1=" + post1 + "&post2=" + post2;
		if (this.win == null || this.win.closed == undefined || this.win.closed) {
			this.win = open(href, "_blank", "width=640,height=300,resizable=yes");
			this.win.focus();
		} else {
			this.win.location.replace (href);
			this.win.focus();
		}
		return (false);
	}
}
/**
 * マスター選択ウィンドウを表示
 * button_name	: クリック判定用 ボタン名
 * url			: 飛び先
 * code			: 返戻値受取り用要素識別
 * with_id		: 返戻値の先頭に ID を含めるか？
 */
function cMasterListOpener(button_name, url, code, with_id, width, height) {
	this.win	= null;
	this.width	= (width ? width : 500);
	this.height	= (height ? height : 600);
	this._makeUrl = function(node) {
		with_id = (with_id ? 1 : 0);
		var now = new Date();
		var code_val = getElementById(code + node.id);
		var href = url + '?id=' + node.id + '&code=' + code + '&with_id=' + with_id;
		if (code_val && code_val.value) href += '&val=' + escape(code_val.value);
		href += '&salt=' + now.getTime();
		return href;
	}
	this.eClick = function(node) {
		if (node.name != button_name || !node.id) return true;
		href = this._makeUrl(node);
		if (this.win == null || this.win.closed == undefined || this.win.closed) {
			this.win = open(href, "_blank", "width="+this.width+",height="+this.height+",scrollbars=yes,resizable=yes");
			this.win.focus();
		} else {
			this.win.location.replace(href);
			this.win.focus();
		}
		return false;
	}
}
/**
 * 呼び出し元に値をセットして終了
 * button_name	: クリック判定用名称
 * item_name	: 返戻値作成用要素名称
 * code			: 返戻値受取り用要素識別
 * with_id		: 返戻値の先頭に ID を含めるか？
 */
function cMasterListSubmit(button_name, item_name, code, with_id) {
	this.id_separator = '|';
	this.data_separator = ',';
	this._getCodeValues = function(node) {
		var item = getElementsByName(item_name);
		var result = new Array();

		for (var i = 0; i < item.length; ++i) {
			if (item[i].type == 'checkbox' && item[i].checked) {
				result.push(item[i].value);
			} else if (item[i].type == 'select-one') {
				result.push(item[i].value);	
			} else if (item[i].type == 'select-multiple') {
				for (var j = 0; j < item[i].options.length; ++j) {
					if (item[i].options[j].selected) {
						result.push(item[i].options[j].value);
					}
				}
			}
		}
		var ret = result.join(this.data_separator);
		if (ret) {
			if (with_id) ret = node.id + this.id_separator + ret;
		}
		return ret;
	}
	this._setOpenerValue = function (key, val) {
		var _item = getElementById(key, window.opener.document);
		if (_item) {
			_item.value = val;
		}
	}
	this.eClick = function(node) {
		if (node.name == button_name && node.id) {
			this._setOpenerValue(code+node.id, this._getCodeValues(node));
			window.close();
		}
		return true;
	}
}

/*##################################################################################################*/
var homesCtrl =
{
	/**
	 * CLICKイベント
	 * LABELタグがIE以外でこのイベントを受け取った場合、特別処理としてIDで指定された
	 * NODEへイベントをバブリングする。
	 * 特別処理を行うには、IDの値を次のようにする必要がある。
	 *   id="lbl:{バブリングするコントロールのID}"
	 */
	eClick : function (e) {
		var node = (document.all ? event.srcElement : e.target);
		if (!node.tagName) node = node.parentNode;
		if (!document.all) {
			if (strComp(node.tagName, 'label')) {
				var target=node.attributes.getNamedItem('for');
				if (target) {
					node = document.getElementById (target.value);
					if (navigator.userAgent.indexOf("Safari") != -1) doClick (node);
				}
			}
		}
		ret = this._eClick (node);
		if (!ret) {
			if (navigator.userAgent.indexOf("Safari")) {
					node['onclick'] = function () {return false};
			} else if (e && e.preventDefault) {
				e.preventDefault();
			} else if (event && event.preventDefault) {
				event.preventDefault();
			}
		}
		return (ret);
	},
	_eClick : function (node) {
		var ret = true;
		var obj = (!!Hyjax) ? Hyjax.EventHandler.obj : this.obj;
		for (var i = 0; i < obj.length; ++i) {
			if (obj[i].eClick) {
				var res = obj[i].eClick(node);
				ret = (ret && res);
			}
		}
		return ret;
	},
	/**
	 * MOUSEOVERイベント
	 */
	eMouseOver : function (e) {
		var node = (document.all ? event.srcElement : e.target);
		if (!node.tagName) node = node.parentNode;
		ret = this._eMouseOver (node);
		// ここでtrueを返すと、IEでなぜかAタグによるリンクがステータスに表示されなくなるため
		ret = false;
		return (ret);
	},
	_eMouseOver : function (node) {
		var ret = true;
		for (var i = 0; i < this.obj.length; ++i) {
			if (this.obj[i].eMouseOver) {
				var res = this.obj[i].eMouseOver(node);
				ret = (ret && res);
			}
		}
		return ret;
	},
	/**
	 * MOUSEOUTイベント
	 */
	eMouseOut : function (e) {
		var node = (document.all ? event.srcElement : e.target);
		if (!node.tagName) node = node.parentNode;
		ret = this._eMouseOut (node);
		if (!ret && e) e.preventDefault ();
		return (ret);
	},
	_eMouseOut : function (node) {
		var ret = true;
		for (var i = 0; i < this.obj.length; ++i) {
			if (this.obj[i].eMouseOut) {
				var res = this.obj[i].eMouseOut(node);
				ret = (ret && res);
			}
		}
		return ret;
	},
	/**
	 * LOADイベント
	 */
	eLoad : function (e) {
		var ret = true;
		var node = (document.all ? event.srcElement : e.target);
		for (var i = 0; i < this.obj.length; ++i) {
			if (this.obj[i].eLoad) {
				var res = this.obj[i].eLoad(node);
				ret = (ret && res);
			}
		}
		if (!ret && e) e.preventDefault ();
		return (ret);
	},
	/**
	 * 動作対象となるオブジェクトの登録
	 */
	registerObj : function (o) {
		if (typeof Hyjax == 'undefined') {
			if (!this.obj) this.obj = new Array();
			this.obj.push (o);
		} else {
			// Hyjax がある場合はイベントハンドラを Hyjax へ委譲
			Hyjax.EventHandler.register(o);
		}
	}
};

/*##################################################################################################*/
/**
 * イベントのハンドリング
 */
if (typeof Hyjax == 'undefined') {
	// Hyjax がない場合のみ，ここでイベントを登録する
	if (document.attachEvent)
	{
		document.attachEvent('onclick',     function(){return homesCtrl.eClick()});
		document.attachEvent('onmouseover', function(){return homesCtrl.eMouseOver()});
		document.attachEvent('onmouseout',  function(){return homesCtrl.eMouseOut()});
	}
	else if (document.addEventListener)
	{
		document.addEventListener('click',     function(e){return homesCtrl.eClick(e)},     true);
		document.addEventListener('mouseover', function(e){return homesCtrl.eMouseOver(e)}, true);
		document.addEventListener('mouseout',  function(e){return homesCtrl.eMouseOut(e)},  true);
	}

	if (window.attachEvent) {
		window.attachEvent('onload', function(){return homesCtrl.eLoad()});
	}
	else if (window.addEventListener) {
		window.addEventListener('load', function(e){return homesCtrl.eLoad(e)}, true);
	}
}


// LABELのハイライト処理は常に登録しておく
var o = new cHighlightLabel ();
homesCtrl.registerObj (o);

