//	gmap.js (+ gmap.html + gmap/search.gif + gmap/gguy.gif)
//	Copyright 2008 CMONOS Co.Ltd.
//	Version: 1.1
//	License: MIT License 
//	※ Google Maps API および各種マーカー画像に関する全ての権利は米 Google, Inc が保有しています。
//
//	URI: http://cmonos.jp/
//	Last Modified: 2008-12-09
//	Author: CMONOS Co.Ltd.
//
//	【ストリートビュー関連コードのベースとしたデモ】
//	Street View Data Querying (Example by Tom Manshreck)
//	http://gmaps-samples.googlecode.com/svn/trunk/streetview/streetview_layer.html
//
//	【使い方】
//	次のような <iframe> タグで、地図を埋め込みます。
//
//	<iframe class="gmap-frame" id="gmap-canvas" src="./gmap.html?key=API_KEY&om=1&z=4&c=36.315125,137.504883"  width="500" height="400" scrolling="no" marginwidth="0" marginheight="0" frameborder="0">
//	<a href="./gmap.html?key=API_KEY&om=1&z=4&c=36.315125,137.504883" target="_blank">新しいウィンドウで地図を開く</a>
//	</iframe>
//
//	【地図呼び出しオプション】
//	key		GoogleMaps API キー(http://code.google.com/apis/maps/signup.html で取得します)
//	om		1=概観地図(右下に表示される小さな四角い概観地図)を表示する場合
//	z		拡大倍率(0-17)
//	t		地図のタイプ(k=衛星写真/h=地図と衛星の合成/設定なし=通常の地図)
//	c		中心座標の緯度,中心座標の経度
//	m		中心座標コメント
//	mw		中心座標コメントを表示する情報ウィンドウの幅
//	s		1=地図検索欄を表示する
//	sv		1=ストリートビューを表示する
//	url		kml ファイルの URL
//	fit		1=kml ファイルに合わせて中心座標と拡大倍率を調整する
//	d		kml ファイルに記述された線分の距離を表示するかどうか
//			(1=始点から終点までの総延長を表示する/2=総延長に加えて始点と終点の直線距離を表示する)
//	width	地図の幅(ピクセル)
//	height	地図の高さ(ピクセル)
//	tr		情報ウィンドウ内リンクのターゲット p=_parent/s=_self/b=_blank/t=_top
//	i		1=index 用
//	r		1=地図を移動または拡大縮小する度に kml を再読み込みする(必ず fit を無効化します)
//	sf		kml 再検索フォームのID
//
//	【以下は呼びだし元ページのフォームに地図の情報を書き込む場合に使用するオプションです】
//	z_field		表示中の地図の拡大倍率を収める入力欄のID
//	t_field		表示中の地図の地図のタイプを収める入力欄のID
//	c_field		表示中の地図の中心座標を収める入力欄のID
//	m_field		表示中の地図の中心座標コメントが収められている入力欄のID
//	fit_field	表示中の地図を KML ファイルにあわせて調整するかどうかの設定が収められているチェックボックスのID
//	addr_field	地図検索欄に読み込む住所が収められている住所入力欄のIDのカンマ区切りリスト(都道府県,市区群,番地,ビル)

//	外部ドメインからのアクセスを許可する場合は下記を false にします。
var domain_check = true;

//	デフォルトのマーカーアイコン
function getGIcon() {
	var g_icon = new GIcon();
	g_icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
	g_icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	g_icon.iconSize = new GSize(12, 20);
	g_icon.shadowSize = new GSize(22, 20);
	g_icon.iconAnchor = new GPoint(6, 20);
	g_icon.infoWindowAnchor = new GPoint(5, 1);
	return g_icon;
}

//	定規アイコン
function getMeasureIcon() {
	var m_icon = new GIcon();
	m_icon.image = "http://maps.google.com/mapfiles/kml/pal5/icon5.png";
	m_icon.shadow = "http://maps.google.com/mapfiles/kml/pal5/icon5s.png";
	m_icon.iconSize = new GSize(32,32);
	m_icon.shadowSize = new GSize(59,32);
	m_icon.iconAnchor = new GPoint(16,16);
	m_icon.infoWindowAnchor = new GPoint(16,1);
	return m_icon;
}

//	選択マーカー画像
function toggleGIcon(this_marker,is_selected) {
	this_marker.setImage((is_selected) ? "http://labs.google.com/ridefinder/images/mm_20_orange.png" : "http://labs.google.com/ridefinder/images/mm_20_red.png");
}

//	ストリートビューマン
function getGuyIcon() {
	var guy_icon = new GIcon(G_DEFAULT_ICON);
	guy_icon.image = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-0.png";
	guy_icon.transparent = "http://maps.google.com/intl/en_us/mapfiles/cb/man-pick.png";
	guy_icon.imageMap = [
		26,13, 30,14, 32,28, 27,28, 28,36, 18,35, 18,27, 16,26,
		16,20, 16,14, 19,13, 22,8
	];
	guy_icon.iconSize = new GSize(49, 52);
	guy_icon.iconAnchor = new GPoint(25, 35);
	guy_icon.infoWindowAnchor = new GPoint(25, 5);
	return guy_icon;
}

var q = urlDecode(self.document.location.search);
var api_enabled = false;
var map;
var map_center;
var center_marker = null;
var geocoder_client = null;
var measure_icon = null;
var default_icon = null;
var streetview_client = null;
var streetview_overlay = null;
var streetview_man = null;
var streetview_man_location = null;
var panorama = null;
var kml_overlay = null;
var _caller = (parent && parent != self) ? parent : (opener) ? opener : self; 
if (q["key"] != null && q["key"] != "") {
	if (!domain_check || _caller.document.domain == self.document.domain) api_enabled = true;
	if ((navigator.userAgent.match(/MSIE\s*(\d+\.\d+)/) && parseFloat(RegExp.$1) < 5.5) || (navigator.userAgent.match(/Safari\/(\d+)/) && parseFloat(RegExp.$1) < 400)) api_enabled = false;
	if (api_enabled) self.document.write('<script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=' + q["key"] + '" type="text/javascript"></script>');
}
var z_field = null;
var t_field = null;
var c_field = null;
var m_field = null;
var fit_field = null;
var addr_field_ids = null;
var mw = (q["mw"] != null && q["mw"] > 100) ? q["mw"] : 280;
if (q["z_field"] != null && q["z_field"] != "" && _caller.document.getElementById(q["z_field"])) z_field = _caller.document.getElementById(q["z_field"]);
if (q["t_field"] != null && q["t_field"] != "" && _caller.document.getElementById(q["t_field"])) t_field = _caller.document.getElementById(q["t_field"]);
if (q["c_field"] != null && q["c_field"] != "" && _caller.document.getElementById(q["c_field"])) c_field = _caller.document.getElementById(q["c_field"]);
if (q["m_field"] != null && q["m_field"] != "" && _caller.document.getElementById(q["m_field"])) m_field = _caller.document.getElementById(q["m_field"]);
if (q["fit_field"] != null && q["fit_field"] != "" && _caller.document.getElementById(q["fit_field"])) fit_field = _caller.document.getElementById(q["fit_field"]);
if (q["addr_field"] != null && q["addr_field"] != "") addr_field_ids = q["addr_field"].split(/,/);
var field_enabled = (z_field != null || t_field != null || c_field != null || m_field != null || fit_field != null) ? true : false;
var kml_url = null;
var base_url = null;
var search_form = null;
if (q["r"] != null && q["r"] == 1) q["fit"] = null;
function load() {
	if (api_enabled && GBrowserIsCompatible()) {
		var z = 4;
		var center = new Array(36.315125,137.504883);
		var w;
		var h;
		if (q["width"] != null && q["width"] != "" && !isNaN(q["width"]) && q["height"] != null && q["height"] != "" && !isNaN(q["height"])) {
			w = parseInt(q["width"]);
			h = parseInt(q["height"]);
		} else {
			w = ((self.innerWidth) ? self.innerWidth : ((document.compatMode != null && document.compatMode != "BackCompat") ? self.document.documentElement.clientWidth : self.document.body.clientWidth));
			h = ((self.innerHeight) ? self.innerHeight : ((document.compatMode != null && document.compatMode != "BackCompat") ? self.document.documentElement.clientHeight : self.document.body.clientHeight))
			self.onresize = function () { fitWindow(); };
		}
		map = new GMap2(self.document.getElementById("map"),{ size : new GSize(w, h) });
		if (q["c"] != null && q["c"] != "") center = q["c"].split(/,/);
		if (q["z"] != null && q["z"] != "" && !isNaN(q["z"])) z = parseInt(q["z"]);
		map_center = new GLatLng(center[0],center[1]);
		map.setCenter(map_center, z);
		if (h > 320) {
			map.addControl( new GLargeMapControl() );
		} else {
			map.addControl( new GSmallMapControl() );
		}
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl());
		if (q["om"] != null && q["om"] == 1) map.addControl(new GOverviewMapControl());
		if (q["t"] != null && q["t"] != "") map.setMapType((q["t"] == "k") ? G_SATELLITE_MAP : (q["t"] == "h") ? G_HYBRID_MAP : G_NORMAL_MAP);
		if ((m_field != null) || (q["m"] != null && q["m"] != "")) {
			var center_icon = getGIcon();
			if (m_field != null) {
				map.enableDoubleClickZoom();
				center_marker = new GMarker(
					map_center,
					{
						icon	:	center_icon,
						title	:	'この地図の中心'
					}
				);
				GEvent.addListener(
					center_marker,
					"click",
					function () {
						map.disableDragging();
						map_center = map.getCenter();
						openCenterInfoWindow();
					}
				);
				GEvent.addListener(
					center_marker,
					"infowindowclose",
					function () {
						map.enableDragging();
						map.panTo(map_center);
					}
				);
				GEvent.addListener(
					map,
					"drag",
					function () {
						center_marker.setPoint(map.getCenter());
					}
				);
			} else {
				center_marker = new GMarker(map_center,{icon : center_icon});
				GEvent.addListener(
					center_marker,
					"click",
					function () {
						center_marker.openInfoWindowHtml('<div style="font-size: 14px">' + q["m"] + '</div>',{ maxWidth : mw })
					}
				);
			}
			map.addOverlay(center_marker);
		}
		if (q["url"] != null && q["url"] != "") {
			kml_url = q["url"];
			base_url = q["url"].replace(/\?.*$/,'');
		} else if (q["sf"] != null && q["sf"] != "" && _caller.document.getElementById(q["sf"])) {
			search_form = _caller.document.getElementById(q["sf"]);
			base_url = search_form.action;
			kml_url = base_url + '?' + urlEncode(getHashFromForm(search_form))
		}
		if (kml_url != null) {
			if (q["i"] == null || q["i"] != 1) {
				if (q["r"] != null && q["r"] == 1) {
					refreshKml();
				} else {
					kml_overlay = new GGeoXml(kml_url);
					map.addOverlay(kml_overlay);
				}
				if (q["fit"] != null && q["fit"] == 1) {
					kml_overlay.gotoDefaultViewport(map);
					saveMap();
				}
			}
			if ((q["i"] != null && q["i"] == 1) || (q["d"] != null && q["d"] >= 1)) {
				var request = GXmlHttp.create();
				request.open("GET", kml_url, true);
				request.onreadystatechange = function () {
					if (request.readyState == 4) {
						//var kml = request.responseXML;
						var kml = GXml.parse(request.responseText);
						if ((q["i"] != null && q["i"] == 1 && q["fit"] != null && q["fit"] == 1) || (q["d"] != null && q["d"] >= 1)) {
							var coordinates = kml.documentElement.getElementsByTagName("coordinates");
							var n;
							var e;
							var s;
							var w;
							for (var i=0; i<coordinates.length; i++) {
								var points = GXml.value(coordinates[i]).replace(/^\s+/,'').replace(/\s+$/,'').split(/\s+/);
								var len = points.length;
								var center_n = Math.floor(len/2);
								var center_point = null;
								var start_point = null;
								var prev_point = null;
								var distance = 0;
								for (var j=0; j<len; j++) {
									var lnglat = points[j].split(/,/);
									if (lnglat[0] != null && lnglat[1] != null) {
										var lng = parseFloat(lnglat[0]);
										var lat = parseFloat(lnglat[1]);
										if (q["i"] != null && q["i"] == 1 && q["fit"] != null && q["fit"] == 1) {
											if (n == null || lat > n) n = lat;
											if (s == null || lat < s) s = lat;
											if (e == null || lng > e) e = lng;
											if (w == null || lng < w) w = lng;
										}
										if (q["d"] != null && q["d"] >= 1) {
											var here = new GLatLng(lat,lng);
											if (start_point == null) start_point = here;
											if (j == center_n && len > 1) center_point = here;
											if (prev_point != null) distance += here.distanceFrom(prev_point);
											prev_point = here;
										}
									}
								}
								if (q["d"] != null && q["d"] >= 1 && center_point != null) {
									var distance_info = formattedDistance(distance);
									if (len == 2) {
										center_point = new GLatLng(parseFloat((center_point.lat() + start_point.lat()) / 2),parseFloat((center_point.lng() + start_point.lng()) / 2));
									} else if (q["d"] == 2) {
										var shortest = prev_point.distanceFrom(start_point);
										if (shortest != distance) distance_info += '<div style="font-size: 12px">(直線距離:' + formattedDistance(shortest) + ')</div>';
									}
									if (measure_icon == null) measure_icon = getMeasureIcon();
									map.addOverlay(makeMarker(center_point,measure_icon,distance_info));
								}
							}
						}
						if (q["i"] != null && q["i"] == 1) {
							var placemarks = kml.documentElement.getElementsByTagName("Placemark");
							for (var i=0; i<placemarks.length; i++) {
								var placemark_name = 'error!';
								var placemark_description = 'error!';
								var placemark_link = null;
								var placemark_point = map.getCenter();
								var placemarker;
								for (var j=0; j<placemarks[i].childNodes.length; j++) {
									if (placemarks[i].childNodes.item(j).nodeName.toLowerCase() == "name") {
										placemark_name = placemarks[i].childNodes.item(j).firstChild.nodeValue;
									} else if (placemarks[i].childNodes.item(j).nodeName.toLowerCase() == "description") {
										placemark_description = placemarks[i].childNodes.item(j).firstChild.nodeValue;
									} else if (placemarks[i].childNodes.item(j).nodeName.toLowerCase() == "atom:link") {
										placemark_link = placemarks[i].childNodes.item(j).getAttribute("href");
									} else if (placemarks[i].childNodes.item(j).nodeName.toLowerCase() == "point") {
										for (var k=0; k<placemarks[i].childNodes.item(j).childNodes.length; k++) {
											if (placemarks[i].childNodes.item(j).childNodes.item(k).nodeName.toLowerCase() == "coordinates") {
												var placemark_lnglat = placemarks[i].childNodes.item(j).childNodes.item(k).firstChild.nodeValue.split(/,/);
												placemark_point = new GLatLng(parseFloat(placemark_lnglat[1]),parseFloat(placemark_lnglat[0]))
											}
										}
									}
								}
								if (default_icon == null) default_icon = getGIcon();
								placemarker = makeMarker(placemark_point,default_icon,placemark_name,placemark_description);
								map.addOverlay(placemarker);
								if (placemark_link != null) {
									setMouseOverImage(
										placemark_link,
										placemarker,
										placemark_name,
										placemark_description
									);
								}
							}
							if (q["fit"] != null && q["fit"] == 1 && n != null && s != null && e != null && w != null) {
								var bound = new GLatLngBounds(new GLatLng(s,w),new GLatLng(n,e));
								map.setCenter(bound.getCenter(), map.getBoundsZoomLevel(bound));
								saveMap();
							}
						}
					}
				}
				request.send(null);
			}
			if (search_form != null) {
				search_form.onsubmit = function () {
					kml_url = base_url + '?' + urlEncode(getHashFromForm(this));
					refreshKml();
					return false;
				};
			}
			if (q["r"] != null && q["r"] == 1) {
				GEvent.addListener( map, 'dragend', function () { refreshKml(); } );
				GEvent.addListener( map, 'zoomend', function () { refreshKml(); } );
			}
		}
		if (q["sv"] != null && q["sv"] == 1 && w > 250 && h > 250) {
			self.document.getElementById("streetview-tool").innerHTML = '<a style="display: block; font-size: 1px; text-indent: -200px; overflow: hidden; cursor: pointer; border: none; margin: 0; padding: 0; position: absolute; top: 0; left: 56px; width: 15px; height: 15px; z-index: 10000; background-image: url(\'./gmap/gguy.gif\')" onclick="toggleStreetviewOverlay()" title="ストリートビュー">ストリートビュー</a>';
		}
		if (field_enabled || (q["s"] != null && q["s"] == 1)) {
			self.document.getElementById("geocoder-tool").innerHTML = '<a style="display: block; font-size: 1px; text-indent: -200px; overflow: hidden; cursor: pointer; border: none; margin: 0; padding: 0; position: absolute; top: 0; left: 0; width: 15px; height: 15px; z-index: 10000; background-image: url(\'./gmap/search.gif\')" onclick="toggleSearchBox()" title="住所検索">住所検索</a><form id="geocoder-search" action="#" onsubmit="geocoderSearch(); return false;" style="width: ' + w + 'px; display: none; position: absolute; top: 0; left: 0; margin-top: 100px; text-align: center;"><input type="search" placeholder="住所検索" results="5" autosave="geocodersearch" size="24" id="geocoderkey" value="" /><input type="button" onclick="geocoderSearch()" value="検索" /><img style="border: 0px none ; margin-left: 3px; width: 14px; height: 13px; -moz-user-select: none; cursor: pointer;" src="http://www.google.co.jp/intl/ja_jp/mapfiles/close.gif" onclick="toggleSearchBox()" title="住所検索欄を閉じる" /></form>';
			self.document.getElementById("geocoder-search").style.display = "none";
			if (field_enabled) {
				GEvent.addListener( map, 'dragend', function () { centerMarker(); saveMap(); } );
				GEvent.addListener( map, 'zoomend', function () { centerMarker(); saveMap(); } );
				GEvent.addListener( map, 'maptypechanged', function () { saveMap(); } );
			}
		}
		if (
			(
				m_field != null
				|| (q["m"] != null && q["m"] != "")
				|| (q["i"] != null && q["i"] == 1)
				|| kml_overlay != null
			) && q["tr"] != null && q["tr"] != ""
		) {
			GEvent.addListener( map, 'infowindowopen', 
				function () {
					var self_links = document.getElementsByTagName('a');
					for (var i=0; i<self_links.length; i++) {
						if (
								typeof self_links[i].getAttribute("href") == "string"
								&& self_links[i].getAttribute("href").search(/^http/i) != -1
								&& self_links[i].getAttribute("href").search(/^http:\/\/\w+\.google/i) == -1
								&& ((q["i"] == null || q["i"] != 1) || (self_links[i].target == null || self_links[i].target == ""))
						) {
							if (q["tr"] != null && q["tr"] == "p") {
								self_links[i].target = "_parent";
							} else if (q["tr"] != null && q["tr"] == "t") {
								self_links[i].target = "_top";
							} else if (q["tr"] != null && q["tr"] == "s") {
								self_links[i].target = "_self";
							} else if (q["tr"] != null && q["tr"] == "d") {
								if (self_links[i].getAttribute("href").search(/m=(DetailViewer|Inquiry)&/) != -1) {
									self_links[i].target = "detailViewer";
									self_links[i].onclick = function () { window.open('','detailViewer','width=640,height=480,scrollbars=yes,resizable=yes'); };
								} else {
									self_links[i].target = "_blank";
								}
							} else {
								self_links[i].target = "_blank";
							}
						}
					}
				}
			);
		}
	} else if (q["key"] != null && q["key"] != "") {
		var w;
		var h;
		if (q["width"] != null && q["width"] != "" && !isNaN(q["width"]) && q["height"] != null && q["height"] != "" && !isNaN(q["height"])) {
			w = parseInt(q["width"]);
			h = parseInt(q["height"]);
		} else {
			w = ((self.innerWidth) ? self.innerWidth : ((document.compatMode != null && document.compatMode != "BackCompat") ? self.document.documentElement.clientWidth : self.document.body.clientWidth));
			h = ((self.innerHeight) ? self.innerHeight : ((document.compatMode != null && document.compatMode != "BackCompat") ? self.document.documentElement.clientHeight : self.document.body.clientHeight))
		}
		if (w > 512) w = 512;
		if (h > 512) h = 512;
		var gmap_img = document.createElement('img');
		gmap_img.style.width = w + "px";
		gmap_img.style.height = h + "px";
		gmap_img.style.border = "none";
		if (q["m"] != null && q["m"] != "") gmap_img.title = q["m"].replace(/<.*?>/,'');
		var center = ((q["c"] != null && q["c"] != "") ? q["c"] : '36.315125,137.504883');
		gmap_img.src	= 'http://maps.google.com/staticmap?key=' + q["key"]
						+ '&center=' + center
						+ '&zoom=' + ((q["z"] != null && q["z"] != "" && !isNaN(q["z"])) ? parseInt(q["z"]) : 4)
						+ '&size=' + w + 'x' + h
						+ ((q["m"] != null && q["m"] != "") ? '&markers=' + center : '');
		self.document.getElementById("map").appendChild(gmap_img);
		var gmap_msg = document.createElement('p');
		gmap_msg.style.position = 'absolute';
		gmap_msg.style.backgroundColor = '#FFF';
		gmap_msg.style.color = '#000';
		gmap_msg.style.top = 0;
		gmap_msg.style.left = 0;
		gmap_msg.innerHTML = 'Google マップを表示できませんでした。';
		self.document.getElementById("map").appendChild(gmap_msg);
	}
}

function refreshKml() {
	if (kml_overlay != null) map.removeOverlay(kml_overlay);
	kml_overlay = new GGeoXml(kml_url + ((kml_url.search(/\?/) == -1) ? '?' : '&') + 'gmap_sw=' + map.getBounds().getSouthWest().lat() + ',' + map.getBounds().getSouthWest().lng() + '&gmap_ne=' + map.getBounds().getNorthEast().lat() + ',' + map.getBounds().getNorthEast().lng());
	map.addOverlay(kml_overlay);
}

function setMouseOverImage(placemark_link,placemarker,marker_title,marker_description) {
	var caller_links = _caller.document.getElementsByTagName('a');
	for (var i=0; i<caller_links.length; i++) {
		if (caller_links[i].href == placemark_link) {
			GEvent.addDomListener(
				caller_links[i],
				'mouseover',
				function () {
					toggleGIcon(placemarker,true);
					if ((marker_description != null && marker_description != "") || (marker_title != null && marker_title != "")) {
						placemarker.openInfoWindowHtml(
							((marker_description != null && marker_description != "") ? marker_description : marker_title),
							{maxWidth : mw}
						);
					}
				}
			);
			GEvent.addDomListener(
				caller_links[i],
				'mouseout',
				function () {
					toggleGIcon(placemarker,false);
				}
			);
		}
	}
}

function openPanoramaBubble() {
	var w = ((self.innerWidth) ? self.innerWidth : ((document.compatMode != null && document.compatMode != "BackCompat") ? self.document.documentElement.clientWidth : self.document.body.clientWidth));
	var h = ((self.innerHeight) ? self.innerHeight : ((document.compatMode != null && document.compatMode != "BackCompat") ? self.document.documentElement.clientHeight : self.document.body.clientHeight));
	var content_node = document.createElement('div');
	content_node.style.textAlign = 'center';
	content_node.style.width = (w - 50) + 'px';
	content_node.style.height = (h - 80) + 'px';
	content_node.innerHTML = '読み込み中...';

	var small_node = document.createElement('div');
	small_node.style.width = '200px';
	small_node.style.height = '200px';
	small_node.id = 'pano';
	streetview_man.openInfoWindow(small_node, { maxContent: content_node, maxTitle: "最大表示" });

	panorama = new GStreetviewPanorama(small_node);
	panorama.setLocationAndPOV(streetview_man.getLatLng(),{ zoom : 1 });
	GEvent.addListener(panorama, "newpano", onNewLocation);
	GEvent.addListener(panorama, "yawchanged", onYawChange); 

	GEvent.addListener(
		map.getInfoWindow(),
		"maximizeend",
		function() {
			panorama.setContainer(content_node);  
			window.setTimeout("panorama.checkResize()", 5);
		}
	);
}

function onYawChange(newYaw) {
	var GUY_NUM_ICONS = 16;
	var GUY_ANGULAR_RES = 360/GUY_NUM_ICONS;
	if (newYaw < 0) newYaw += 360;
	streetview_man.setImage("http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-" + (Math.round(newYaw/GUY_ANGULAR_RES) % GUY_NUM_ICONS) + ".png");
}

function onNewLocation(lat,lng) {
	var latlng = new GLatLng(lat,lng);
	streetview_man.setLatLng(latlng);
}

function toggleStreetviewOverlay() {
	if (streetview_overlay == null) {
		if (streetview_client == null) streetview_client = new GStreetviewClient();
		streetview_man_location = null;
		streetview_man = new GMarker(map.getCenter(), { icon: getGuyIcon(), draggable: true });
		map.addOverlay(streetview_man);
		GEvent.addListener(streetview_man, "dragend", getNearestStreetview);
		GEvent.addListener(streetview_man, "click", getNearestStreetview);
		getNearestStreetview();
		streetview_overlay = new GStreetviewOverlay();
		map.addOverlay(streetview_overlay);
	} else {
		map.removeOverlay(streetview_overlay);
		streetview_overlay = null;
		map.removeOverlay(streetview_man);
		streetview_man = null;
	}
}

function getNearestStreetview() {
	streetview_client.getNearestPanorama(streetview_man.getLatLng(), onResponse);
}

function onResponse(response) {
	if (response.code != 200) {
		if (streetview_man_location != null) streetview_man.setLatLng(streetview_man_location);
	} else {
		var latlng = new GLatLng(response.Location.lat, response.Location.lng);
		streetview_man.setLatLng(latlng);
		if (streetview_man_location != null) openPanoramaBubble();
		streetview_man_location = latlng;
	}
}

function formattedDistance (meter) {
	return (meter > 1000) ? (parseInt(meter) / 1000) + 'km' : parseInt(meter) + 'm';
}

function openCenterInfoWindow() {
	if (m_field.value != "") center_marker.openInfoWindowHtml('<div style="font-size: 14px">' + m_field.value + '</div>',{maxWidth : mw});
}

function makeMarker(point,icon,marker_title,marker_description){
	var marker = new GMarker(point,{
		icon	:	icon,
		title	:	marker_title.replace(/<.*?>/g,'')
	});
	GEvent.addListener(
		marker,
		"click",
		function() {
			marker.openInfoWindowHtml(
				((marker_description != null && marker_description != "") ? marker_description : marker_title),
				{maxWidth : mw}
			);
		}
	);
	return marker;
}

function geocoderSearch() {
	var keyword = self.document.getElementById('geocoderkey').value;
	if (keyword != null && keyword != "") {
		if (geocoder_client == null) geocoder_client = new GClientGeocoder();
		geocoder_client.getLatLng(
			keyword,
			function (latlng) {
				if (!latlng) {
					alert("条件に該当する地図は見つかりませんでした");
				} else {
					var z = map.getZoom();
					map.setCenter(latlng, ((z < 10) ? 15 : z));
					saveMap();
					centerMarker();
					if (q["r"] != null && q["r"] == 1) refreshKml();
				}
			}
		);
	}
}

function toggleSearchBox() {
	var search_box = self.document.getElementById("geocoder-search");
	if (search_box.style.display == null || search_box.style.display == 'none') {
		var addr = '';
		if (addr_field_ids != null && addr_field_ids.constructor == Array && addr_field_ids.length > 0) {
			for (var i in addr_field_ids) {
				if (_caller.document.getElementById(addr_field_ids[i])) {
					var addr_field = _caller.document.getElementById(addr_field_ids[i])
					if (addr_field.type != null && addr_field.type == 'select') {
						addr += addr_field.options[addr_field.options.selectedIndex].value;
					} else {
						addr += addr_field.value;
					}
				}
			}
			if (addr != "") self.document.getElementById("geocoderkey").value = addr;
		}
		search_box.style.display = 'block';
		self.document.getElementById("geocoderkey").focus();
		if (addr == "") self.document.getElementById("geocoderkey").select();
	} else {
		search_box.style.display = 'none';
	}
}

function saveMap() {
	if (z_field != null) z_field.value = map.getZoom();
	if (t_field != null) t_field.value = map.getCurrentMapType().getUrlArg();
	if (c_field != null) c_field.value = map.getCenter().lat() + ',' + map.getCenter().lng();
	if (fit_field != null) fit_field.checked = false;
}

function centerMarker() {
	if (center_marker != null) center_marker.setPoint(map.getCenter());
}

function fitWindow() {
	var w = ((self.innerWidth) ? self.innerWidth : ((document.compatMode != null && document.compatMode != "BackCompat") ? self.document.documentElement.clientWidth : self.document.body.clientWidth));
	var h = ((self.innerHeight) ? self.innerHeight : ((document.compatMode != null && document.compatMode != "BackCompat") ? self.document.documentElement.clientHeight : self.document.body.clientHeight));
	self.document.getElementById("map").style.width = w + "px";
	self.document.getElementById("map").style.height = h + "px";
	if (map != null) map.checkResize();
}

function urlDecode(query) {
	var hash = new Array();
	if (query == null || query == "" || query.search("=") == -1) return hash;
	query = query.replace(/^\?/,'').split('&');
	for (var i=0; i<query.length; i++) {
		var p = query[i].split('=');
		if (window.decodeURIComponent) {
			p[0] = decodeURIComponent(p[0].replace(/\+/g,' '));
			p[1] = decodeURIComponent(p[1].replace(/\+/g,' '));
		} else {
			p[0] = unescape(p[0].replace(/\+/g,' '));
			p[1] = unescape(p[1].replace(/\+/g,' '));
		}
		if (hash[p[0]] == null) {
			hash[p[0]] = p[1];
		} else {
			if (hash[p[0]].constructor == Array) {
				hash[p[0]].push(p[1]);
			} else {
				hash[p[0]] = new Array(hash[p[0]],p[1]);
			}
		}
	}
	return hash;
}

function urlEncode (hash) {
	var query = '';
	for (var key in hash) {
		if (hash[key] != null) {
			var encoded_key = ((window.encodeURIComponent) ? encodeURIComponent(key) : escape(key)).replace(/ /g,'+')
			if (hash[key].constructor == Array) {
				for (var i=0; i<hash[key].length; i++) {
					if ((typeof hash[key][i] == "string" || typeof hash[key][i] == "number") && hash[key][i] != null) query += ((query != "") ? "&" : "") + encoded_key + "=" + ((window.encodeURIComponent) ? encodeURIComponent(hash[key][i]) : escape(hash[key][i])).replace(/ /g,'+');
				}
			} else if (typeof hash[key] == "string" || typeof hash[key] == "number") {
				query += ((query != "") ? "&" : "") + encoded_key + "=" + ((window.encodeURIComponent) ? encodeURIComponent(hash[key]) : escape(hash[key])).replace(/ /g,'+');
			}
		}		
	}
	return query;
}

function getHashFromForm (this_form) {
	var hash = new Array();
	for (var i=0; i < this_form.elements.length; i++) {
		if (typeof this_form.elements[i].name != "undefined" && this_form.elements[i].name != "" && (typeof this_form.elements[i].value == "string" || typeof this_form.elements[i].value == "number")) {
			var name = this_form.elements[i].name;
			if (typeof this_form.elements[i].type == "undefined" || this_form.elements[i].type == null) {
				hash[name] = this_form.elements[i].value;
			} else if (this_form.elements[i].type == 'text' || this_form.elements[i].type == 'password' || this_form.elements[i].type == 'textarea' || this_form.elements[i].type == 'hidden' || this_form.elements[i].type == 'submit' || this_form.elements[i].type == 'image' || this_form.elements[i].type == 'search') {
				if (this_form.elements[i].type == 'hidden' && typeof this_form.elements[i].getAttribute('alt') == 'string') {
					hash[name] = this_form.elements[i].getAttribute('alt');
				} else {
					hash[name] = this_form.elements[i].value;
				}
			} else if (this_form.elements[i].type == 'checkbox' || this_form.elements[i].type == 'radio') {
				if (this_form.elements[i].checked) {
					if (hash[name] != null) {
						if (hash[name].constructor == Array) {
							hash[name].push(this_form.elements[i].value);
						} else {
							hash[name] = new Array(hash[name],this_form.elements[i].value);
						}
					} else {
						hash[name] = this_form.elements[i].value;
					}
				}
			} else if (this_form.elements[i].type.search(/select/) != -1) {
				for (var o=0; o < this_form.elements[i].options.length; o++) {
					if (this_form.elements[i].options[o].selected) {
						if (hash[name] != null) {
							if (hash[name].constructor == Array) {
								hash[name].push(this_form.elements[i].options[o].value);
							} else {
								hash[name] = new Array(hash[name],this_form.elements[i].options[o].value);
							}
						} else {
							hash[name] = this_form.elements[i].options[o].value;
						}
					}
				}
			}
		}
	}
	return hash;
}


