<?php
function maps_proc($http_arg, $item_tbl, $alone='') {
	$con = my_mysql_connect(_DB_SCHEMA);
?>
<div id="maps_filter">
<span id="mp_list_filter">
<script>
function SelectionCategory(form, sel, selname, arg_pool) {
	for (i = 0; i < sel.options.length; i++) {
		if (sel.options[i].selected == true) {
			window.location.href = "<?= $_SERVER['SCRIPT_NAME'] ?>?" + arg_pool + "&" + selname + "=" + encodeURL(sel.options[i].value);
		}
	}
}
function categoryReset(arg_pool) {
	window.location.href = "<?= $_SERVER['SCRIPT_NAME'] ?>?" + arg_pool;
}
</script>
<form method="POST" name="filter_form" action="<?= $_SERVER['SCRIPT_NAME'] ?>?<?= query_from_http_arg_pool($http_arg) ?>">
	<span class="mp_list_category_select">
<?php
	$item = array(	"表示名"=>"カテゴリ",	"列名"=>"id_category", "http_arg_GET名"=>"cat",
			"type"=>"select", "参照テーブル"=>"m_category", "参照テーブル表示列"=>"c_categoryName",
			"select_space"=>"Y",
			"参照テーブル表示順"=>"c_categoryDisplayOrder", "参照テーブル表示色"=>"c_categoryDisplayColor");
	// mp_list_filter_category_select($item, $http_arg[$item['http_arg_GET名']], $_SESSION['current_id'], $http_arg, '');
	filter_category_select($http_arg['cat'], $_SESSION['current_id'], $http_arg);	/* for calendar ( _my_calendar.php ) */
?>
	</span>
	<span id="mp_list_filter_key_select">
<?php
	mp_list_filter_key_select($http_arg['key'], $http_arg);
?>
	</span>
	<span id="mp_list_add_filter">
	<script>
	function CheckboxOnOff(onOff, arg_pool) {
		if (onOff == 'on') {
			window.location.href = "<?= $_SERVER['SCRIPT_NAME'] ?>?all=off&" + arg_pool;
		} else {
			window.location.href = "<?= $_SERVER['SCRIPT_NAME'] ?>?all=on&" + arg_pool;
		}
	}
	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);
	}
	function handleNoFlash(errorCode) {
		if (errorCode == FLASH_UNAVAILABLE) {
			alert("Error: Flash doesn't appear to be supported by your browser");
			return;
		}
	}
	</script>
	<label><input type="checkbox" style="margin-left: 10px;" value="on" onClick="CheckboxOnOff('<?= $_SESSION['schedule_maps_all'] ?>', '<?= query_from_http_arg_pool($http_arg, $omit_arg) ?>')"<?= $_SESSION['schedule_maps_all'] == 'on' ? ' checked' : '' ?>>全件表示</label>
	<? if ($alone == 'alone') { ?>
		<label><input id="cb_sv" type="checkbox" value="on" onclick="StreetViewOnOff()">ストリートビュー</label>
	<? } ?>
	</span>
</form>
</span>
<div id="mp_list_add_filter" class="block">
<?php
	add_my_filter($http_arg);
?>
</div>
</div>
<?php
	if ($http_arg['cat'] == '' && $http_arg['key'] == '' && $http_arg['selY'] == '' && $http_arg['selM'] == '' && $http_arg['selD'] == '' && $http_arg['toY'] == '' && $http_arg['toM'] == '' && $http_arg['toD'] == '' && $_SESSION['schedule_maps_all'] <> 'on') {
			echo "<script type='text/javascript'>function init(){}</script>\n";
			noramal_msg('件名に地図チェックが入っているスケジュールが対象です。',3);
			noramal_msg('検索条件を１つ以上指定してください。',1);
			noramal_msg('検索条件なしで全件表示する場合は、[全件表示]をチェックしてください。件数が多いと時間がかかります。',1);
	} else {
		$sel_filter[] = array("arg"=>'cat', "colname"=>'id_category', "data"=>$http_arg['cat']);
		$order_tbl[] = array();
		$add_where = add_where_create($http_arg);
		$sql = mp_list_sql_create($_SESSION['current_id'], 'v_schedule', $item_tbl, $order_tbl, '', $http_arg['key'], $sel_filter, 'yes', $add_where);
		$sql .= " and c_map = 1 and c_subject <> ''";
		$sql .= " order by c_subject, c_date desc";
		$rs = my_mysql_query_debug_print($sql);
		$row = mysql_num_rows($rs);
		if ($row <> 0) {
			google_maps($rs, $row, $alone);
		} else {
			echo "<script type='text/javascript'>function init(){}</script>\n";
			error_msg('該当するデータがありません。');
		}
		$con = mysql_close($con);
	}
}
?>
<?php
function google_maps($rs, $row, $alone) {
	if (!defined("GETLATLNG_SLEEP_TIME")) {
		define("GETLATLNG_SLEEP_TIME", 200000);	// 0.2秒
	}
?>
<script src="http://www.google.com/jsapi?key=<?= GOOGLE_API_KEY ?>"></script>
<script>
var map;
var ge;
var geocoder = null;
var maxLat=-999, minLat=999, maxLng=-999, minLng=999;
var notFound = '';
google.load("maps", "2.x");
function setHeightPercent(elementID, fixHeight) {
	// マップの高さ設定
	//if (document.all) {	// IE
	//	fixHeight += 40;
	//}
	mapsWinHeight = 100 - Math.ceil( fixHeight * 100 / screen.availHeight );
	document.getElementById(elementID).style.height = mapsWinHeight + "%";
}
function init() {
	setHeightPercent('map3d', <?= MAPS_FIX_HEIGHT ?>);
	map = new GMap2(document.getElementById('map3d'));
	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;
			doStuffWithEarth();
		});
	});
	geocoder = new GClientGeocoder();
	maxLat = -999;
	minLat = 999;
	maxLng = -999;
	minLng = 999;
	var vpoint = Array();
<?php
	$popstr = '';
	$address = '';
	$point_tbl = array();
	while ($rec=mysql_fetch_array($rs)) {
		if (($address <> '' and $address <> $rec['c_subject'])) {
			$point_tbl[] = array($address, $popstr);
			$popstr = '';
		}
		$popstr .= '<font color=#000080>【<b>'.date_from_mysql('Y/m/d',$rec['c_date']).'</b>】</font>';
		$popstr .= ' '.str_replace("'",'"',day_week_view($rec['c_date'],true)).'<br>';
		if ($rec['c_memo'] <> '') {
			$popstr .= str_replace("\r",'',str_replace("'","’",ins_br(strip_tags($rec['c_memo'])))).'<br>';
		}
		$address = $rec['c_subject'];
	}
	$point_tbl[] = array($address, $popstr);
	$adr_cnt = 0;
	foreach ($point_tbl as $point) {
		$status = getLatLng($point[0], $lat, $lng);
?>
	vpoint[<?= $adr_cnt ?>] = Array();
	vpoint[<?= $adr_cnt ?>]["address"] = '<?= $point[0] ?>';
	vpoint[<?= $adr_cnt ?>]["popstr"] = '<?= $point[1] ?>';
	vpoint[<?= $adr_cnt ?>]["lat"] = <?= $lat ?>;
	vpoint[<?= $adr_cnt ?>]["lng"] = <?= $lng ?>;
	vpoint[<?= $adr_cnt ?>]["status"] = <?= $status ?>;
<?php
		++$adr_cnt;
		usleep(GETLATLNG_SLEEP_TIME);
	}
?>
	showMarker(vpoint, <?= $adr_cnt ?>);
}
var side_bar_html = "";
var gmarkers = [];
var i = 0;
function createMarker(point, addr, popstr, lat, lng) {
	var marker = new GMarker(point);
	GEvent.addListener(marker, "click", function() {
		html = '<a href="http://maps.google.com/maps?q=' + encodeURL(addr);
		html += '" target="_blank">≪' + addr + '≫</a><br>';
		html += popstr;
		map.openInfoWindowHtml(point, html);
	});
	gmarkers[i] = marker;
	side_bar_html += '<li><a href="javascript:myClick(' + i + ')">' + addr + '</a></li>';
	i++;
	return marker;
}
function myClick(i) {
	GEvent.trigger(gmarkers[i], "click");
}
function showMarker(vpoint, cnt) {
	if (geocoder) {
		for (var ix=0; ix<cnt; ix++) {
			if (vpoint[ix]["status"] == 200) {
				var lat = vpoint[ix]["lat"];
				var lng = vpoint[ix]["lng"];
				var point = 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(point, vpoint[ix]["address"], vpoint[ix]["popstr"], lat, lng));
			} else {
				notFound += vpoint[ix]["address"] + '&nbsp;';
			}
		}
		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);
		document.getElementById('side_bar').innerHTML = "<ul>"+side_bar_html+"</ul>";
		document.getElementById('not_found').innerHTML = notFound;
	}
}
function doStuffWithEarth() {
	document.getElementById('installed-plugin-version').innerHTML = ge.getPluginVersion().toString();
}
function markerClear() {
	map.clearOverlays();
}
function addressClear() {
	document.getElementById("address").value = '';
}
function handleNoFlash(errorCode) {
	//if (errorCode == FLASH_UNAVAILABLE) {
	//	alert("Error: Flash doesn't appear to be supported by your browser");
		return;
	//}
}
</script>
<div id="map3d"></div>
<div id="side_bar">Loading...</div>
<div>Not found: <span id="not_found" style="color: red;"></span></div>
<div id="panorama" style="display:none;">
地図上の道路をクリックしてください。
<a href="javascript:StreetViewOff()">閉じる</a></div>
<div>Installed Plugin Version: <span id="installed-plugin-version" style="font-weight: bold;">Loading...</span></div>
<?php
}
function getLatLng($address, &$lat, &$lng) {
	$latLng = my_file_get_contents('http://maps.google.com/maps/geo?q='.urlencode($address).'&output=csv&sensor=false&key='.GOOGLE_API_KEY);
	$ary = explode(',', $latLng);
	$lat = $ary[2];
	$lng = $ary[3];
	return $ary[0];
}
?>
