var xmldoc;
var unitText = '';

function loadDiary() {
	var xml = makeXml(currentYear, currentMonth);

	var myAjax = new Ajax.Request(
		xml, {
			method: 'get',
			requestHeaders: ['If-Modified-Since','Wed, 15 Nov 1995 00:00:00 GMT'],
			onComplete: viewDiary,
			onFailure : function(error) {
				alert(error.responseText);
			}
		});

	unitText = '';
	document.getElementById("diary").innerHTML = '<div class="reading"><em>データ読み込み中...</em></div><table class="bottom"><tr><td></td></tr></table>';
}

function loadAffiliate() {
	new Ajax.Request(
		'/kanpachi/affiliate/amazon.xml', {
			method: 'get',
			requestHeaders: ['If-Modified-Since','Wed, 15 Nov 1995 00:00:00 GMT'],
			onComplete: viewAffiliate,
			onFailure : function(error) {
				alert(error.responseText);
			}
		});
}

function viewDiary(xml) {
	xmldoc = xml.responseXML.documentElement;
	var day = getNode("day", xmldoc);
	var cnt;
	var error = getSimpleValue("error", xmldoc);

	if	(error != "") {
		document.getElementById("diary").innerHTML = error;
		return;
	}

	// 状態の初期化
	viewTide = new Array();

	for	(cnt = 0; cnt < day.length; cnt++) {
		viewTide[cnt] = true;
	}


	// 表示
	makeFrame();
	attachDocumentAll();
	makeTab();
	loadAffiliate();

	if	(jump != undefined) {
		// 指定位置までスクロール
		Element.scrollTo(jump);
	}
}

function makeFrame() {
	var day = getNode("day", xmldoc);
	var cnt, point;
	var text = "";

	for	(cnt = 0; cnt < day.length; cnt++) {
		var attr = getAttributes(day[cnt]);
		var count = attr["-points"] - 0;
		text += "<span id=\"name_" + attr['-date'] + "\"/>";
		text += "<table class=\"dayframe\"><tr><td>";
		text += "<table><tr valign=\"top\"><td id=\"" + attr["-date"] + "\" class=\"dateframe\"></td><td class=\"header\">";
		for	(point = 0; point < count; point++) {
			text += "<span id=\"" + attr["-date"] + (point + 1) + "\" class=\"pointframe\"></span>";
		}
		text += "</td></tr></table></td></tr></table><table class=\"bottom\"><tr><td></td></tr></table>\n";
	}
	document.getElementById("diary").innerHTML = text;
}

function attachDocumentAll() {
	var day = getNode("day", xmldoc);
	var cnt, point;

	for	(cnt = 0; cnt < day.length; cnt++) {
		var attr = getAttributes(day[cnt]);
		var count = attr["-points"] - 0;
		var date = attr["-date"];

		// 
		attachHeader(date);

		for	(point = 0; point < count; point++) {
			attachDocument(date, point + 1);
		}
	}
}

function attachHeader(yyyymmdd) {
	var day = getNode("day", xmldoc);
	var cnt;
	var text = "";

	for	(cnt = 0; cnt < day.length; cnt++) {
		var attr = getAttributes(day[cnt]);
		var date = attr["-date"];
		var week = attr["-week"];
		var tide = getNode("tide", day[cnt]);
		var photo = getNode("photo", day[cnt]);
		var cnt;

		if	(date != yyyymmdd) {
			continue;
		}

		// 西暦
		text += "<div class=\"date\">" + date.substring(0, 4) + "/" + date.substring(4, 6) + "/" + date.substring(6, 8) + " (";

		// クッキーの設定
		setCookie('year', date.substring(0, 4));
		setCookie('month', date.substring(4, 6));

		// 曜日
		switch	(week) {
			case "日": text += "<span class=\"sunday\">"; break;
			case "土": text += "<span class=\"saturday\">"; break;
			default: text += "<span class=\"weekday\">";
		}
		text += week + "</span>)</div>";

		if	(tide.length != 0) {
			// タイドグラフ
			text += "<div class=\"tide\">";
			text += "<span class=\"tideframe\">" + getAttributes(tide[0])["-turn"] + "潮</span><br/>";
			var tidedetail = getNode("eorf", tide[0]);
			for	(cnt = 0; cnt < tidedetail.length; cnt++) {
				var tideattr = getAttributes(tidedetail[cnt]);
				text += "<span class=\"tidetype\">" + tideattr["-type"] + "潮</span>";
				text += "<span class=\"tidetime\">" + tideattr["-time"] + "</span>";
				text += "<span class=\"tideheight\">" + tideattr["-height"] + " cm</span><br/>";
			}
			text += "</div>";
		}

		if	(photo.length != 0) {
			// 写真
			text += "<div class=\"photoframe\">";
			for	(cnt = 0; cnt < photo.length; cnt++) {
				var photoattr = getAttributes(photo[cnt]);
				text += "<img class=\"photo\" width=\"128\" height=\"96\" src=\"../image/" + date.substring(0, 4) + "/" + photoattr["-thumb"] + "\"";
				if	(photoattr["-img"] != undefined) {
					var url = 'src=/kanpachi/image/' + date.substring(0, 4) + '/' + photoattr['-img'];
					if	(photoattr["-alt"] != undefined) {
						url += '&title=' + photoattr["-alt"] + '&desc=' + photoattr["-alt"];
					}
					text += " onclick=\"return openSubImage('" + url +"', '528', '500')\"";
				}
				if	(photoattr["-alt"] != undefined) {
					text += " alt=\"" + photoattr["-alt"] + "\"><br/>" + photoattr["-alt"];
				}
				else {
					text += "/>";
				}
				if	(photoattr["-img"] != undefined) text += "</a>";
				if	(cnt + 1 != photo.length) text += "";
			}
			text += "</div>";
		}

		document.getElementById(date).innerHTML = text;
		return;
	}
}

function attachDocument(viewdate, viewpoint) {
	var day = getNode("day", xmldoc);
	var cnt;
	var text = "";

	for	(cnt = 0; cnt < day.length; cnt++) {
		var attr = getAttributes(day[cnt]);
		var date = attr["-date"];
		var key = viewdate + viewpoint;

		if	(date != viewdate) {
			continue;
		}
		var pointNodes = getNode("point", day[cnt]);
		var point = pointNodes[viewpoint - 1];
		var pointAttr = getAttributes(point);
		var time = getNode("time", point);

		// イメージ
		var weatherImage = Array();
		weatherImage["晴"] = "../image/sun.gif";
		weatherImage["曇"] = "../image/cloud.gif";
		weatherImage["雨"] = "../image/rain.gif";
		weatherImage["雪"] = "../image/snow.gif";
		weatherImage["霧"] = "../image/mist.gif";
		var windImage = Array();
		windImage["北"] = "../image/north.gif";
		var waveImage = Array();
		waveImage["高"] = "../image/high.gif";
		var colorImage = Array();
		colorImage["澄"] = "../image/clear.gif";

		text += "<table class=\"part\"><tr><td valign=\"middle\" width=\"14px\">" + makeToggleSpan(key + "main", true) + "</td><td>";
		text += "<span class=\"point\">" + pointAttr["-name"] + "</span>";
//		text += "<span class=\"city\">(" + pointAttr["-city"] + ")</span>";
		if	(pointAttr["-map"] != undefined) {
			text += "<span class=\"map\" onclick=\"openGoogleMap(" + pointAttr["-map"] + ", 408, 496)\"><img src=\"../image/map.gif\" alt=\"地図\"></span>";
		}
		if	(time.length != 0) {
			var timeAttr = getAttributes(time[0]);
			text += "<span class=\"time\"> - " + timeAttr["-start"] + "～" + timeAttr["-end"] + "</span>";
		}

		if	(getNode("condition", point).length > 0) {
			var condition = getNode("condition", point)[0];
			var weather = getNode("weather", condition);
			var wind = getNode("wind", condition);
			var wave = getNode("wave", condition);
			text += "<span class=\"weather\">天候：";
			for	(cnt = 0; cnt < weather.length; cnt++) {
				var weatherAttr = getAttributes(weather[cnt]);
				text += "<img style=\"vertical-align:middle\" src=\"" + weatherImage[weatherAttr["-sky"]] + "\"/>";
				switch	(weatherAttr["-link"]) {
					case "時": text += "<img style=\"vertical-align:middle\" src=\"../image/eachtime.gif\" alt=\"時々\">"; break;
					case "後": text += "<img style=\"vertical-align:middle\" src=\"../image/aftertime.gif\" alt=\"後\">"; break;
				}
			}

			if	(wind.length > 0) {
				text += "</span>|<span class=\"wind\">風：";
				for	(cnt = 0; cnt < wind.length; cnt++) {
					var windAttr = getAttributes(wind[cnt]);
	//				text += "<img style=\"vertical-align:middle\" src=\"" + windImage[windAttr["-dir"]] + "\"/>";
					text += windAttr["-dir"];
					if	(cnt + 1 != wind.length) {
						text += "<span style=\"font-size:8px\">のち</span>";
					}
				}
			}

			if	(wave.length > 0) {
				text += "</span>|<span class=\"wave\">波：";
				for	(cnt = 0; cnt < wave.length; cnt++) {
					var waveAttr = getAttributes(wave[cnt]);
					text += waveAttr["-height"];
	//				text += waveAttr["-color"];
					if	(cnt + 1 != wave.length) {
						text += "<span style=\"font-size:8px\">のち</span>";
					}
				}
			}

			text += "</span>";
		}
		text += "</td></tr></table>";
		text += "<div id=\"" + key + "main\">";

		var tackle = getNode("tackle", point);

		if	(tackle.length > 0) {
			text += "<table class=\"tackletitle\">";
			text += "<tr><td valign=\"top\" rowspan=\"2\">" + makeToggleSpan(key + "tackle", true) + "</td><td>タックル</td>";
			text += "<tr><td class=\"tackleframe\" id=\"" + key + "tackle\">";

			for	(cnt = 0; cnt < tackle.length; cnt++) {
				text += makeTackle(tackle[cnt]) + "<br/>";
			}
			text += "</td></tr></table>";
		}

		var get = getNode("get", point);

		if	(get.length != 0) {
			var fish = getNode("fish", get[0]);

			text += "<table class=\"gettitle\">";
			text += "<tr><td valign=\"top\" rowspan=\"2\">" + makeToggleSpan(key + "get", true) + "</td><td>獲得魚</td>";
			text += "<tr><td class=\"getframe\" id=\"" + key + "get\">";
			text += "<table cellpadding=\"0\" cellspacing=\"0\">";

			for	(cnt = 0; cnt < fish.length; cnt++) {
				var fishAttr = getAttributes(fish[cnt]);
				text += "<tr";
				if	(fishAttr["-record"] != null && fishAttr["-record"] == "yes") {
					text += " class=\"record\"";
				}
				text += "><td class=\"fishname\">" + fishAttr["-name"];
				text += "</td>";
				text += "<td class=\"fishsize\">";
				
				if	(fishAttr["-max"] != null) {
					if	(fishAttr["-min"] != null) {
						text += fishAttr["-min"] + "～" + fishAttr["-max"] + " cm";
					}
					else {
						text += fishAttr["-max"] + " cm";
					}
				}

				text += "</td><td class=\"fishcount\">";
				if	(fishAttr["-count"] != null) {
					text += fishAttr["-count"] + " 匹";
					if	(fishAttr["-release"] != null) {
						text += "</td><td class=\"fishrelease\">（内 " + fishAttr["-release"] + " 匹リリース）";
					}
				}
				text += "</td></tr>";
			}
			text += "</table></td></tr></table>";
		}

		var tmp = getSimpleValue("text", point);
		tmp = tmp.replace(/\t/g, "");
		tmp = tmp.replace(/\[/g, "<");
		tmp = tmp.replace(/\]/g, ">");
		text += tmp;
		unitText += tmp;
		text += "</div>";

		document.getElementById(key).innerHTML = text;
//		if	($(key + "tackle")) Element.hide(key + "tackle");
		return;
	}
}

function makeToggleSpan(key, open) {
	return "<span class=\"openclose\" onclick=\"return viewToggle('" + key + "')\"><img class=\"togglebutton\"src=\"" + getOpenCloseImage(open) + "\" id=\"" + (key + "openclose") + "\"/></span>";
}

function viewToggle(id) {
	Element.toggle(id);
	$(id + "openclose").src = getOpenCloseImage(Element.visible(id));
	return false;
}

function getOpenCloseImage(open) {
	return open ? "closeIcon.gif" : "openIcon.gif";
}

function makeTackle(tackle) {
	var rod = getNode("rod", tackle);
	var reel = getNode("reel", tackle);
	var line = getNode("line", tackle);
	var bait = getNode("bait", tackle);
	var target = getNode("target", tackle);
	var text = "";
	var view = false;
	var cnt;

	if	(rod.length > 0) {
		var attribute = getAttributes(rod[0]);
		text += attribute["-name"];// + makeSet(attribute["-set"]);
		view = true;
	}

	if	(reel.length > 0) {
		var attribute = getAttributes(reel[0]);
		text += (view ? "＋" : "") + attribute["-name"];// + makeSet(attribute["-set"]);
		view = true;
	}

	for	(cnt = 0; cnt < line.length; cnt++) {
		var attribute = getAttributes(line[cnt]);
		text += (cnt == 0 ? (view ? "＋" : "") : "／") + attribute["-type"] + " " + attribute["-weight"] + " 号 (" + attribute["-length"] + "m)";
		view = true;
	}

	for	(cnt = 0; cnt < bait.length; cnt++) {
		var attribute = getAttributes(bait[cnt]);
		text += (cnt == 0 ? (view ? "＋" : "") : "／") + attribute["-name"];
		view = true;
	}

	for	(cnt = 0; cnt < target.length; cnt++) {
		var attribute = getAttributes(target[cnt]);
		text += (cnt == 0 ? (view ? " → " : "") : "／") + attribute["-name"];
		view = true;
	}

	return text;
}

function makeSet(num) {
	return num > 1 ? "<span class=\"set\">×" + num + "</span>"  : "";
}

function isExistDiary(year, month) {
	if	(year < minYear) return false;
	if	(year > maxYear) return false;
	if	(exist[String(year)] == undefined) return false;
	return	exist[String(year)].charAt(month-1) == 'o' ? true : false;
}

function makeXml(year, month) {
	return String(year).zeroFormat(4) + String(month).zeroFormat(2) + ".xml";
}

function makeTab() {
	var text = '<tr><td class="tabyear"></td>';
	var year;
	var month;
	var cnt;
	var nextYear = false;

endofprev:
	for	(year = currentYear -1; year >= minYear; year--) {
		for	(month = 12; month > 0; month--) {
			if	(isExistDiary(year, month)) {
				text = '<tr><td class="tabyear">';
				text += "<a style=\"text-decoration:none;\" href=\"#\" onclick=\"return onChangeDiary('" + year + "', '" + month + "')\">";
				text += year + ' 年</a></td>';
				break endofprev;
			}
		}
	}

	for	(cnt = 0; cnt < 12; cnt++) {
		text += '<td class="tabseparator"></td>';
		text += '<td ';
		if	(currentMonth == cnt + 1) {
			text += 'class="tabcurrent">' + (cnt + 1) + '月';
		}
		else if (isExistDiary(currentYear, cnt + 1)) {
			text += 'class="tabnormal">';
			text += "<a href=\"#\" onclick=\"return onChangeDiary('" + currentYear + "', '" + (cnt + 1) + "')\">";
			text += (cnt + 1) + '月</a>';
		}
		else {
			text += 'class="tabgray">' + (cnt + 1) + '月';
		}
		text += '</td>';
	}

	text += '<td class="tabseparator"></td>';

endofnext:
	for	(year = currentYear + 1; year <= maxYear; year++) {
		for	(month = 1; month < 13; month++) {
			if	(isExistDiary(year, month)) {
				text += '<td class="tabyear">';
				text += "<a style=\"text-decoration:none;\" href=\"#\" onclick=\"return onChangeDiary('" + year + "', '" + month + "')\">";
				text += year + ' 年</a></td>';
				nextYear = true;
				break endofnext;
			}
		}
	}

	if	(!nextYear) {
		text += '<td class="tabyear"></td>';
	}

	text = '<table border="0" cellpadding="0" cellspacing="0">' + text + '</tr></table>';

	document.getElementById("tab").innerHTML = text;
}

function onChangeDiary(year, month) {
	currentYear = year - 0;
	currentMonth = month - 0;
	loadDiary();
	return false;
}

function setCookie(key, val){
	document.cookie = key + "=" + escape(val) + ";";
}

function getCookie(key) {
	var cookies = document.cookie.split(";");
	var cnt;

	for	(cnt = 0; cnt < cookies.length; cnt++) {
		cookies[cnt] = cookies[cnt].replace(/\b|\s/g, "");
		var keyvalue = cookies[cnt].split("=");
		if	(key == keyvalue[0]) return keyvalue[1];
	}
}

function viewAffiliate(xml) {
	var doc = xml.responseXML.documentElement;
	var item = getNode("item", doc);
	var cnt, index;
	var text = '';
	var links = new Array();

	for	(cnt = 0; cnt < item.length; cnt++) {
		var month = getSimpleValue('month', item[cnt]);
		var group = month.split(",");
		for	(index = 0; index < group.length; index++) {
			var range = group[index].split("-");
			if	(currentMonth - 0 >= range[0] && currentMonth - 0 <= range[1]) {
				links.push(getSimpleValue('link', item[cnt]));
			}
		}
	}

	text = links[Math.floor(Math.random() * links.length)];
	document.getElementById("affiliate").innerHTML = text;
}
