var xml_url = "category.xml?t=" + new Date();
var cnt = 0;               // カテゴリ数
var itm_cnt = 0;           // アイテム数 izawa
var catwidth = 200         // パーソナライズ幅
var h_cnt = 3;             // 縦のBOX数
var posAry;
var interval = 40;
var rowline = 285;
var xAry = [10,305,600];
var startX = 0;
var startY = rowline;
var zIndex = 1;
var chkAry = "";


// HTTPリクエストを行ない、XMLファイルを読込む
function httpXmlRequest() {
var httpObj;               // HTTP通信用オブジェクト

	// FireFox用
	try {
		netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	} catch (e) {
		;
	}
	// httpリクエストオブジェクトを作成
	try {
		if (window.XMLHttpRequest) {
			httpObj = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			httpObj = new ActiveXObject("Microsoft.XMLHTTP");
		} else {
			httpObj = false;
		}
	} catch (e) {
		httpObj = false;
	}
	if (httpObj) {
		try {
			httpObj.open("get",xml_url,false);
			httpObj.send("");
		} catch(e) {
			alert(e);
		}
		dispXmlElement(httpObj.responseXML);
	}
}


// 画面作成
function dispXmlElement(xml) {
	// category要素参照の配列
	var categories = xml.getElementsByTagName("category");
	var names = "";
	document.open();
	posAry = new Array(categories.length);
	for (var i = 0 ; i < categories.length ; i++) {
		// 情報を格納する変数の初期化
		var id = "";
		var name = "";
		var barcolor = "";
		var categorycolor = "";
		var a = "";
		var url = "";
		var host = "";
		var val = "";
		var childcnt = 0;
		cnt++;
		// category要素内の子要素の情報を取得
		for(var j = 0 ; j < categories[i].childNodes.length ; j++) {
			var child = categories[i].childNodes[j];
			id = cnt;
			if (child.tagName == "name") {
				if (child.firstChild) {
					name = child.firstChild.nodeValue;
					names += "," + name;
				}
			} else if (child.tagName == "barcolor") {
				if (child.firstChild) {
					barcolor = child.firstChild.nodeValue;
				}
			} else if (child.tagName == "categorycolor") {
				if (child.firstChild) {
					categorycolor = child.firstChild.nodeValue;
				}
			} else if (child.tagName == "lists") {
				var lists = child.getElementsByTagName("list");
				childcnt = lists.length;
				for(var k = 0 ; k < childcnt ; k++) {
					for(var l = 0 ; l < lists[k].childNodes.length ; l++) {
						if (lists[k].childNodes[l].tagName == 'name') {
							if (lists[k].childNodes[l].firstChild) {
								a = a + "," + lists[k].childNodes[l].firstChild.nodeValue;
							}
						} if (lists[k].childNodes[l].tagName == "url") {
							if (lists[k].childNodes[l].firstChild) {
								url += "," + lists[k].childNodes[l].firstChild.nodeValue;
							}
						} if (lists[k].childNodes[l].tagName == "host") {
							if (lists[k].childNodes[l].firstChild) {
								host += "," + lists[k].childNodes[l].firstChild.nodeValue;
							}
						} if (lists[k].childNodes[l].tagName == "value") {
							if (lists[k].childNodes[l].firstChild) {
								val += "," + lists[k].childNodes[l].firstChild.nodeValue;
							}
						}
					}
				}
			}
		}
		// テンプレートとなるタグ要素を複製
		if (name.length > 18) {
			name = "<small>" + name.substring(0,18)  + "...</small>";
		}
		var html = "<div id=\"tbl" + id + "\">\n" +
				   "  <div id=\"bar" + id + "\" style=\"background:url(image/green-bar.png);color:navy;font-size:110%;letter-spacing:4px;\">" + 
				   "<button type=\"button\" onclick=\"return closeChildWindow(this ,'" + itm_cnt + "','" + a.split(",").length + "');\" id=\"close" + id + "\" class=\"btn\">×</button>&nbsp;" + name + "</div>\n" +
				   "  <div id=\"category" + id + "\" style=\"background-color:mintcream\" width=\"250px\">\n" +
				   "    <button class=\"btnCss\" onClick=\"return checkSelect('on' ,'" + itm_cnt + "','" + a.split(",").length + "')\">全選択</button>\n" +
				   "    <button class=\"btnCss\" onClick=\"return checkSelect('off','" + itm_cnt + "','" + a.split(",").length + "')\">解除</button>\n" +
				   "    <br />\n";
					for(var m = 1 ; m <  a.split(",").length; m++) {
						html += "    <input type=\"checkbox\" name=\"" + host.split(",")[m] +
								"\" value=\"" + val.split(",")[m] + "\" id=\"itm" + itm_cnt + "\" onClick='itemSetCookie(\"itm" + itm_cnt + "\")'>\n" +
								"    <a target=\"_blank\" href=\"" + url.split(",")[m] + "\">" +  a.split(",")[m] + "</a>\n";
						if (m < a.split(",").length - 1) {
							html += "    <br />\n";
						}
						// 総アイテム数をカウントアップ
						itm_cnt++;
					}
					html += "    <br />\n" +
							"  </div>\n" +
							"</div>\n";
		document.write(html);
		// 各ボックスの高さを保存しておく
		posAry[i] = 60 + (childcnt * 20);
		//$("tbl" + (i + 1)).style.height = 60 + (childcnt * 20);
	}
	// パーソナライズ
	var html = "      <div id=\"area\" style=\"top:5px;left:794px;width:" + catwidth + "px;\" onmousedown=\"this.style.zIndex=zIndex++\">\n";
	html += "        &nbsp;&nbsp;<img src=\"image/person.png\" /><a id=\"person\" onClick=\"openPersonalize();\" onMouseover=\"javascript:this.style.cursor='pointer';\" onMouseout=\"javascript:this.style.cursor='auto';\"><img src=\"image/close.png\" /></a></b>\n";
	html += "        <div id=\"check\">\n";
	for(var j = 1 ; j < names.split(",").length ; j++) {
		html += "        <input type=\"checkbox\" id=\"chk" + j + "\">" + names.split(",")[j] + "<br />\n";
	}
	html += "        <button onclick=\"return clearCookie();\">初期状態に戻す</button><br />\n";
	html += "        </div>\n";
	html += "      </div>\n";
	document.write(html);
	document.close();
	
	for(var i= 0 ; i < itm_cnt - 1 ; i++) {
		chkAry += ",";
	}
}


/*「全選択」「全解除」ボタン押下時処理 */
function checkSelect(mode,idx,max) {
	for(var i = 1 ; i < max ; i++) {
		$("itm" + idx).checked = (mode == "on");
		itemSetCookie("itm" + idx);
		idx++;
	}
	return false;
}


/* 「初期状態に戻すボタン」処理 */
function clearCookie() {
	for(var i = 1 ; i <= cnt ; i++) {
		document.cookie = "close" + i + "=" + "xx; expires=Tue, 1-Jan-1980 00:00:00;";
		document.cookie = "btn" + i +  "=" + "xx; expires=Tue, 1-Jan-1980 00:00:00;";
		document.cookie = "tbl" + i + "X=" + "xx; expires=Tue, 1-Jan-1980 00:00:00;";
		document.cookie = "tbl" + i + "Y=" + "xx; expires=Tue, 1-Jan-1980 00:00:00;";
	}
	// アイテムのチェック状態
	document.cookie = "chkAry=" + "xx; expires=Tue, 1-Jan-1980 00:00:00;";
	visibleControl();
	return false;
}


/* カテゴリの「×」ボタンを押下したときの処理 */
function closeChildWindow(obj,idx,max) {
	$(obj.id.replace("close","tbl")).style.visibility = "hidden";
	$(obj.id.replace("close","category")).style.visibility = "hidden";
	$(obj.id.replace("close","chk")).checked = "";
	setCookie(obj.id,"hidden",365);
	startX = $(obj.id.replace("close","tbl")).style.left.replace("px","");
	startY = $(obj.id.replace("close","tbl")).style.top.replace("px","");
	// チェックボックス全解除処理
	checkSelect("off", idx, max);
	rebuild();
}


/* アイテムIDからCookieに設定・削除 */
function itemSetCookie(id) {
var idx = id.replace("itm","");
var ary = chkAry.split(",");

	if ($(id).checked) {
		// Cookie設定
		ary[idx] = "enable";
	} else {
		// Cookie削除
		ary[idx] = "";
	}
	chkAry = "";
	for(var i = 0 ; i < itm_cnt ; i++) {
		if (i > 0) {
			chkAry += ",";
		}
		if (ary[i] == "undefined") {
			chkAry += "";
		} else {
			chkAry += ary[i];
		}
	}
	setCookie("chkAry",chkAry,365);
}


/* アイテムIDからCookieを読込チェックボックスのコントロール */
function itemGetCookie(id) {
var idx = id.replace("itm","");
var ary = getCookie("chkAry").split(",");

	if (ary[idx] == "enable") {
		$(id).checked = true;
	} else {
		$(id).checked = false;
	}
}


/* パーソナライズのオープン・クローズ */
var close = false;
function openPersonalize() {
	$("area").style.zIndex = zIndex++;
	if (! close) {
		$("person").innerHTML = "<img src=\"image/open.png\" />";
		$("check").style.visibility = "hidden";
		bytefx.size($("area"),{width:catwidth,height:23},8);
	} else {
		$("person").innerHTML = "<img src=\"image/close.png\" />";
		$("check").style.visibility = "visible";
		bytefx.size($("area"),{width:catwidth,height:cnt * 23.35 + 23},8);
	}
	close = ! close;
}


/* ウィンドウをアクティブに */
function activeWindow(e) {
	var target_node;
	if (e.target) {
		target_node = e.target;
	} else {
		target_node = e.srcElement;
	}
	if ($(target_node.id.replace("category","tbl"))) {
		$(target_node.id.replace("category","tbl")).style.zIndex = zIndex++;
	}
}


/* パーソナライズチェックボックス押下時処理 */
function chkControl(e) {

	var target_node;
	if (e.target) {
		target_node = e.target;
	} else {
		target_node = e.srcElement;
	}
	var chkbox = $(target_node.id);
	if (chkbox.checked) {
		// チェックボックスON時処理
		$(target_node.id.replace("chk","tbl")).style.visibility = "visible";
		$(target_node.id.replace("chk","category")).style.visibility = "visible";
		filter($(target_node.id.replace("chk","close")),100);
		setCookie(target_node.id.replace("chk","close"),"visible",365);
		rebuild2(target_node.id.replace("chk","tbl"));
		// m.miki added
		setCookie(target_node.id.replace("chk","tbl") + "X",$(target_node.id.replace("chk","tbl")).style.left,365);
		setCookie(target_node.id.replace("chk","tbl") + "Y",$(target_node.id.replace("chk","tbl")).style.top,365);
	} else {
		// チェックボックスOFF時処理 = 「×」ボタン押下時処理
		$(target_node.id.replace("chk","close")).click();
/* izawa
		$(target_node.id.replace("chk","tbl")).style.visibility = "hidden";
		$(target_node.id.replace("chk","category")).style.visibility = "hidden";
		setCookie(target_node.id.replace("chk","close"),"hidden",365);
		startX = $(target_node.id.replace("chk","tbl")).style.left.replace("px","");
		startY = $(target_node.id.replace("chk","tbl")).style.top.replace("px","");
		rebuild();
izawa */
	}
}

// ドラッグ開始
function dragBegin() {
	startX = this.style.left.replace("px","");
	startY = this.style.top.replace("px","");
	document.body.style.cursor = "move";
	filter(this,50);
	this.style.zIndex = zIndex++;
	return false;
}

// ドラッグ中
function dragging() {
	return false;
}

// ドラッグ終了
function dragged() {
	document.body.style.cursor = "auto";
	filter(this,100);
	var left = this.style.left.replace("px","");
	var top  = this.style.top.replace("px","");
	if (left < 140) {
		bytefx.move(this,{x:xAry[0],y:top},30);
		this.style.left = xAry[0] + "px";
	} else if (left < 420) {
		bytefx.move(this,{x:xAry[1],y:top},30);
		this.style.left = xAry[1] + "px";
	} else {
		bytefx.move(this,{x:xAry[2],y:top},30);
		this.style.left = xAry[2] + "px";
	}
	straightensSelf(this);
	straightens(this);
	savePosition();
//izawa alert(startX + "px" + "-" + this.style.left + ":" + startY + "px" + "-" + this.style.top);
//izawa	if (startX + "px" != this.style.left) {

	if ((startX + "px" != this.style.left) || startY + "px" < this.style.top) {
		rebuild();
	}

	return false;
}

// ドロップしたオブジェクトの動作
function straightensSelf(obj) {
	var x = Number(obj.style.left.replace("px",""));
	var y = Number(obj.style.top.replace("px",""));
	var max = rowline;
	// 先頭に置くケース
	if (y < rowline) {
		bytefx.move(obj,{x:x,y:rowline},30);
		obj.style.top = rowline + "px";
		return false;
	}
	var i;
	// 自身が割込むケース
	for(i = 1 ; i <= cnt ; i++) {
		if (obj.id != "tbl" + i) {
			if ($("tbl" + i).style.visibility != "hidden") {
				if (x == Number($("tbl" + i).style.left.replace("px",""))) {
					var targetY = Number($("tbl" + i).style.top.replace("px",""));
					if (y >= targetY) {
						var h = (targetY + posAry[i - 1]);
						if (max < h) {
							max = h;
						}
						if (y < h) {
							bytefx.move(obj,{x:x,y:h},30);
							obj.style.top = h + "px";
							break;
						}
					}
				}
			}
		}
	}
	// 最下部にドロップしたケース
	if (i > cnt) {
		bytefx.move($(obj.id),{x:x,y:max},30);
		obj.style.top = max + "px";
	}
}

// 移動処理
function straightens(obj) {
	var x = obj.style.left.replace("px","");
	var y = obj.style.top.replace("px","");
	for(var i = 1 ; i <= cnt ; i++) {
		if (obj.id != "tbl" + i) {
			if ($("tbl" + i).style.visibility != "hidden") {
				if (x == Number($("tbl" + i).style.left.replace("px",""))) {
					if (y <= Number($("tbl" + i).style.top.replace("px",""))) {
						var h = (Number(y) + Number(posAry[obj.id.replace("tbl","") - 1]));
						if (h > Number($("tbl" + i).style.top.replace("px",""))) {
							bytefx.move($("tbl" + i),{x:x,y:h},30);
							$("tbl" + i).style.top = h + "px";
							straightens1($("tbl" + i));
						}
					}
				}
			}
		}
	}
	
}

// 繰り返し移動処理
function straightens1(obj) {
	var x = obj.style.left.replace("px","");
	var y = obj.style.top.replace("px","");
	for(var i = 1 ; i <= cnt ; i++) {
		if (obj.id != "tbl" + i) {
			if ($("tbl" + i).style.visibility != "hidden") {
				if (x == Number($("tbl" + i).style.left.replace("px",""))) {
					if (y < (Number($("tbl" + i).style.top.replace("px","")) + posAry[i - 1])) {
						var h = (Number(y) + posAry[obj.id.replace("tbl","") - 1]);
						if (h > Number($("tbl" + i).style.top.replace("px",""))) {
							bytefx.move($("tbl" + i),{x:x,y:h},30);
							$("tbl" + i).style.top = h + "px";
							straightens1($("tbl" + i));
						}
					}
				}
			}
		}
	}
	return false;
}


/* カテゴリ削除移動処理 */
function rebuild() {
	var row = 65536;
	var rowObj = null;
	for(var i = 1 ; i <= cnt ; i++) {
		var x = Number($("tbl" + i).style.left.replace("px",""));
		var y = Number($("tbl" + i).style.top.replace("px",""));
		if (x == startX) {
			if ($("tbl" + i).style.visibility != "hidden") {
				if (y > startY) {
					if (y < row) {
						row = y;
						rowObj = $("tbl" + i);
					}
				}
			}
		}
	}
	if (rowObj) {
		bytefx.move(rowObj,{x:startX,y:startY},30);
		rowObj.style.top = startY + "px";
		setCookie(rowObj.id + "Y",rowObj.style.top,365);
		startY = Number(Number(startY) + Number(posAry[rowObj.id.replace("tbl","") - 1]))
		rebuild();
	}
	return false;
}

// カテゴリ再表示移動処理
function rebuild2(id) {
	var h = rowline;
	var rowObj;
	for(var i = 1 ; i <= cnt ; i++) {
		var x = $("tbl" + i).style.left.replace("px","");
		var y = $("tbl" + i).style.top.replace("px","");
		if (x == xAry[0]) {
			if (id != "tbl" + i) {
				if ($("tbl" + i).style.visibility != "hidden") {
					h += Number(posAry[i -1]);
				}
			}
		}
	}
	$(id).style.top = h + "px";
	$(id).style.left = xAry[0] + "px";
	return false;
}


// 最終的な位置を保存
function savePosition() {
	for(var i = 1 ; i <= cnt ; i++) {
		setCookie("tbl" + i + "X",$("tbl" + i).style.left,365);
		setCookie("tbl" + i + "Y",$("tbl" + i).style.top ,365);
	}
}

// cookieの設定(キー)
function getCookie(key, tmp1, tmp2, xx1, xx2, xx3) {
	tmp1 = " " + document.cookie + ";";
	xx1 = xx2 = 0;
	while(xx1 < tmp1.length) {
		xx2 = tmp1.indexOf(";", xx1);
		tmp2 = tmp1.substring(xx1 + 1, xx2);
		xx3 = tmp2.indexOf("=");
		if (tmp2.substring(0, xx3) == key) {
			return(unescape(tmp2.substring(xx3 + 1, xx2 - xx1 - 1)));
		}
		xx1 = xx2 + 1;
	}
	return("");
}

// cookieの設定(キー,値,有効期限)
function setCookie(key,val,tmp) {
	// 有効期限を設定する
	var expires = new Date();
	expires.setTime(expires.getTime() + (tmp * 24 * 60 * 60 * 1000));
	// cookieの設定
	document.cookie = key + "=" + escape(val) + "; expires=" + expires.toGMTString();
}


// 検索時のチェック
function preSubmit(){
	var flg = 0;
	var frm = document.HBS;

	if (frm.kywd.value == "") {
		alert("検索キーワードを入力してください");
		frm.kywd.focus();	
		return false;
	}

	for(var i = 0 ; i < itm_cnt ; i++) {
		if ($("itm" + i).checked == true) {
			flg = 1;
			break;
		}
	}

	if (flg == 0) {
		alert("データベースを選択してください");
		return false;
	}
	return true;
}


// cookieから表示情報をコントロールします（起動時、初期状態に戻したとき）
function visibleControl() {
var amari;
var syo;
var top = [0,0,0];

	for(var i = 1 ; i <= cnt ; i++) {
		var tmp = getCookie("close" + i);
		amari = (i % h_cnt);
		syo   = Math.ceil(i / h_cnt);
		if (tmp != "hidden") {
			var tblObj = $("tbl" + i);
			var x = getCookie("tbl" + i + "X");
			if (x == null || x == "") {
				//if (amari == 1) {
				//	tblObj.style.left = xAry[0] + "px";
				//} else if (amari == 2) {
				//	tblObj.style.left = xAry[1] + "px";
				//} else if (amari == 0) {
				//	tblObj.style.left = xAry[2] + "px";
				//}
				tblObj.style.left = xAry[(syo - 1)] + "px";
			} else {
				tblObj.style.left = x;
			}
			var y = getCookie("tbl" + i + "Y");
			if (y == null || y == "") {
				//if (top[amari] == 0) {
				if (top[(syo - 1)] == 0) {
				//if (i < 4) {
					//tblObj.style.top  = ((syo * (rowline - interval)) + interval) + "px";
					//top[amari] = ((syo * (rowline - interval)) + interval) + posAry[i - 1];
					tblObj.style.top  = ((amari * (rowline - interval)) + interval) + "px";
					top[(syo - 1)] = ((amari * (rowline - interval)) + interval) + posAry[i - 1];
				} else {
					//tblObj.style.top  = top[amari] + "px";
					//top[amari] += posAry[i - 1];
					tblObj.style.top  = top[(syo - 1)] + "px";
					top[(syo - 1)] += posAry[i - 1];
				}
			} else {
				tblObj.style.top  = y;
			}
		}
	}
	for(var j = 1 ; j <= cnt ; j++) {
		var tmp = getCookie("close" + j);
		if (tmp == "hidden") {
			$("category" + j).style.visibility = "hidden";
			$("tbl" + j).style.visibility = "hidden";
			$("chk" + j).checked = "";
		} else {
			$("category" + j).style.visibility = "visible";
			$("tbl" + j).style.visibility = "visible";
			$("chk" + j).checked = "checked";
		}
	}

	// チェックボックスコントロール
	chkAry = getCookie("chkAry");
	for(var k = 0 ; k < itm_cnt ; k++) {
		itemGetCookie("itm" + k);
	}

}

// ロード時のリスナーをセット
function setListeners(e) {
	for(var i = 1 ; i <= cnt ; i++) {
		addListener($("chk" + i),"click",chkControl,false);
		addListener($("tbl" + i),"mousedown",activeWindow,false);
		bytefx.drag($("tbl" + i),dragBegin,dragged);
	}
	addListener($("area"),"mousedown",activeWindow,false);
	visibleControl();
}

// イベントリスナー登録
function addListener(elem,eventType,func,cap) {
	if (elem.addEventListener) {
		elem.addEventListener(eventType,func,cap)
	} else if (elem.attachEvent) {
		elem.attachEvent("on" + eventType,func);
	} else {
		alert("ご利用のブラウザはサポート対象外です");
		return false;
	}
}

// イベントリスナー解除
function removeListener(elem, eventType,func,cap) {
	if (elem.removeEventListener) {
		elem.removeEventListener(eventType,func,cap);
	} else if (elem.detachEvent) {
		elem.detachEvent("on" + eventType,func);
	}
}

// 透過加工
function filter(obj,rate) {
	obj.style.filter = "alpha(opacity=" + rate + ")";
	obj.style.mozOpacity = (rate / 100);
	obj.style.opacity = (rate / 100);
}

// ページロード時に呼出されます
httpXmlRequest();
addListener(window,"load",setListeners,false);


