<?php
	require("../__common__/__define_common.php");
	require("../__common__/include-common-all.php");
	if (!defined("GOOGLE_MAPS_EARTH_ADDRESS")) {
		define("GOOGLE_MAPS_EARTH_ADDRESS", "新宿");
	}
	if (!defined("GOOGLE_MAPS_EARTH_ZOOM")) {
		define("GOOGLE_MAPS_EARTH_ZOOM", 15);
	}
	if (!defined("MAPS_FIX_HEIGHT")) {
		define("MAPS_FIX_HEIGHT", 24);
	}
	if (!defined("MAPS_PHOTO_ICON_MARKER_SIZE")) {
		define("MAPS_PHOTO_ICON_MARKER_SIZE", "64,64");
	}
	if ($_GET['addr'] <> '') {
		$addr = $_GET['addr'];
	} elseif ($_POST['address'] <> '') {
		$addr = $_POST['address'];
//	} elseif ($_COOKIE['google_maps_address'] <> '') {
//		$addr = $_COOKIE['google_maps_address'];
	} else {
		$addr = GOOGLE_MAPS_EARTH_ADDRESS;
	}
	$addr = str_replace('+', ' ', $addr);
	setcookie('google_maps_address', $addr, time() + LOGIN_COOKIE_EXPIRE, MY_SESSION_PATH);
	if ($_GET['zoom'] <> '') {
		$zoom = $_GET['zoom'];
	} else {
		$zoom = GOOGLE_MAPS_EARTH_ZOOM;
	}
	if (!defined("MAPS_LINEPATH_COLOR")) {
		define("MAPS_LINEPATH_COLOR", "#ff4500");
	}
	if (!defined("MAPS_LINEPATH_WEIGHT")) {
		define("MAPS_LINEPATH_WEIGHT", 3);
	}
	if (!defined("GOOGLE_MAPS_PLACE_TYPES")) {
		define("GOOGLE_MAPS_PLACE_TYPES", "google_maps_place_types.php");
	}
	if (!defined("GOOGLE_MAPS_PLACE_ICON")) {
		define("GOOGLE_MAPS_PLACE_ICON", DIARY_MAPS_ICON_FOLDER."markerSmall80.png");
	}
	if (!defined("HYAKUMEIZAN_CATEGORY_ID")) {
		define("HYAKUMEIZAN_CATEGORY_ID", 3);		//百名山のid_category(in m_category)
	}
	if (!defined("SEKAI_ISAN_CATEGORY_ID")) {
		define("SEKAI_ISAN_CATEGORY_ID", 4);		//世界遺産のid_category(in m_category)
	}
	if (!defined("TETSUDO_EKI_CATEGORY_ID")) {
		define("TETSUDO_EKI_CATEGORY_ID", 5);		//鉄道駅のid_category(in m_category)
	}
	if (!defined("SAKURA_MEISHO_CATEGORY_ID")) {
		define("SAKURA_MEISHO_CATEGORY_ID", 6);		//桜名所のid_category(in m_category)
	}
	if (!defined("HYAKUSEN_CATEGORY_ID")) {
		define("HYAKUSEN_CATEGORY_ID", 7);		//日本百選のid_category(in m_category)
	}
	if (!defined("MAPS_SIDE_BAR_WIDTH")) {
		define("MAPS_SIDE_BAR_WIDTH", "140px");
	}
	if (!defined("MAPS_SIDE_BAR_HEIGHT")) {
		define("MAPS_SIDE_BAR_HEIGHT", "80%");
	}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="author" content="ok.2nd">
<title>Google Maps</title>
<style>
body, div, img, ul, ol, li, p, th, td, form, pre, dl, dt, dd, fieldset, blockquote, caption, h1, h2, h3, h4, h5, h6 {
	margin: 0;
	padding: 0;
}
body {margin: 10px; }
input, select, textarea { margin: 0; }
img { border: 0; }
body {
	background-color: #ffffff;
	text-align: left;
	font-family: "MS PGothic","Osaka",Arial,sans-serif;
}
body, input, button, textarea {
	font-size: 12px;
	line-height: 1.2;
}
button, input[type="button"], input[type="submit"], input[type="reset"] {
	overflow: visible;
	margin: 1px 0;
	padding: 1px 3px;
	padding: 0 2px\9;	/* IE8以下 */
}
body:not(:target) {
	padding: 0 2px\9;	/* IE9 */
}
html {
	width: 100%x;
	height: 100%;
	overflow: hidden;
}
body {
	margin: 0;
	width: 100%;
	height: 100%;
}
#form {
	margin: 5px 0 0 5px;
}
#map_canvas {
	width: 100%;
	height: 100%;
}
#panorama {
	position: absolute; bottom: 5px; right: 6px; width: 48%; height: 45%;
	border: 1px solid #666; padding: 0px; line-height: 1.4; overflow: hidden;
	background: #ffffff;
}
#panowin {
	position: relative; width: 100%; height: 100%;
	border-top: 1px solid #666; padding: 0px;
}
#route_navi {
	position: absolute;
	top: 30px; left: 0px; width: 200px; height: 95%;
	border: 1px solid #666; padding: 6px; line-height: 1.4; overflow:scroll;
/*	background: #ffffff; filter: alpha(opacity=75); -moz-opacity:0.75; opacity:0.75; */
	background: url(../images/trans-white.png);
}
#route_navi_open {
	position: absolute;
	top: 30px; left: 0px; width: 14px; height: 16px;
	border: 1px solid #666; padding: 6px; line-height: 1.4; overflow:hidden;
	background: url(../images/trans-white.png);
}
a { color: blue; }
#side_bar {
	position: absolute; top: 80px; right: 6px; width: <?= MAPS_SIDE_BAR_WIDTH ?>; height: <?= MAPS_SIDE_BAR_HEIGHT ?>;
	border: 1px solid #666; padding: 6px; line-height: 1.4; overflow:scroll;
	background: url(../images/trans-white.png);
}
#side_bar li {
	white-space: nowrap;
}
@media print {
	#form { display: none; }
	#side_bar { display: none; }
/*	#route_navi { display: none; } */
	#route_navi { top: 0px; left: 0px; width: 200px; height: 95%; }
	#route_navi_open { display: none; }
	#route_navi_close { display: none; }
	#map_canvas { position: absolute; top: 0px; left: 0px; }
}
a.suggest_onoff {
	text-decoration: none;
	font-size: xx-small;
}
div.infowin {
	overflow: hidden;
}
div.infowin .ttl a {
	color: #000;
	font-weight: bold;
}
div.infowin .ttl img {
	float: left;
	margin-right: 5px;
	width: 16px;
	height: 16px;
}
a.suggest_onoff {
	text-decoration: none;
	font-size: xx-small;
}
/*	Google Maps APIのInfoWindowのスクロールバーを表示させない */
.gm-style-iw {
	overflow: hidden ! important;
}
.gm-style-iw div {
	overflow: hidden ! important;;
}
</style>
<link rel="stylesheet" href="../scripts/jquery.autocomplete.css?20110824">
<script src="http://maps.google.com/maps/api/js?sensor=false&libraries=panoramio,geometry,places"></script>
<script src="../scripts/jquery.js"></script>
<script src="../scripts/jquery.cookie.js"></script>
<script src="../scripts/ok2nd.js"></script>
<script src="../scripts/addclear.js"></script>
<script>
$(function(){
	$('#address').addClear();
});
</script>
<script>
var geocoder = null;
var map;
var ge;
var streetviewWin = false;
var streetviewInit = false;
var panoramioView = false;
var panoramio;
var LinePathUse = false;
var latLngWin;
var side_bar_html = "";
function initialize() {
	geocoder = new google.maps.Geocoder();
	var myOptions = {
		zoom: <?= $zoom ?>,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		streetViewControl: true
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	panoramio = new google.maps.panoramio.PanoramioLayer();
	latLngWin = new google.maps.InfoWindow();
	google.maps.event.addListener(map, 'click',viewLatLngAddress);
	var lineOptions = {
		strokeColor: "<?= MAPS_LINEPATH_COLOR ?>",
		strokeOpacity: 1.0,
		strokeWeight: <?= MAPS_LINEPATH_WEIGHT ?>
	}
	polyline = new google.maps.Polyline(lineOptions);
	polyline.setMap(map);
	google.maps.event.addListener(map, "click", drawLinePath);
	showAddress('<?= $addr ?>', '<?= $_GET['photo'] ?>');
}
function PlacesSearch() {
	clearPlacesMarker();
	var place_type = $("#places").val();
	$.cookie('google_maps_place_type',place_type,{ path:'<?= MY_SESSION_PATH ?>', expires:365 });
	if(!isNaN(place_type.charAt(0))) {
		mapsArea(place_type);
		return;
	}
	var currentBounds = map.getBounds();
	var request = {
		bounds: currentBounds,
		types: [place_type]
	};
	var service = new google.maps.places.PlacesService(map);
	service.search(request, PlacesSearchCallback);
}
function mapsArea(id_category) {
	var bounds = map.getBounds();
	var ne_lat = bounds.getNorthEast().lat();
	var sw_lat = bounds.getSouthWest().lat();
	var ne_lng = bounds.getNorthEast().lng();
	var sw_lng = bounds.getSouthWest().lng();
	data = 'cat='+id_category+'&ne_lat='+ne_lat+'&sw_lat='+sw_lat+'&ne_lng='+ne_lng+'&sw_lng='+sw_lng;
	$.ajax({
		type: "GET",
		url: "google-maps-places.php",
		data: data,
		async: true,
		success: function(res){
			placeMarkers(res);
		}
	})
}
function placeMarkers(places) {
	if (places == '0') {
		alert('表示されている範囲内では見つかりませんでした。');
	}
	var place_ary = places.split('\n');
	for (var i in place_ary) {
		var parm = place_ary[i].split(':::');
		if (parm[1]) {
			var latlng = parm[1].split(',');
			createPlaceMarkerAbook(parm[0], latlng[0], latlng[1], parm[2]);
		}
	}
}
function createPlaceMarkerAbook(name, lat, lng, popStr) {
	var marker_label = zen2han(name).replace(/&/g,'＆').slice(0, 10);
	var icon = 'http://chart.apis.google.com/chart?chst=d_bubble_text_small&chld=bb|'+marker_label+'|FFD700|000000';
	var icon_s = new google.maps.MarkerImage(icon);
	icon_s.anchor = new google.maps.Point(0, 24);
	icon_s.scaledSize = new google.maps.Size(str_width(marker_label)*5+20, 28);
	markerZindex++;
	var marker = new google.maps.Marker({
		map: map,
		icon: icon_s,
		title: name,
		zIndex: markerZindex,
		position: new google.maps.LatLng(lat, lng)
	});
	var infowindow = new google.maps.InfoWindow();
	google.maps.event.addListener(marker, 'click', function() {
		infowindow.setContent('<div class="infowin">' + popStr.replace(/`/g,"'") + '</div>');
		infowindow.open(map, this);
		marker.setZIndex(++markerZindex);
	});
	side_bar_html += '<li><a href="javascript:myClick(' + placesMarkerCnt + ')">' + name + '</a></li>';
	document.getElementById('side_bar').innerHTML = "<ul>"+side_bar_html+"</ul>";
	$("#side_bar").css("display","");
	placesMarker[placesMarkerCnt] = marker;
	placesMarkerCnt++;
}
function myClick(markerCnt) {
	google.maps.event.trigger(placesMarker[markerCnt], 'click');
}
var markerZindex = 0;
var placesMarker = [];
var placesMarkerCnt = 0;
function PlacesSearchCallback(results, status) {
	if (status == google.maps.places.PlacesServiceStatus.OK && results.length > 0) {
		for (var i=0; i < results.length; i++) {
			createPlaceMarker(results[i]);
		}
	} else {
		alert("見つかりませんでした。");
	}
}
function createPlaceMarker(place) {
	if (!place.name) return;
	var placeLoc = place.geometry.location;
	var marker_label = zen2han(place.name).replace(/&/g,'＆').slice(0, 10);
	var icon = 'http://chart.apis.google.com/chart?chst=d_bubble_text_small&chld=bb|'+marker_label+'|FFD700|000000';
	var icon_s = new google.maps.MarkerImage(icon);
	icon_s.anchor = new google.maps.Point(0, 24);
	icon_s.scaledSize = new google.maps.Size(str_width(marker_label)*5+20, 28);
	markerZindex++;
	var marker = new google.maps.Marker({
		map: map,
		icon: icon_s,
		title: place.name,
		zIndex: markerZindex,
		position: new google.maps.LatLng(placeLoc.lat(), placeLoc.lng())
	});
	var infowindow = new google.maps.InfoWindow({
		maxWidth:320
	});
	var html = '<div class="ttl">';
	html += (place.icon)?'<img src="'+place.icon+'">':'';
	html += '<a href="javascript:window.open(\'http://www.google.com/search?q='+place.name+'\');void(0);">'+place.name+'</a>';
	html += '</div>';
	if (place.vicinity) {
		html += '<p>'+place.vicinity+'</p>';
	}
	if (place.rating) {
		html += '<p>評価：'+place.rating+'</p>';
	}
	html += '<p><a href="javascript:window.open(\'http://maps.google.com/maps?q='+place.geometry.location.lat()+','+place.geometry.location.lng();
	html += '\');void(0);">→Googleマップ</a>';
	html += '<a style="margin-left:10px;" href="javascript:addMarker(\''+place.name+'\','+place.geometry.location.lat()+','+place.geometry.location.lng()+')">マーカー作成</a>';
	html += '<a style="margin-left:10px;" href="javascript:deletePlacesMarker('+(placesMarkerCnt)+')">削除</a><br><br>';
	if (place.photos && place.photos.length >= 1) {
		html += '<p class="picframe"><img src="'+place.photos[0].getUrl({'maxWidth':160,'maxHeight':160})+'"></p>';
	}
	google.maps.event.addListener(marker, 'click', function() {
		infowindow.setContent('<div class="infowin">' + html + '</div>');
		infowindow.open(map, this);
		marker.setZIndex(++markerZindex);
	});
	side_bar_html += '<li><a href="javascript:myClick(' + placesMarkerCnt + ')">' + place.name + '</a></li>';
	document.getElementById('side_bar').innerHTML = "<ul>"+side_bar_html+"</ul>";
	$("#side_bar").css("display","");
	placesMarker[placesMarkerCnt] = marker;
	placesMarkerCnt++;
}
function deletePlacesMarker(markerNo) {
	placesMarker[markerNo].setMap(null);
	delete placesMarker[markerNo];
}
function clearPlacesMarker() {
	for (ix=0; ix<placesMarkerCnt; ix++) {
		if (placesMarker[ix]) {
			placesMarker[ix].setMap(null);
		}
	}
	placesMarkerCnt = 0;
	$("#side_bar").css("display","none");
	side_bar_html = '';
	document.getElementById('side_bar').innerHTML = '';
}
function viewLatLngAddress(e) {
	if (LinePathUse) return;
	var latlng = e.latLng;
	var lat = e.latLng.lat().toString();
	var lng = e.latLng.lng().toString();
	geocoder.geocode({'latLng': latlng}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			if (results[1]) {
				 address = results[1].formatted_address;
			} else {
				 address = ""
			}
		} else {
			address = ""
		}
		// 標高取得
		var elevation = '';
		var locations = [latlng];
		var elevator = new google.maps.ElevationService();
		elevator.getElevationForLocations({
			locations: locations
		}, function(results, status) {
			if (status == google.maps.ElevationStatus.OK) {
				if (results[0].elevation) {
					elevation = results[0].elevation.toFixed(1);
				}
			}
			var html = '<div class="ttl">';
			html += '<a href="javascript:window.open(\'http://www.google.com/search?q='+address+'\');void(0);">'+address+'</a>';
			html += '</div>';
			html += '<p>緯度：'+lat+'</p>';
			html += '<p>経度：'+lng+'</p>';
			html += '<p>標高：'+elevation+'m</p>';
			html += '<a href="javascript:window.open(\'http://maps.google.com/maps?q='+encodeURL(lat)+','+encodeURL(lng);
			html += '\');void(0);">→Googleマップ</a>';
			html += '<a style="margin-left:10px;" href="javascript:addMarker(\''+address+'\','+lat+','+lng+')">マーカー作成</a><br><br>';
			latLngWin.setContent('<div class="infowin">' + html + '</div>');
			latLngWin.setPosition(latlng);
			latLngWin.open(map);
		});
	 });
}
function showAddress(address, photo) {
	if (address == '') return;
	$.cookie('google_maps_address',address,{ path:'<?= MY_SESSION_PATH ?>', expires:365 });
	if (geocoder) {
		geocoder.geocode( {'address': address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var position = results[0].geometry.location;
				map.setCenter(position);
				showMarker(map, position, address, photo);
					zoomMarkerAll();
			} else {
				alert('「'+address+'」が見つかりません。status: '+status);
			}
		});
	}
}
var markers = [];
var markers_l = [];
var markers_pos = [];
var markersCnt = 0;
var current_infowin = null;
function showMarker(map, position, address, photo) {
	var icon = null;
	var html = '<div class="ttl">';
	html += '<a href="javascript:window.open(\'http://www.google.com/search?q='+address+'\');void(0);">'+address+'</a>';
	html += '</div>';
	html += '<p>緯度：'+position.lat()+'</p>';
	html += '<p>経度：'+position.lng()+'</p>';
//	html += '<p><a href="javascript:window.open(\'http://maps.google.com/maps?q='+encodeURL(address);
	html += '<p><a href="javascript:window.open(\'http://maps.google.com/maps?q='+position.lat()+','+position.lng();
	html += '\');void(0);">→Googleマップ</a>';
	html += '<a style="margin-left:10px;" href="javascript:deleteMarker('+(markersCnt)+')">マーカー削除</a></p><br><br>';
	if (photo != '') {
		html += '<p><a href="javascript:window.open(\''+photo+'\');void(0);"><img src="'+photo+'" height=64></a></p>';
		icon = new google.maps.MarkerImage(
			photo,
			new google.maps.Size(<?= MAPS_PHOTO_ICON_MARKER_SIZE ?>),	// size
			new google.maps.Point(0,0),	// origin
			new google.maps.Point(16,16),	// anchor
			new google.maps.Size(<?= MAPS_PHOTO_ICON_MARKER_SIZE ?>)	// scaledSize
		);
	}
	var infowindow = new google.maps.InfoWindow({
		content: '<div class="infowin">' + html + '</div>'
	});
	markerZindex++;
	var marker = new google.maps.Marker({
		icon: icon,
		map: map,
		zIndex: markerZindex,
		position: position
	});
	google.maps.event.addListener(marker, 'click', function() {
		if (current_infowin) {
			current_infowin.close();
		}
		infowindow.open(map,marker);
		marker.setZIndex(++markerZindex);
		current_infowin = infowindow;
	});
	markerLabel(markersCnt, position, address);
	markers[markersCnt] = marker;
	markersCnt++;
}
function markerLabel(markerIx, position, address) {
	var marker_label = zen2han(address).replace(/&/g,'＆');
	var icon_l = 'http://chart.apis.google.com/chart?chst=d_text_outline&chld=f0f|13|l|fff|_|'+marker_label;
	var icon_s = new google.maps.MarkerImage(icon_l);
	icon_s.anchor = new google.maps.Point(-5, 12);
//	icon_s.scaledSize = new google.maps.Size(str_width(marker_label)*5+10, 13);
	var marker_l = new google.maps.Marker({
		position: position,
		map: map,
		icon: icon_s
	});
	var place_len = address.length * 3 + 5;
	html = '<form method="post" onsubmit="changeLabel('+markerIx+');return false">';
	html += '<input id="place" name="place" type="text" size="'+place_len+'" value="'+address+'">';
	html += '<input type="submit" value="修正">';
	html += '</form>';
	var editwindow = new google.maps.InfoWindow({
		content: html
	});
	google.maps.event.addListener(marker_l, 'click', function() {
		if (current_infowin) {
			current_infowin.close();
		}
		editwindow.open(map, marker_l);
		current_infowin = editwindow;
	});
	markers_l[markerIx] = marker_l;
	markers_pos[markerIx] = position;
}
function changeLabel(markerIx) {
	var place = $("#place").val();
	markers_l[markerIx].setMap(null);
	markerLabel(markerIx, markers_pos[markerIx], place);
}
function clearMarker() {
	for (ix=0; ix<markersCnt; ix++) {
		if (markers[ix]) {
			markers[ix].setMap(null);
			markers_l[ix].setMap(null);
		}
	}
	markersCnt = 0;
}
function markerVisible(onoff) {
	for (ix=0; ix<markersCnt; ix++) {
		if (markers[ix]) {
			markers[ix].setOptions({visible:onoff});
		}
	}
}
function setHeightPercent(elementID, fixHeight) {
	// マップの高さ設定
	//if (document.all) {	// IE
	//	fixHeight += 50;
	//}
	mapsWinHeight = 100 - Math.ceil( fixHeight * 100 / screen.availHeight );
	document.getElementById(elementID).style.height = mapsWinHeight + "%";
}
function addressClear() {
	document.getElementById("address").value = '';
}
function StreetViewOnOff() {
	if (!streetviewWin) {
		StreetViewOn();
	} else {
		StreetViewOff();
	}
}
function StreetViewOn() {
	$("#panorama").css("display","");
	if (!streetviewInit) {
		var panoramaOptions = {
			pov: {
				heading: 34,
				pitch: 10,
				zoom: 1
			}
		};
		var panorama = new google.maps.StreetViewPanorama(document.getElementById("panowin"), panoramaOptions);
		map.setStreetView(panorama);
	}
	streetviewInit = true;
	streetviewWin = true;
}
function StreetViewOff() {
	$("#panorama").css("display","none");
	streetviewWin = false;
	$("#cb_sv").attr("checked", false);
}
function PanoramioOnOff(me) {
	if (me.checked) {
		$("#panoramio_opt").css("display","");
		panoramio.setMap(map);
	} else {
		$("#panoramio_opt").css("display","none");
		panoramio.setMap(null);
	}
}
function getTaggedPhotos() {
	var tagFilter = document.getElementById('tag').value;
	panoramio.setTag(tagFilter);
}
function resetTaggedPhotos() {
	document.getElementById('tag').value = '';
	panoramio.setTag('');
}
function LinePathOnOff() {
	if (LinePathUse) {
		LinePathUse = false;
	} else {
		LinePathUse = true;
	}
}
function drawLinePath(event) {
	if (LinePathUse) {
		lpath = polyline.getPath();
		lpath.push(event.latLng);
		kyori = google.maps.geometry.spherical.computeLength(lpath.getArray());
	//	document.getElementById("lineLength").value = kyori.toFixed(1);
		document.getElementById("lineLength").value = num_format(kyori,1);
	}
}
function clearLinePath() {
	polyline.setMap(null);
	var lineOptions = {
		strokeColor: "<?= MAPS_LINEPATH_COLOR ?>",
		strokeOpacity: 1.0,
		strokeWeight: <?= MAPS_LINEPATH_WEIGHT ?>
	}
	polyline = new google.maps.Polyline(lineOptions);
	polyline.setMap(map);
	google.maps.event.addListener(map, "click", drawLinePath);
	document.getElementById("lineLength").value = "";
}
function addMarker(addr, lat, lng) {
	var position = new google.maps.LatLng(lat, lng);
	showMarker(map, position, addr.replace('日本,',''), '');
	latLngWin.close(map);
}
function deleteMarker(markerNo) {
	markers[markerNo].setMap(null);
	markers_l[markerNo].setMap(null);
	delete markers[markerNo];
	delete markers_l[markerNo];
}
function zoomMarkerAll() {
	if (markersCnt == 0) return;
	maxLat = -999;
	minLat = 999;
	maxLng = -999;
	minLng = 999;
	for (ix=0; ix<markersCnt; ix++) {
		if (markers[ix] != null) {
			var latlng = markers[ix].position;
			var lat = latlng.lat();
			var lng = latlng.lng();
			if (maxLat < lat) maxLat = lat;
			if (minLat > lat) minLat = lat;
			if (maxLng < lng) maxLng = lng;
			if (minLng > lng) minLng = lng;
		}
	}
	southWest = new google.maps.LatLng(minLat,minLng);
	northEast = new google.maps.LatLng(maxLat,maxLng);
	bounds = new google.maps.LatLngBounds(southWest,northEast);
	map.fitBounds(bounds);
	if (map.getZoom() > 16) {
		map.setZoom(16);
	}
	$("#c_mapCenterLat").val(map.getCenter().lat());
	$("#c_mapCenterLng").val(map.getCenter().lng());
	$("#c_mapZoomLevel").val(map.getZoom());
}
var directionsService = new google.maps.DirectionsService();
var proute = null;
var coordinates = [];
var directions;
function travelModeSelect() {
	$.cookie('google_maps_TravelMode',$("#travel_mode").val(),{ path:'<?= MY_SESSION_PATH ?>', expires:365 });
	if (proute != null) {
		plotRouteClear();
		plotRouteView();
	}
}
function plotRouteOnOff() {
	if (proute == null) {
		proute = plotRouteView();
		markerVisible(false);
	} else {
		plotRouteClear();
		markerVisible(true);
		proute = null;
	}
}
var route_navi = false;
var directionsDisplay;
var waypoints_cnt;
function plotRouteView() {
	var waypoints = [];
	waypoints_cnt = 0;
	var start = null
	var end = null
	if (markersCnt < 2) {
		alert("マーカーが2つありません。");
		$("#cb_pr").attr('checked', false);
		return null;
	}
	for (ix=0; ix<markersCnt; ix++) {
		if (markers[ix] != null) {
			var latlng = markers[ix].position;
			waypoints.push({
				location:latlng,
				stopover:true
			});
			waypoints_cnt += 1;
			if (start == null) {
				start = latlng;
			} else {
				end = latlng;
			}
		}
	}
	if (end == null) {
		alert("マーカーが2つありません。");
		$("#cb_pr").attr('checked', false);
		return null;
	}
	if (route_navi) {
		directionsDisplay.setMap(null);
		directionsDisplay.setPanel(null);
	}
	var rendererOptions = {
		draggable: true
	};
	directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
	directionsDisplay.setMap(map);
	route_navi = true;
	directionsDisplay.setPanel(document.getElementById("route_navi"));
	$("#route_navi").css("display","");
	$("#route_navi_open").css("display","none");
	if ($("#travel_mode").val() == "w") {
		var travelMode = google.maps.DirectionsTravelMode.WALKING;
		var avoidTolls = false;
	} else if ($("#travel_mode").val() == "t") {
		var travelMode = google.maps.DirectionsTravelMode.DRIVING;
		var avoidTolls = true;
	} else {
		var travelMode = google.maps.DirectionsTravelMode.DRIVING;
		var avoidTolls = false;
	}
	var request = {
		origin: start,
		destination: end,
		waypoints: waypoints,
		optimizeWaypoints: true,
		avoidTolls: avoidTolls,
		travelMode: travelMode
	};
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
			route_all_calculate(response);
		}
	});
	google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
		route_all_calculate(directionsDisplay.directions);
	});
	return 'on';
}
function route_all_calculate(response) {
	var route = response.routes[0];
	var distance = 0;
	var duration = 0;
	var dis_time = '';
	for (var i=0; i<=waypoints_cnt; i++) {
		distance += route.legs[i].distance.value;
		duration += route.legs[i].duration.value;
		dis_time += '<br>' + String.fromCharCode(i+66) + ') ' + cal_dis_time(route.legs[i].distance.value, route.legs[i].duration.value);
	}
	var route_all = cal_dis_time(distance, duration); 
	document.getElementById("route_all_time").innerHTML = '<strong>' + route_all + '</strong>' + dis_time;
}
function cal_dis_time(distance, duration) {
	hh = 0;
	dstKm = Math.round(distance / 100) / 10;
	if (duration >= 3600)	{
		hh = Math.floor(duration / 3600);
		duration = duration % 3600;
	}
	mm = Math.ceil(duration / 60);
	var res = '時間：';
	if (hh > 0) {
		res += hh + '時間';
	}
	res += mm + '分'
	res += ' 距離：' + dstKm + 'km';
	return res;
}
function plotRouteClear() {
	$("#route_navi").css("display","none");
	$("#route_navi_open").css("display","none");
	directionsDisplay.setMap(null);
}
</script>
</head>
<?php
	if ($_COOKIE['google_maps_place_type'] <> '') {
		$place_type = $_COOKIE['google_maps_place_type'];
	} else {
		$place_type = '';
	}
	require(GOOGLE_MAPS_PLACE_TYPES);
?>
<body onload="initialize()">
<form id="form" method="POST" action="<?= $_SERVER['SCRIPT_NAME'] ?>">
<script src="../scripts/ubilabs-geocomplete/jquery.geocomplete.min.js"></script>
<script src="../scripts/jquery.autocomplete_my.js"></script>
<?php
	if ($_COOKIE['maps_suggestOnOff'] == 'off') {
		$suggest_on = ' display:none;';
		$suggest_off = '';
	} else {
		$suggest_on = '';
		$suggest_off = ' display:none;';
	}
?>
<script>
var suggest_sw = '<?= $_COOKIE['maps_suggestOnOff'] ?>';
function suggest(sw) {
	suggest_sw = sw;
	$.cookie("maps_suggestOnOff",sw,{ path:'<?= MY_SESSION_PATH ?>', expires:365 });
	if (sw == 'off') {
		alt_sw = 'on';
	} else {
		alt_sw = 'off';
	}
	$("#suggest_"+sw).css("display","");
	$("#suggest_"+alt_sw).css("display","none");
	document.getElementById("address").focus();
}
$(document).ready(function(){
	$('#address').autocomplete('../index/google-suggest.php');
});
</script>
<a id="suggest_on" class="suggest_onoff" href="javascript:suggest('off');" style="color:#EACC8F;<?= $suggest_on ?>">●</a><a id="suggest_off" class="suggest_onoff" href="javascript:suggest('on');" style="color:#EACC8F;<?= $suggest_off ?>">○</a><input id="address" class="text" type="text" style="width:160px;" name="address" value="<?= $addr ?>"><button onclick="showAddress(form.address.value,'');return false;">検索</button><button onclick="clearMarker();return false;">マーカ削除</button><button onclick="zoomMarkerAll();return false;">マーカ全て</button>
	<label><input id="cb_path" type="checkbox" value="on" onclick="LinePathOnOff()" style="margin-left:3px;">距離</label><input type="text" id="lineLength" style="width:50px;">m<input onclick="clearLinePath();" type="button" value="ｸﾘｱ">
	<label><input id="cb_pr" type="checkbox" value="on" onclick="plotRouteOnOff()" style="margin-left:3px;">ルート表示</label>
	<select id="travel_mode" onChange="travelModeSelect()">
		<option value="d">車(有料有)
		<option value="t"<?php if ($_COOKIE['google_maps_TravelMode'] == 't') echo ' selected'; ?>>車(有料無)
		<option value="w"<?php if ($_COOKIE['google_maps_TravelMode'] == 'w') echo ' selected'; ?>>徒歩
	</select>
	<label><input id="cb_sv" type="checkbox" value="on" onclick="StreetViewOnOff()" style="margin-left:3px;">ストリートビュー</label>
	<select id="places">
		<option value="<?= SEKAI_ISAN_CATEGORY_ID ?>"<?= ($place_type == SEKAI_ISAN_CATEGORY_ID) ? ' selected' : '' ?>>世界遺産</option>
		<option value="<?= SAKURA_MEISHO_CATEGORY_ID ?>"<?= ($place_type == SAKURA_MEISHO_CATEGORY_ID) ? ' selected' : '' ?>>日本桜名木</option>
		<option value="<?= TETSUDO_EKI_CATEGORY_ID ?>"<?= ($place_type == TETSUDO_EKI_CATEGORY_ID) ? ' selected' : '' ?>>日本鉄道駅</option>
		<option value="<?= HYAKUMEIZAN_CATEGORY_ID ?>"<?= ($place_type == HYAKUMEIZAN_CATEGORY_ID) ? ' selected' : '' ?>>日本百名山</option>
		<optgroup label="日本百名山▼">
		<?php
			$kubun_tbl = array("百名山", "二百名山", "三百名山");
			foreach ($kubun_tbl as $kubun) {
				$url_name = HYAKUMEIZAN_CATEGORY_ID.':'.$kubun;
		?>
			<option value="<?= $url_name ?>"<?= ($place_type == $url_name) ? ' selected' : '' ?>><?= $kubun ?></option>
		<?php
			}
		?>
		</optgroup>
		<option value="<?= HYAKUSEN_CATEGORY_ID ?>"<?= ($place_type == HYAKUSEN_CATEGORY_ID) ? ' selected' : '' ?>>日本百選</option>
		<optgroup label="日本百選▼">
		<?php
			$con = my_mysql_connect(_DB_SCHEMA_abook);
			$sql = "select distinct c_memo,c_markericon from m_abook where id_category = ".HYAKUSEN_CATEGORY_ID." order by c_memo";
			$rs = my_mysql_query($sql);
			while ($rec=mysql_fetch_array($rs)) {
				$url_name = HYAKUSEN_CATEGORY_ID.':'.urlencode($rec['c_memo']);
		?>
			<option value="<?= $url_name ?>"<?= ($place_type == $url_name) ? ' selected' : '' ?>><?= my_htmlspecialchars(str_replace('・','',str_replace('人と自然が織りなす風景','人と自然',str_replace('百選','',str_replace('100選','',str_replace('ふるさといきもの','いきもの',str_replace('全国','',str_replace('日本','',str_replace('日本の','',$rec['c_memo']))))))))) ?></option>
		<?php
			}
			$con = mysql_close($con);
		?>
		</optgroup>
<?php
	$pre_place = '';
	foreach ($place_tbl as $place) {
		if ($place[0] <> $pre_place) {
?>
		<optgroup label="<?= $place[0] ?>">
<?php
		}
		$pre_place = $place[0];
?>
		<option value="<?= $place[1] ?>"<?= ($place_type == $place[1]) ? ' selected' : '' ?>><?= $place[2] ?></option>
<?php
	}
?>
	</select><button onclick="PlacesSearch();return false;">探す</button><button onclick="clearPlacesMarker();return false;">ｸﾘｱ</button>
	<label><input type="checkbox" value="on" onclick="PanoramioOnOff(this)" style="margin-left:3px;">写真</label><span id="panoramio_opt" style="display: none;"><input id="tag" type="textbox" value="" style="width:60px;">
	<input type="button" value="タグ絞込" onclick="getTaggedPhotos()"><input type="button" value="リセット" onclick="resetTaggedPhotos()"></span>
</form>
<div id="map_canvas"></div>
<div id="side_bar" style="display:none;"></div>
<div id="route_navi" style="display:none;">
<div id="route_navi_close"><a href="javascript:route_naviOff()">×</a> <a href="javascript:route_naviOff()">ルートナビを閉じる</a><br></div>
<span id="route_all_time"></span><br>
</div>
<div id="route_navi_open" style="display:none;"><a href="javascript:route_naviOn()">▽</a></div>
<div id="panorama" style="display:none;">
人形マークを、道路上にドラッグ＆ドロップしてください。
<a href="javascript:StreetViewOff()">閉じる</a><br>
<div id="panowin"></div></div>
<script>
function route_naviOff() {
	$("#route_navi").css("display","none");
	$("#route_navi_open").css("display","");
}
function route_naviOn() {
	$("#route_navi_open").css("display","none");
	$("#route_navi").css("display","");
}
</script>
</body>
</html>
