var timerID;
var diary_http = null;
var stay_http = null;

function init(mode) {
	var d = document.getElementById("Player");
	var html;
	if ((navigator.userAgent.indexOf("IE") > -1) && (navigator.platform == "Win32")) {
		if (mode == 2) {
			html = 
				"<object id='MMPlayer1' width='100%' height='100%' classid='CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6' onclick='mmClick()'>";
		} else {
			html = 
				"<object id='MMPlayer1' width='640' height='428' classid='CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6' onclick='mmClick()'>";
		}
		html = html +
				"<param name='StretchToFit' value='True'>" +
				"<param name='AutoStart ' value='False'>" +
//				"<param name='ShowStatusBar' value='False'>" +
//				"<param name='ShowControls' value='False'>" +
				"<param name='EnableContextMenu' value='False'>";
		if (mode == 2) {
			html = html +"<param name='uiMode' value='none'>";
		}
		d.innerHTML = html + "</object>";
		if (volume != 0) {
			MMPlayer1.settings.volume = volume;
		}
		MMPlayer1.settings.setMode("loop", true);
		if (mode != 0) {
			if (mode == 2) {
				if (playmode == "shuffle") {
					MMPlayer1.settings.setMode("shuffle", true);
					playmode = "shuffle";
				}
			} else {
				MMPlayer1.settings.setMode("shuffle", true);
				playmode = "shuffle";
			}
		}
		MMPlayer1.URL = url;
		timerID = setTimeout('playmovie()', 500);
//		if (playmode == "loop") {
//			var media = MMPlayer1.currentPlaylist.item(index);
//			MMPlayer1.controls.playItem(media);
//		}
//		MMPlayer1.controls.play();
//		if (playmode == "shuffle") {
//			MMPlayer1.controls.next();
//		}
	} else{
		html = "<h3>高画質のムービーをご覧になるには Internet Explorer が必要です。</h3>";
		d.innerHTML = html;
		timerID = setTimeout('playmovie()', 500);
	}
}

function playmovie() {
	clearTimeout(timerID);

	if ((navigator.userAgent.indexOf("IE") > -1) && (navigator.platform == "Win32")) {
		if ((playmode == "loop") && ! load) {
			timerID = setTimeout('playmovie()', 50);
			return;
		}

		if (playmode == "loop") {
			index = next;
			var media = MMPlayer1.currentPlaylist.item(index);
			MMPlayer1.controls.playItem(media);
		}
		MMPlayer1.controls.play();
	} else {
		searchDiary();
		searchStay();
	}
}

function changeMovie(n) {
	if ((navigator.userAgent.indexOf("IE") > -1) && (navigator.platform == "Win32")) {
		MMPlayer1.controls.stop();
		next = n;
		if (playmode != "loop") {
			document.getElementsByName("playtype")[0].selectedIndex = 1;
			index = 0;
			playmode = "loop";
			MMPlayer1.settings.setMode("shuffle", false);
		}
		timerID = setTimeout('playmovie()', 500);
		window.scroll(0,60);
	} else {
		alert("高画質のムービーをご覧になるには Internet Explorer が必要です。");
	}
}

function changePlayMode(n) {
	if ((navigator.userAgent.indexOf("IE") > -1) && (navigator.platform == "Win32")) {
		MMPlayer1.controls.stop();
		if (n != 0) {
			MMPlayer1.settings.setMode("shuffle", true);
			playmode = "shuffle";
		} else {
			MMPlayer1.settings.setMode("shuffle", false);
			playmode = "loop";
			index = 0;
		}
		MMPlayer1.URL = url;
		timerID = setTimeout('playmovie()', 700);
//		if (playmode == "loop") {
//			var media = MMPlayer1.currentPlaylist.item(index);
//			MMPlayer1.controls.playItem(media);
//		}
//		MMPlayer1.controls.play();
//		if (n != 0) {
//			MMPlayer1.controls.next();
//		}
	} else {
		alert("高画質のムービーをご覧になるには Internet Explorer が必要です。");
	}
}

function openVideo(p, t) {
	if ((navigator.userAgent.indexOf("IE") > -1) && (navigator.platform == "Win32")) {
		var v = MMPlayer1.settings.volume;
		MMPlayer1.controls.stop();
		var w = screen.availWidth-8;
		var h = screen.height-36-(screen.height-screen.availHeight);
		var s = "top=0,left=0,width="+w+",height="+h+"resizable=no,toolbar=no,menubar=no,status=no";
		var o = window.open(p+"?"+url+"&"+playmode+"&"+t+"&"+index+"&"+v,"_blank",s);
	} else {
		alert("高画質のムービーをご覧になるには Internet Explorer が必要です。");
	}
}

function changePage(p) {
	var s = p+"?"+MMPlayer1.settings.volume;
	location.href = s;
}

function openHealWindow(p, t) {
	MMPlayer1.controls.stop();
	var w = 368;
	var h = 208;
	var s = "top=0,left=0,width="+w+",height="+h+"resizable=no,toolbar=no,menubar=no,status=no";
	var o = window.open(p+"?"+url+"&"+playmode+"&"+t+"&"+index,"_blank",s);
}

function openPage(s) {
	if (large) {
		if (opener.closed) {
			window.open(s, "");
			close();
		} else {
			opener.location.href = s;
			close();
		}
	} else {
		location.href = s;
	}
}

function searchDiary() {
	if (areakey == "") return;

//	var API_URL = "http://api.4travel.jp/Ver1/SearchAlbum.php";
	var API_URL = "http://www.healing-japan.tv/cgi-bin/trans_4travel.cgi";

	var query = API_URL + "?format=xml&areatype=shigun&areakey=" + areakey + "&max=5&order=travel_date&oc=sjis";

	var d = document.getElementById("Diary");
	d.innerHTML = "";

	try {
		diary_http = new ActiveXObject("Microsoft.XMLHTTP");
	} catch( ex ) {
		try {
			diary_http = new XMLHttpRequest();
		} catch( ex2 ) {
			diary_http = null;
		}
	}

	if( diary_http == null ) {
		return;
	}

	diary_http.onreadystatechange = searchDiaryResult;
	diary_http.open("GET", query, true);
	diary_http.send(null);
}

function searchDiaryResult() {
	var d = document.getElementById("Diary");

	if( diary_http.readyState == 4 ) {
		var str_html = "";
		if( diary_http.status == 200 ) {
			var res_xml = diary_http.responseXML;

			if( res_xml != null ) {
				try {

					var item_list = res_xml.getElementsByTagName("item");
					if (item_list.length != 0) {
						var item_node = item_list[0];
						var area = item_node.getElementsByTagName("area")[0].childNodes[0].nodeValue;

						str_html += "<table class=\"v30\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td>";
						str_html += "<table class=\"datatitle\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td>";
						str_html += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td>";
						str_html += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td>";
						str_html += "<h4 class=\"pagefont fontcolor1\">" + area + "の旅行記　<font size=\"-1\">（";
						str_html += "<a href=\"http://4travel.jp/\" target=\"_blank\" title=\"旅行のクチコミサイト フォー トラベル\">Web Services by 4travel.jp</a>）</font></h4></td>";
						str_html += "<td align=\"right\" valign=\"top\"></td></tr></table></td></tr></table></td></tr></table></td></tr></table>";

						str_html += "<table class=\"v20\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td>";
						str_html += "<p class=\"honbun\">　" + spotname + "周辺の旅行記（旅行ブログ）をご紹介しています。</p></td></tr></table>";
						str_html += "<table class=\"v10\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"95%\"><tr><td>";
						str_html += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"word-break:break-all;\">";

						for( var i = 0; i < item_list.length; i++ ) {
							var item_node = item_list[i];

							str_html += "<tr height=\"1\"><td class=\"bgcolor2\" height=\"1\" colspan=\"5\"></td></tr>";
							str_html += "<tr valign=\"middle\"><td class=\"bgcolor2\" width=\"10\"></td><td class=\"bgcolor5\" width=\"10\">";
							str_html += "<h5 class=\"homepage2\"><a href=\"" + item_node.getElementsByTagName("albumurl")[0].childNodes[0].nodeValue + "\" target=\"_blank\">";
							str_html += "<IMG src=\"" + item_node.getElementsByTagName("picture")[0].childNodes[0].nodeValue + "\" width=135 border=\"0\" alt=\"" +
										item_node.getElementsByTagName("albumtitle")[0].childNodes[0].nodeValue + "\"></a><br><br></h5></td>";
							str_html += "<td class=\"bgcolor2\" width=\"1\"></td><td class=\"bgcolor6\">";
							str_html += "<p class=\"homepage2\"><a href=\"" + item_node.getElementsByTagName("albumurl")[0].childNodes[0].nodeValue +
										"\" target=\"_blank\">" + item_node.getElementsByTagName("albumtitle")[0].childNodes[0].nodeValue + "</a></p>";
							str_html += "<p class=\"homepage2\"><strong>旅行時期</strong> " + item_node.getElementsByTagName("fromdate")[0].childNodes[0].nodeValue +
										"〜" + item_node.getElementsByTagName("todate")[0].childNodes[0].nodeValue + " | <span class=pts-f80>by " +
										item_node.getElementsByTagName("traveler")[0].childNodes[0].nodeValue + "さん</span></p>";
							var description = item_node.getElementsByTagName("description")[0].childNodes[0].nodeValue;
//							if (description.length > 100) description = description.substring(0, 100);
							description = trim(description, 100);
							str_html += "<p class=\"homepage2\">" + description + "…（<a href=\"" +
										item_node.getElementsByTagName("albumurl")[0].childNodes[0].nodeValue + "\" target=\"_blank\">もっと見る</a>）</p>";
							str_html += "<div id=maincontent><div class=clear id=mainwrap><div class=clear id=col3wrap><div id=maincol><div class=pts-mb30>" +
										"<ul class=listStripeL><div class=listStripeL-colR>";
							str_html += "</div></ul></div></div></div></div></div></td><td class=\"bgcolor2\" valign=\"top\" width=\"1\"></td></tr>";
						}

						str_html += "<tr height=\"1\"><td class=\"bgcolor2\" height=\"1\" colspan=\"5\"></td></tr></table></td></tr></table>";
					}

				} catch( ex ) {
					str_html += "<div class=\"error\">エラーが発生しました。</div>";
				}
			} else {
				str_html += "<div class=\"error\">エラーが発生しました。</div>";
			}
		} else {
			str_html += "<div class=\"error\">エラーが発生しました。</div>";
		}
		d.innerHTML = str_html;
		diary_http = null;
	}
}

function searchStay() {
	if (lat == -1) return;

//	var API_URL = "http://jws.jalan.net/APIAdvance/HotelSearch/V1/";
	var API_URL = "http://www.healing-japan.tv/cgi-bin/trans_jalan.cgi";
	var API_KEY = "tau11b0b392c71";
	var range = 50.0;

	var jPoint = ChangeLocationGlobalToJapan(lng, lat);
	var jx_ms = parseInt(jPoint.x * 3600 * 1000);
	var jy_ms = parseInt(jPoint.y * 3600 * 1000);

	var query = API_URL + "?xml_ptn=1&pict_size=3&key=" + API_KEY + "&x=" + jx_ms + "&y=" + jy_ms + "&range=" + range;

	var d = document.getElementById("Stay");
	d.innerHTML = "";

	try {
		stay_http = new ActiveXObject("Microsoft.XMLHTTP");
	} catch( ex ) {
		try {
			stay_http = new XMLHttpRequest();
		} catch( ex2 ) {
			stay_http = null;
		}
	}

	if( stay_http == null ) {
		return;
	}

	stay_http.onreadystatechange = searchStayResult;
	stay_http.open("GET", query, true);
	stay_http.send(null);
}

function searchStayResult() {
	var d = document.getElementById("Stay");

	if( stay_http.readyState == 4 ) {
		var str_html = "";
		if( stay_http.status == 200 ) {
			var res_xml = stay_http.responseXML;
			if( res_xml != null ) {
				try {

					var hotel_list = res_xml.getElementsByTagName("Hotel");
					if (hotel_list.length != 0) {
						str_html += "<table class=\"v30\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td>";
						str_html += "<table class=\"datatitle\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td>";
						str_html += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td>";
						str_html += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td>";
						str_html += "<h4 class=\"pagefont fontcolor1\">近隣の宿泊施設　<font size=\"-1\">（Powered by ";
						str_html += "<a href=\"http://jws.jalan.net/\" target=\"_blank\">じゃらん Web サービス</a></font><font size=\"-1\">）</font></h4>";
						str_html += "</td><td align=\"right\" valign=\"top\"><table class=\"midashilink2\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><td>";
						str_html += "<a href=\"./localmap/localmap-spot-index-" + spotindex + ".html\" target=\"_blank\">⇒ 周辺地図で確認</a></td></tr></table>";
						str_html += "</td></tr></table></td></tr></table></td></tr></table></td></tr></table>";

						str_html += "<table class=\"v20\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td>";
						str_html += "<p class=\"honbun\">　" + spotname + "周辺の宿泊施設をご紹介しています。</p></td></tr></table>";
						str_html += "<table class=\"v10\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"95%\"><tr><td>";
						str_html += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">";

						var count = 1;
						for( var i = 0; i < hotel_list.length && i < 10; i++ ) {
							try {
								var hotel_node = hotel_list[i];
								var hotelUrl = hotel_node.getElementsByTagName("HotelDetailURL")[0].childNodes[0].nodeValue;
								hotelUrl = hotelUrl.replace("?", "%3F");
								hotelUrl = hotelUrl.replace("&", "%26");
								hotelUrl = hotelUrl.replace("=", "%3D");
								var pictUrl = hotel_node.getElementsByTagName("PictureURL")[0].childNodes[0].nodeValue;
								var pictCap = hotel_node.getElementsByTagName("PictureCaption")[0].childNodes[0].nodeValue;
								var hotelName = hotel_node.getElementsByTagName("HotelName")[0].childNodes[0].nodeValue;
								var hotelAddr = hotel_node.getElementsByTagName("HotelAddress")[0].childNodes[0].nodeValue;
								var smplRate = hotel_node.getElementsByTagName("SampleRateFrom")[0].childNodes[0].nodeValue;
								var hotelCopy = hotel_node.getElementsByTagName("HotelCatchCopy")[0].childNodes[0].nodeValue;

								str_html += "<tr height=\"1\"><td class=\"bgcolor2\" height=\"1\" colspan=\"5\"></td></tr>";
								str_html += "<tr valign=\"middle\"><td class=\"bgcolor2\" width=\"10\"></td><td class=\"bgcolor5\" width=\"10\">";
								str_html += "<h5 class=\"homepage2\"><a href=\"http://ck.jp.ap.valuecommerce.com/servlet/referral?sid=2493422&pid=877486268&vc_url=" + hotelUrl +
											"%26vos%3Dnjalvccp99000\" target=\"_blank\">" +
											"<img src=\"http://ad.jp.ap.valuecommerce.com/servlet/gifbanner?sid=2493422&pid=877486268\" height=\"1\" width=\"1\" Border=\"0\">" +
											"<img src=\"" + pictUrl + "\" width=135 border=0 alt=\"" + pictCap + "\"><br></a><br></h5></td>";
								str_html += "<td class=\"bgcolor2\" width=\"1\"></td><td class=\"bgcolor6\">";
								str_html += "<p class=\"homepage2\">" + count + 
											". <A class=\"s16_00 fb\" href=\"http://ck.jp.ap.valuecommerce.com/servlet/referral?sid=2493422&pid=877486268&vc_url=" +
											hotelUrl + "%26vos%3Dnjalvccp99000\" target=\"_blank\">" + 
											"<img src=\"http://ad.jp.ap.valuecommerce.com/servlet/gifbanner?sid=2493422&pid=877486268\" height=\"1\" width=\"1\" Border=\"0\">" +
											hotelName + "</A></p>";
								str_html += "<p class=\"homepage2\">" + hotelAddr + "</p>";
								str_html += "<p class=\"homepage2\">最安料金：一泊" + smplRate + "円</p>";
								str_html += "<p class=\"homepage2\">" + hotelCopy + "</p>";
								str_html += "</td><td class=\"bgcolor2\" valign=\"top\" width=\"1\"></td></tr>";
								count ++;
							} catch( ex ) {}
						}

						str_html += "<tr height=\"1\"><td class=\"bgcolor2\" height=\"1\" colspan=\"5\"></td></tr></table></td></tr></table>";
					}

				} catch( ex ) {
				alert(ex);
					str_html += "<div class=\"error\">エラーが発生しました。</div>";
				}
			} else {
				str_html += "<div class=\"error\">エラーが発生しました。</div>";
			}
		} else {
			str_html += "<div class=\"error\">エラーが発生しました。</div>";
		}
		d.innerHTML = str_html;
		stay_http = null;
	}
}

function Point(_x, _y) {
	Point.prototype.x = _x;
	Point.prototype.y = _y;
}

function ChangeLocationJapanToGlobal(jx, jy) {
	var wy = jy - jy * 0.00010695 + jx * 0.000017464 + 0.0046017;
	var wx = jx - jy * 0.000046038 - jx * 0.000083043 + 0.010040;
	return new Point(wx, wy);
}

function ChangeLocationGlobalToJapan(wx, wy) {
	var jy = wy * 1.000106961 - wx * 0.000017467 - 0.004602017;
	var jx = wx * 1.000083049 + wy * 0.000046047 - 0.010041046;
	return new Point(jx, jy);
}

function trim(str, size) {
	if(str.length > size){
		var cutstring = str.substring(0, size);
		var byte = getByteCount(cutstring);
		var tmp = "";
		if (byte < size * 2) {
			for(k=0; k < (size * 2 - byte) * 2; k++){
				tmp = str.substring(0, size + k);
				if (getByteCount(tmp) >= size * 2) {
					break;
				}
			}
		}
		if(tmp){
			return tmp;
		} else {
			return str.substring(0, size);
		}
	} else {
		return str;
	}
}

function checkIsZenkaku(value) {
	for (var i = 0; i < value.length; ++i) {
		var c = value.charCodeAt(i);
		if (c < 256 || (c >= 0xff61 && c <= 0xff9f)) {
			return false;
		}
	}
	return true;
}

function getByteCount(value) {
	var count = 0;
	for ( var i = 0; i < value.length; ++i ) {
		var sub = value.substring(i, i + 1);
		if( checkIsZenkaku(sub) ){
			count += 2;
		} else {
			count += 1;
		}
	}
	return count;
}
