<?php
function google_map_multi($multi_id, $mode='view') {
	google_map_view(0, '', '', '', '', $mode, $multi_id);
}
function google_map_view($id, $centerLat, $centerLng, $zoomLevel, $mapHeight='', $mode='view', $multi_id='') {
	if ($multi_id == '' and $mode == 'view' and $centerLat == 0 and $centerLng == 0 and $zoomLevel == 0) {
		return;
	}
	if (!defined("GOOGLE_MAPS_EARTH_ZOOM")) {
		define("GOOGLE_MAPS_EARTH_ZOOM", 15);
	}
	if (!defined("MAPS_FIX_HEIGHT")) {
		define("MAPS_FIX_HEIGHT", 0);
	}
	if ($_GET['zoom'] <> '') {
		$zoom = $_GET['zoom'];
	} else {
		$zoom = GOOGLE_MAPS_EARTH_ZOOM;
	}
?>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var geocoder = null;
var newicon;
var shadowicon;
var micon = [];
var gmarkers = [];
var markerCnt = 0;
var new_markers = [];
var new_markerCnt = 0;
var editor = [];
var listener = [];
var side_bar_ul = [];
var current_infowin = null;
var directionsService = new google.maps.DirectionsService();
$(function() {
	initialize();
});
function setHeightPercent(elementID, fixHeight) {
	// マップの高さ設定
	if (document.all) {	// IE
		fixHeight += 5;
	}
<?php	if ($mode == 'full') { ?>
	mapsWinHeight = 90 - Math.ceil( fixHeight * 90 / screen.availHeight );
<?php	} else { ?>
	mapsWinHeight = 100 - Math.ceil( fixHeight * 100 / screen.availHeight );
<?php	} ?>
	document.getElementById(elementID).style.height = mapsWinHeight + "%";
}
function initialize() {
	setHeightPercent('map_canvas', <?= MAPS_FIX_HEIGHT ?>);
	geocoder = new google.maps.Geocoder();
	var myOptions = {
		zoom: 15,
		center: new google.maps.LatLng(35.6813820, 139.7660840),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		disableDoubleClickZoom: true,
<?php	if ($mode == 'full') { ?>
		streetViewControl: true
<?php	} else { ?>
		streetViewControl: false
<?php	} ?>
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
	$sql = "select * from r_markertype";
	$rs = my_mysql_query($sql);
	$row = mysql_num_rows($rs);
	while ($rec=mysql_fetch_array($rs)) {
?>
	micon[<?= $rec['id_markertype'] ?>] = "<?= DIARY_MAPS_ICON_FOLDER ?><?= $rec['c_markericon'] ?>";
<?php
	}
?>
	newicon = "<?= DIARY_MAPS_ICON_FOLDER ?>yellow-dot.png";
	shadowicon = "<?= DIARY_MAPS_ICON_FOLDER ?>msmarker.shadow.png";
<?php	if ($mode == 'edit') { ?>
	google.maps.event.addListener(map, "dragend", function() {
		moveMapCenter();
	});
	google.maps.event.addListener(map, "zoom_changed", function() {
		moveMapCenter();
	});
<?php	} ?>
	maxLat = -999;
	minLat = 999;
	maxLng = -999;
	minLng = 999;
	var vpoint = Array();
<?php
	if ($multi_id <> '') {
		$sql = "select * from v_marker where id_account = '".$_SESSION['current_id']."' and c_delete = 0";
		$sql .= " and id_schedule in (".$multi_id.") order by c_mdate, id_schedule, c_order, id_marker";
	} else {
		$sql = "select * from v_marker where id_account = '".$_SESSION['current_id']."' and c_delete = 0";
		$sql .= " and id_schedule = ".$id." order by c_order, id_marker";
	}
	$rs = my_mysql_query($sql);
	$row = mysql_num_rows($rs);
	$adr_cnt = 0;
	if ($row > 0) {
		while ($rec=mysql_fetch_array($rs)) {
?>
	vpoint[<?= $adr_cnt ?>] = Array();
	vpoint[<?= $adr_cnt ?>]["place"] = '<?= quote_chg($rec['c_place']) ?>';
	vpoint[<?= $adr_cnt ?>]["comment"] = '<?= quote_chg($rec['c_comment']) ?>';
	vpoint[<?= $adr_cnt ?>]["lat"] = <?= $rec['c_lat'] ?>;
	vpoint[<?= $adr_cnt ?>]["lng"] = <?= $rec['c_lng'] ?>;
	vpoint[<?= $adr_cnt ?>]["id"] = <?= $rec['id_marker'] ?>;
	vpoint[<?= $adr_cnt ?>]["mtype"] = <?= $rec['id_markertype'] ?>;
<?php	if ($rec['c_mdate'].'' <> '') { ?>
	vpoint[<?= $adr_cnt ?>]["date"] = '<?= date_from_mysql("Y-m-d", $rec['c_mdate']) ?>';
<?php	} else {?>
	vpoint[<?= $adr_cnt ?>]["date"] = '';
<?php	} ?>
<?php
			++$adr_cnt;
		}
	}
?>
	showMarker(vpoint, <?= $adr_cnt ?>);
<?php	if ($mode == 'edit') { ?>
	newIconListenerSet();
<?php	} ?>
<?php	if ($multi_id <> '') { ?>
	zoomMarkerAll();
<?php	} else { ?>
	<?php	if ($centerLat <> '') { ?>
	var latlng = new google.maps.LatLng(<?= $centerLat ?>, <?= $centerLng ?>);
	map.setCenter(latlng);
	map.setZoom(<?= $zoomLevel ?>);
	<?php	} ?>
<?php	} ?>
}
function newIconListenerSet() {
	google.maps.event.addListener(map, 'click', function(event) {
		addNewIcon(event.latLng, '');
	});
}
function showMarker(vpoint, cnt) {
	if (geocoder) {
		for (var ix=0; ix<cnt; ix++) {
			var lat = vpoint[ix]["lat"];
			var lng = vpoint[ix]["lng"];
			var place = vpoint[ix]["place"];
			var comment = vpoint[ix]["comment"];
			var mtype = vpoint[ix]["mtype"];
			var id = vpoint[ix]["id"];
			var mdate = vpoint[ix]["date"];
			if (maxLat < lat) maxLat = lat;
			if (minLat > lat) minLat = lat;
			if (maxLng < lng) maxLng = lng;
			if (minLng > lng) minLng = lng;
			var latlng = new google.maps.LatLng(lat, lng);
			createMarker(latlng, place, comment, mtype, id, ix, mdate);
		}
		southWest = new google.maps.LatLng(minLat,minLng);
		northEast = new google.maps.LatLng(maxLat,maxLng);
		bounds = new google.maps.LatLngBounds(southWest,northEast);
		sideBarCreateView(cnt);
	}
}
function createMarker(latlng, place, comment, mtype, id, markerIx, mdate) {
<?php	if ($mode == 'edit') { ?>
	draggable = true;
<?php	} else { ?>
	draggable = false;
<?php	} ?>
	var image = new google.maps.MarkerImage(micon[mtype],
		new google.maps.Size(32, 37),
		new google.maps.Point(0, 0),
		new google.maps.Point(16, 32));
	var shadow = new google.maps.MarkerImage(shadowicon,
		new google.maps.Size(59, 32),
		new google.maps.Point(0, 0),
		new google.maps.Point(16, 32));
	var marker = new google.maps.Marker({
		position: latlng,
		map: map,
		shadow: shadow,
		icon: image,
		title: place,
		draggable: draggable
	});
	createListener(marker, latlng, place, comment, id, markerIx, mdate);
	gmarkers[markerCnt] = marker;
	addSideBarItem(markerCnt, place);
	markerCnt++;
<?php	if ($mode == 'edit') { ?>
	google.maps.event.addListener(marker, "dragend", function() {
		var p = marker.position;
		lat = p.lat();
		lng = p.lng();
		var d = new Date();	// キャッシュを利用されないため
		$.get("marker-move.php?time="+d.getTime().toString(), {id:id,lat:lat,lng:lng});
		google.maps.event.removeListener(listener[markerIx]);
		var latlng = gmarkers[markerIx].position;
		createListener(gmarkers[markerIx], latlng, place, comment, id, markerIx, '');
	});
<?php	} ?>
	return marker;
}
function myClick(markerCnt) {
	google.maps.event.trigger(gmarkers[markerCnt], 'click');
}
function addNewIcon(latlng, place) {
	if (current_infowin) {
		current_infowin.close();
		current_infowin = null;
	}
	var new_markerIx = new_markerCnt;
	new_markerCnt++;
	var image = new google.maps.MarkerImage(newicon,
		new google.maps.Size(32, 32),
		new google.maps.Point(0, 0),
		new google.maps.Point(16, 32));
	var shadow = new google.maps.MarkerImage(shadowicon,
		new google.maps.Size(59, 32),
		new google.maps.Point(0, 0),
		new google.maps.Point(16, 32));
	new_markers[new_markerIx] = new google.maps.Marker({
		position: latlng,
		map: map,
		shadow: shadow,
		icon: image,
		title: place,
		draggable: true
	});
	var markerIx = markerCnt;
	var html = '<form method="post" onsubmit="newMarkerCreate('+new_markerIx+','+markerIx+');return false" onreset="cancelMarker('+new_markerIx+');return false"><table><tr><td align="right">地名:&nbsp;</td><td><input id="place" name="place" type="text" size="22" value="'+place+'"/></td></tr><tr><td align="right">コメント:&nbsp;</td><td><textarea id="comment" name="comment" cols="50" rows="4" wrap="soft"></textarea></td></tr><tr><td></td><td><input type="submit" value="登録" />マーカーをキャンセル:&nbsp;<input type="reset" value="キャンセル" /></form>';
	var infowindow = new google.maps.InfoWindow({
		content: html
	});
	google.maps.event.addListener(new_markers[new_markerIx], 'click', function() {
		infowindow.open(map,new_markers[new_markerIx]);
		current_infowin = infowindow;
	});
}
function newMarkerCreate(new_markerIx, markerIx) {
	var place = $("#place").val();
	if (place=="") return;
	var comment = $("#comment").val();
	var latlng = new_markers[new_markerIx].position;
	var lat = latlng.lat();
	var lng = latlng.lng();
	var d = new Date();	// キャッシュを利用されないため
	var httpObj = $.post("marker-add.php?time="+d.getTime().toString(), {pid:<?= $id ?>,lat:lat,lng:lng,place:place,comment:comment},
		function(data){
			var latlng = new_markers[new_markerIx].position;
			id = httpObj.responseText;
			chgmark = createMarker(latlng, place, comment, 0, id, markerIx, '')
			sideBarCreateView(markerIx+1);
		}
	);
	newIconListenerSet();
	current_infowin.close();
	current_infowin = null;
	moveMapCenter();
}
function moveMapCenter(){
	var latlng = map.getCenter();
	var zoomlevel = map.getZoom();
	$("#c_mapCenterLat").val(latlng.lat());
	$("#c_mapCenterLng").val(latlng.lng());
	$("#c_mapZoomLevel").val(zoomlevel);
//	var d = new Date();	// キャッシュを利用されないため
//	$.get("mapcenter-move.php?time="+d.getTime().toString(), {id:<?= $id ?>,lat:latlng.lat(),lng:latlng.lng(),zoom:zoomlevel});
}
function addSideBarItem(markerIx, place) {
	side_bar_ul[markerIx] = '<li id="sideLi'+markerIx+'"><a id="side'+markerIx+'" href="javascript:myClick(' + markerIx + ')">' + place + '</a></li>';
}
function sideBarCreateView(markerIx) {
	var side_bar_html = '';
	for (ix=0; ix<markerIx; ix++) {
		side_bar_html += side_bar_ul[ix];
	}
	if (side_bar_html == '') {
		$("#side_bar").html("<p>マーカー追加してください。</p>");
	} else {
		$("#side_bar").html("<ul>"+side_bar_html+"</ul>");
	}
}
function createListener(marker, latlng, place, comment, id, markerIx, mdate) {
	html = '';
	if (mdate != '') {
		html += '<font color=#ff0000>【<b>'+mdate+'</b>】</font><br>';
	}
	html += '<font color=#000080>≪<b>'+place+'</b>≫</font><br><div style="width:200px;">';
	if (comment.length > 50) {
		html += comment.slice(0,50).replace(/\n/ig,"<br>") + '.....<br>';
	} else {
		html += comment.replace(/\n/ig,"<br>") + '<br>';
	}
	html += '</div>';
	editor[markerIx] = '<form method="post" onsubmit="editMarker('+markerIx+','+id+');return false" onreset="removeMarker('+markerIx+','+id+');return false"><table><tr><td align="right">地名:&nbsp;</td><td><input id="place'+id+'" name="place'+id+'" type="text" size="22" value="'+place+'" /></td></tr><tr><td align="right">コメント:&nbsp;</td><td><textarea id="comment'+id+'" name="comment'+id+'" cols="50" rows="4" wrap="soft">'+comment.replace(/<br>/gi,"\n")+'</textarea></td></tr><tr><td></td><td><input type="submit" value="修正" />マーカーを削除:&nbsp;<input type="reset" value="削除" /></td></tr></table></form>';
<?php	if ($mode == 'edit') { ?>
	html = html + "<br><a href='javascript:openEditWindow("+markerIx+")'>編集</a>";
<?php	} else { ?>
	html = html + '<a href="http://maps.google.com/maps?q=' + latlng.lat() + ',' + latlng.lng() + '" target="_blank">Googleマップ</a>';
	if (markerIx != 0) {
		var ll = gmarkers[markerIx-1].position;
		html = html + '&nbsp;&nbsp;<a href="http://maps.google.com/maps?saddr=' + ll.lat() + ',' + ll.lng() + '&daddr=' + latlng.lat() + ',' + latlng.lng() + '" target="_blank">前地点からの経路</a>';
	} else if (markerCnt > 1) {
		var ll = gmarkers[1].position;
		html = html + '&nbsp;&nbsp;<a href="http://maps.google.com/maps?saddr=' + latlng.lat() + ',' + latlng.lng() + '&daddr=' + ll.lat() + ',' + ll.lng() + '" target="_blank">次地点への経路</a>';
	}
<?php	} ?>
	var infowindow = new google.maps.InfoWindow({
		content: html
	});
	listener[markerIx] = google.maps.event.addListener(marker, 'click', function() {
		if (current_infowin) {
			current_infowin.close();
		}
		infowindow.open(map,marker);
		current_infowin = infowindow;
	});
}
function editMarker(markerIx, id) {
	var place = $("#place"+id).val();
	if (place=="") return;
	var comment = $("#comment"+id).val();
	var d = new Date();	// キャッシュを利用されないため
	$.post("marker-update.php?time="+d.getTime().toString(), {id:id,place:place,comment:comment});
	current_infowin.close();
	current_infowin = null;
	$("#side"+markerIx).html(place);
	gmarkers[markerIx].setTitle(place);
	google.maps.event.removeListener(listener[markerIx]);
	var latlng = gmarkers[markerIx].position;
	createListener(gmarkers[markerIx], latlng, place, comment, id, markerIx, '');
}
function cancelMarker(new_markerIx) {
	if (current_infowin) {
		current_infowin.close();
		current_infowin = null;
	}
	new_markers[new_markerIx].setMap(null);
}
function removeMarker(markerIx,id) {
	current_infowin.close();
	current_infowin = null;
	gmarkers[markerIx].setMap(null);
	gmarkers[markerIx] = null;
	$("#sideLi"+markerIx).css("display","none");
	side_bar_ul[markerIx] = "";
	side_bar_on = 0;
	for (ix=0; ix<markerCnt; ix++) {
		if (side_bar_ul[ix] != "") {
			side_bar_on = 1;
		}
	}
	if (side_bar_on == 0) {
		$("#side_bar").html("<p>マーカー追加してください。</p>");
	}
	var d = new Date();	// キャッシュを利用されないため
	$.get("marker-delete.php?time="+d.getTime().toString(), {id:id});
}
function openEditWindow(i) {
	var infowindow = new google.maps.InfoWindow({
		content: editor[i]
	});
	if (current_infowin) {
		current_infowin.close();
	}
	infowindow.open(map,gmarkers[i]);
	current_infowin = infowindow;
}
function showAddress(address) {
	if (geocoder) {
		geocoder.geocode( { 'address': address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				position = results[0].geometry.location;
				map.setCenter(position);
<?php	if ($mode == 'edit') { ?>
				addNewIcon(position, address);
<?php	} ?>
			} else {
				alert(address + " が見つかりません。status: " + status);
			}
		});
	}
}
function addressClear() {
	document.getElementById("address").value = '';
}
function zoomMarkerAll() {
	maxLat = -999;
	minLat = 999;
	maxLng = -999;
	minLng = 999;
	for (ix=0; ix<markerCnt; ix++) {
		if (gmarkers[ix] != null) {
			var latlng = gmarkers[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);
	$("#c_mapCenterLat").val(map.getCenter().lat());
	$("#c_mapCenterLng").val(map.getCenter().lng());
	$("#c_mapZoomLevel").val(map.getZoom());
}
var streetviewWin = false;
var streetviewInit = false;
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;
	$("#side_bar").css("height","35%");
}
function StreetViewOff() {
	$("#panorama").css("display","none");
	streetviewWin = false;
	$("#cb_sv").attr("checked", false);
	$("#side_bar").css("height","70%");
}
var proute = null;
var coordinates = [];
var directions;
function travelModeSelect() {
	if (proute != null) {
		plotRouteClear();
		plotRouteView();
	}
}
function plotRouteOnOff() {
	if (proute == null) {
		plotRouteView();
		proute = 'on';
	} else {
		plotRouteClear();
		proute = null;
	}
}
var route_navi = false;
function plotRouteView() {
	if (route_navi) {
		directionsDisplay.setMap(null);
		directionsDisplay.setPanel(null);
	}
	directionsDisplay = new google.maps.DirectionsRenderer();
	directionsDisplay.setMap(map);
	route_navi = true;
<?php	if ($mode == 'full') { ?>
	directionsDisplay.setPanel(document.getElementById("route_navi"));
	$("#map_canvas").css("margin-left","220px");
	width = (screen.availWidth - 220) * 100 / screen.availWidth;
	$("#map_canvas").css("width",width+"%");
	$("#route_navi").css("display","");
<?php	} ?>
	var waypoints = [];
	for (ix=0; ix<markerCnt; ix++) {
		if (gmarkers[ix] != null) {
			var latlng = gmarkers[ix].position;
			waypoints.push({
				location:latlng,
				stopover:true
			});
		}
		if (ix == 0) {
			var start = latlng;
		} else if (ix+1 == markerCnt) {
			var end = latlng;
		}
	}
	if ($("#travel_mode").val() == "w") {
		var travelMode = google.maps.DirectionsTravelMode.WALKING;
	} else {
		var travelMode = google.maps.DirectionsTravelMode.DRIVING;
	}
	var request = {
		origin: start,
		destination: end,
		waypoints: waypoints,
		optimizeWaypoints: true,
		travelMode: travelMode
	};
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
		}
	});
}
function plotRouteClear() {
<?php	if ($mode == 'full') { ?>
	$("#map_canvas").css("margin-left","0px");
	$("#map_canvas").css("width","100%");
	$("#route_navi").css("display","none");
<?php	} ?>
	directionsDisplay.setMap(null);
}
function mapHeightChange() {
	$("#map_frame").css("height",$("#mapHeight").val());
	$("#c_mapHeight").val($("#mapHeight").val());
}
</script>
<form id="form" onsubmit="showAddress(this.address.value); return false">
<?php	if ($mode == 'view') { ?>
	<input id="address" class="text" type="text" name="address" value="" style="width:200px;">
<?php	} else { ?>
	<input id="address" class="text" type="text" name="address" value="" style="width:280px;">
<?php	} ?>
	<input type="submit" value="場所を検索" style="background-color: #e0e0e0;">
	<button onclick="addressClear(); return false" style="margin-left:0px;">クリア</button>
	<button onclick="zoomMarkerAll(); return false" style="margin-left:0px;">マーカー全て表示</button>
<?php	if ($mode == 'edit') { ?>
	高さ：<select id="mapHeight" onchange="mapHeightChange()">
	<?php
		$keyary = explode(",", DIARY_MAPS_FRAME_HEIGHT_SELECT);
		foreach ($keyary as $height) {
	?>
		<option value="<?= $height ?>"<?= $height == $mapHeight ? " selected" : "" ?>><?= $height ?>
	<?php
		}
	?>
		</select>
<?php	} ?>
<?php	if ($mode <> 'edit') { ?>
	<button onclick="location.reload(); return false" style="margin-left:0px;">リセット</button>
<?php	} ?>
<?php	if ($mode != 'edit') { ?>
	<?php	if ($mode == 'full') { ?>
	<select id="travel_mode" onChange="travelModeSelect()">
		<option value="d">車
		<option value="w">徒歩
	</select>
	<?php	} ?>
	<input id="cb_pr" type="checkbox" value="on" onclick="plotRouteOnOff()">ルート表示
<?php	} ?>
<?php	if ($mode == 'full') { ?>
	<input id="cb_sv" type="checkbox" value="on" onclick="StreetViewOnOff()">ストリートビュー
<?php	} ?>
<?php	if ($mode == 'view') { ?>
	<a href="maps-diary.php?id=<?= $id ?>&multi=<?= $multi_id ?>" target="_blank" style="margin-left:10px;">全画面表示</a>
<?php	} ?>
</form>
<?php
	if ($mode <> 'full') {
		if ($mapHeight == '') {
			$map_height = DIARY_MAPS_FRAME_HEIGHT;
		} else {
			$map_height = $mapHeight;
		}
	}
?>
<div id="map_frame" style="height:<?= $map_height ?>">
<div id="map_canvas"></div>
<div id="side_bar">Loading...</div>
<?php	if ($mode == 'full') { ?>
	<div id="route_navi" style="display:none;"></div>
<?php	} ?>
<div id="panorama" style="display:none;">
人形マークを、道路上にドラッグ＆ドロップしてください。
<a href="javascript:StreetViewOff()">閉じる</a><br>
<div id="panowin"></div></div>
</div>
<?php
}
?>
<?php
function quote_chg($str) {
	return str_replace("\r",'',ins_br(my_htmlspecialchars(str_replace("'", '’', $str))));
}
?>
