<?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_API_KEY")) {
		define("GOOGLE_API_KEY", "ABQIAAAA1XbMiDxx_BTCY2_FkPh06RRaGTYH6UMl8mADNa0YKuWNNa8VNxQEerTAUcfkyrr6OwBovxn7TDAH5Q");
	}
	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 src="http://www.google.com/jsapi?key=<?= GOOGLE_API_KEY ?>"></script>
<script type="text/javascript">
$(function() {
	init();
});
google.load("maps", "2.x");
var map;
var ge;
var geocoder = null;
var myListener;
var notFound = '';
var newicon;
var micon = [];
var gmarkers = [];
var markerCnt = 0;
var new_markers = [];
var new_markerCnt = 0;
var editor = [];
var listener = [];
var side_bar_ul = [];
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 init() {
	setHeightPercent('map_canvas', <?= MAPS_FIX_HEIGHT ?>);
	map = new GMap2(document.getElementById('map_canvas'));
<?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'] ?>] = new GIcon();
	micon[<?= $rec['id_markertype'] ?>].image = "<?= DIARY_MAPS_ICON_FOLDER ?><?= $rec['c_markericon'] ?>";
	micon[<?= $rec['id_markertype'] ?>].shadow = "<?= DIARY_MAPS_ICON_FOLDER ?>msmarker.shadow.png";
	micon[<?= $rec['id_markertype'] ?>].iconSize = new GSize(32,32);
	micon[<?= $rec['id_markertype'] ?>].shadowSize = new GSize(59,32);
	micon[<?= $rec['id_markertype'] ?>].iconAnchor = new GPoint(16,32);
	micon[<?= $rec['id_markertype'] ?>].infoWindowAnchor = new GPoint(16,0);
<?php
	}
?>
	newicon = new GIcon();
	newicon.image = "<?= DIARY_MAPS_ICON_FOLDER ?>yellow-dot.png";
	newicon.shadow = "<?= DIARY_MAPS_ICON_FOLDER ?>msmarker.shadow.png";
	newicon.iconSize = new GSize(32,32);
	newicon.shadowSize = new GSize(59,32);
	newicon.iconAnchor = new GPoint(16,32);
	newicon.infoWindowAnchor = new GPoint(16,0);

	var mapui = map.getDefaultUI();
	mapui.maptypes.physical = true;
	map.setUI(mapui);
	map.addMapType(G_SATELLITE_3D_MAP);
	GEvent.addListener(map, 'maptypechanged', function() {
		if (ge) return;
		map.getEarthInstance(function(pluginInstance) {
			ge = pluginInstance;
		});
	});
<?php	if ($mode == 'edit') { ?>
	GEvent.addListener(map, "dragend", function() {
		moveMapCenter();
	});
	GEvent.addListener(map, "zoomend", function() {
		moveMapCenter();
	});
<?php	} ?>
	geocoder = new GClientGeocoder();
	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') { ?>
	GEvent.addListener(map, "click", function(overlay, latlng) {
		if (latlng) {
			addNewIcon(latlng, '');
		}
	});
<?php	} ?>
<?php	if ($multi_id <> '') { ?>
	zoomMarkerAll();
<?php	} else { ?>
	<?php	if ($centerLat <> '') { ?>
	var latlng = new GLatLng(<?= $centerLat ?>, <?= $centerLng ?>);
	map.setCenter(latlng, <?= $zoomLevel ?>);
	<?php	} ?>
<?php	} ?>
}
function addNewIcon(latlng, place) {
	var new_markerIx = new_markerCnt;
	new_markerCnt++;
	new_markers[new_markerIx] = new GMarker(latlng, {icon:newicon, draggable:true});
	myListener = GEvent.addListener(new_markers[new_markerIx], "click", function() {
		var markerIx = markerCnt;
		var html = '<form method="post" onsubmit="newMarkerCreate('+new_markerIx+','+markerIx+',this.place.value,this.comment.value);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="5" wrap="soft"></textarea></td></tr><tr><td></td><td><input type="submit" value="登録" /></td></tr></table></form>';
		html += '<form name="delete" method="post" onsubmit="cancelMarker('+new_markerIx+');return false">' +
	 'マーカーをキャンセル:&nbsp;<input type="submit" value="キャンセル" />' +
	 '</form>';
		new_markers[new_markerIx].openInfoWindow(html);
	});
	map.addOverlay(new_markers[new_markerIx]);
}
function newMarkerCreate(new_markerIx, markerIx, place, comment) {
	if (place=="") return;
	var latlng = new_markers[new_markerIx].getLatLng();
	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].getLatLng();
			id = httpObj.responseText;
			chgmark = createMarker(latlng, place, comment, 0, id, markerIx, '')
			map.addOverlay(chgmark);
			sideBarCreateView(markerIx+1);
		}
	);
	new_markers[new_markerIx].closeInfoWindow();
	map.removeOverlay(new_markers[new_markerIx]);
	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) {
	listener[markerIx] = GEvent.addListener(marker, "click", function() {
		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 > 100) {
			html += comment.slice(0,100).replace(/\n/ig,"<br>") + '<br>.....<br>';
		} else {
			html += comment.replace(/\n/ig,"<br>") + '<br><br>';
		}
		html += '</div>';
		editor[markerIx] = '<form method="post" onsubmit="editMarker('+markerIx+','+id+',this.place'+id+'.value,this.comment'+id+'.value);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="5" wrap="soft">'+comment.replace(/<br>/gi,"\n")+'</textarea></td></tr><tr><td></td><td><input type="submit" value="修正" /></td></tr></table></form>';
		editor[markerIx] += '<form name="delete" method="post" onsubmit="removeMarker('+markerIx+','+id+');return false">' + 'マーカーを削除:&nbsp;<input type="submit" value="削除" />' + '</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].getLatLng();
			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].getLatLng();
			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	} ?>
		map.openInfoWindowHtml(latlng, html);
	});
}
function editMarker(markerIx, id, place, comment) {
	var d = new Date();	// キャッシュを利用されないため
	$.post("marker-update.php?time="+d.getTime().toString(), {id:id,place:place,comment:comment});
	gmarkers[markerIx].closeInfoWindow();
	$("#side"+markerIx).html(place);
	GEvent.removeListener(listener[markerIx]);
	var latlng = gmarkers[markerIx].getLatLng();
	createListener(gmarkers[markerIx], latlng, place, comment, id, markerIx, '');
}
function cancelMarker(new_markerIx) {
	map.removeOverlay(new_markers[new_markerIx]);
}
function removeMarker(markerIx,id) {
	map.removeOverlay(gmarkers[markerIx]);
	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) {
	gmarkers[i].openInfoWindowHtml(editor[i]);
}
function myClick(i) {
	GEvent.trigger(gmarkers[i], "click");
}
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"];
			var latlng = new GLatLng(lat, lng);
			if (maxLat < lat) maxLat = lat;
			if (minLat > lat) minLat = lat;
			if (maxLng < lng) maxLng = lng;
			if (minLng > lng) minLng = lng;
			map.addOverlay(createMarker(latlng, place, comment, mtype, id, ix, mdate));
		}
		bounds = new GLatLngBounds(new GLatLng(minLat,minLng), new GLatLng(maxLat,maxLng));
		zoomlevel = map.getBoundsZoomLevel(bounds);
		if (zoomlevel > 15) zoomlevel = 15;
		map.setCenter(bounds.getCenter(), zoomlevel);
		sideBarCreateView(cnt);
	}
}
function createMarker(latlng, place, comment, mtype, id, markerIx, mdate) {
<?php	if ($mode == 'edit') { ?>
	var marker = new GMarker(latlng, {icon:micon[mtype], draggable:true});
<?php	} else { ?>
	var marker = new GMarker(latlng, {icon:micon[mtype], draggable:false});
<?php	} ?>
	createListener(marker, latlng, place, comment, id, markerIx, mdate);
	gmarkers[markerCnt] = marker;
	addSideBarItem(markerCnt, place);
	markerCnt++;
<?php	if ($mode == 'edit') { ?>
	GEvent.addListener(marker, "dragend", function() {
		var p = marker.getLatLng();
		lat = p.lat();
		lng = p.lng();
		var d = new Date();	// キャッシュを利用されないため
		$.get("marker-move.php?time="+d.getTime().toString(), {id:id,lat:lat,lng:lng});
		GEvent.removeListener(listener[markerIx]);
		var latlng = gmarkers[markerIx].getLatLng();
		createListener(gmarkers[markerIx], latlng, place, comment, id, markerIx, '');
	});
<?php	} ?>
	return marker;
}
function showAddress(address) {
	if (geocoder) {
		geocoder.getLatLng(
			address,
			function(latlng) {
				if (!latlng) {
					alert(address + " が見つかりません");
				} else {
<?php	if ($mode == 'edit') { ?>
					addNewIcon(latlng, address);
<?php	} ?>
					map.setCenter(latlng, <?= $zoom ?>);
				}
			}
		);
	}
}
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].getLatLng();
			lat = latlng.lat();
			lng = latlng.lng();
			if (maxLat < lat) maxLat = lat;
			if (minLat > lat) minLat = lat;
			if (maxLng < lng) maxLng = lng;
			if (minLng > lng) minLng = lng;
		}
	}
	bounds = new GLatLngBounds(new GLatLng(minLat,minLng), new GLatLng(maxLat,maxLng));
	zoomlevel = map.getBoundsZoomLevel(bounds);
	zoomlevel--;		// 1レベル拡大
	if (zoomlevel > 15) zoomlevel = 15;
	map.setCenter(bounds.getCenter(), zoomlevel);
	$("#c_mapCenterLat").val(map.getCenter().lat());
	$("#c_mapCenterLng").val(map.getCenter().lng());
	$("#c_mapZoomLevel").val(map.getZoom());
}
var streetview = '';
var svOverlay;
function StreetViewOnOff() {
	if (streetview == '') {
		StreetViewOn();
	} else {
		StreetViewOff();
	}
}
function StreetViewOn() {
	map.getDragObject().setDraggableCursor("default");
	$("#panorama").css("display","");
	$("#side_bar").css("height","35%");
	var myPano = new GStreetviewPanorama(document.getElementById("panorama"));
	//	GEvent.addListener(myPano, "error", handleNoFlash);
	svOverlay = new GStreetviewOverlay();
	map.addOverlay(svOverlay);
	GEvent.addListener(map, "click", function(overlay,latlng) {
		myPano.setLocationAndPOV(latlng);
	});
	streetview = 'on';
}
function StreetViewOff() {
	map.removeOverlay(svOverlay);
	$("#panorama").css("display","none");
	$("#side_bar").css("height","70%");
	map.getDragObject().setDraggableCursor("pointer");
	streetview = '';
	$("#cb_sv").attr("checked", false);
}
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;
	}
}
function plotRouteView() {
<?php	if ($mode == 'full') { ?>
	$("#map_canvas").css("margin-left","220px");
	width = (screen.availWidth - 220) * 100 / screen.availWidth;
	$("#map_canvas").css("width",width+"%");
	directions = new GDirections(map, document.getElementById("route_navi"));
	$("#route_navi").css("display","");
<?php	} else { ?>
	directions = new GDirections(map);
<?php	} ?>
	for (ix=0; ix<markerCnt; ix++) {
		if (gmarkers[ix] != null) {
			var latlng = gmarkers[ix].getLatLng();
			coordinates_element = latlng.lat() + "," + latlng.lng();
			coordinates.push(coordinates_element);
		}
	}
	if (coordinates.length > 1) {
		if ($("#travel_mode").val() == "w") {
			var option = {preserveViewport:true, travelMode:G_TRAVEL_MODE_WALKING};
		} else {
			var option = {preserveViewport:true, travelMode:G_TRAVEL_MODE_DRIVING};
		}
		directions.loadFromWaypoints(coordinates, option);
	}
}
function plotRouteClear() {
<?php	if ($mode == 'full') { ?>
	$("#map_canvas").css("margin-left","0px");
	$("#map_canvas").css("width","100%");
	$("#route_navi").css("display","none");
<?php	} ?>
	directions.clear();
	directions = null;
}
function handleNoFlash(errorCode) {
	if (errorCode == FLASH_UNAVAILABLE) {
		alert("Error: Flash doesn't appear to be supported by your browser");
		return;
	}
}
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:2px;">クリア</button>
	<button onclick="zoomMarkerAll(); return false" style="margin-left:2px;">マーカー全て表示</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:2px;">リセット</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>
</div>
</div>
<?php
}
?>
<?php
function quote_chg($str) {
	return str_replace("\r",'',ins_br(my_htmlspecialchars(str_replace("'", '’', $str))));
}
?>
