<?php
function maps_proc($http_arg, $item_tbl, $alone='') {
	$con = my_mysql_connect(_DB_SCHEMA);
?>
<div id="maps_filter">
<span id="mp_list_filter" class="block_xxx">
<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 + "=" + URLencode(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, '');
?>
	</span>
	<span id="mp_list_filter_key_select" class="block_left_xxx">
<?php
	mp_list_filter_key_select($http_arg['key'], $http_arg);
?>
	</span>
	<span id="mp_list_add_filter" class="block_left_xxx">
	<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 streetviewWin = false;
	var streetviewInit = false;
/*	var position;	*/
	function StreetViewOnOff() {
		if (!streetviewWin) {
			StreetViewOn();
		} else {
			StreetViewOff();
		}
	}
	function StreetViewOn() {
		$("#panorama").css("display","");
		if (!streetviewInit) {
			var panoramaOptions = {
			/*	position: position,	*/
				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%");
	}
	</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()" style="margin-left:5px;">ストリートビュー</label>
		<label><input type="checkbox" value="on" onclick="PanoramioOnOff(this)" style="margin-left:5px;">写真</label>
<script>
function PanoramioOnOff(my) {
	if (my.checked) {
		panoramio.setMap(map);
	} else {
		panoramio.setMap(null);
	}
}
</script>
	<? } ?>
	</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 initialize(){}</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 initialize(){}</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://maps.google.com/maps/api/js?sensor=false&libraries=panoramio"></script>
<script src="../scripts/encodeURL.js"></script>
<script>
var map;
var geocoder = null;
var maxLat=-999, minLat=999, maxLng=-999, minLng=999;
var gmarkers = [];
var markerCnt = 0;
var notFound = '';
var side_bar_html = "";
var current_infowin = null;
function setHeightPercent(elementID, fixHeight) {
	// マップの高さ設定
	//if (document.all) {	// IE
	//	fixHeight += 40;
	//}
	mapsWinHeight = 100 - Math.ceil( fixHeight * 100 / screen.availHeight );
	document.getElementById(elementID).style.height = mapsWinHeight + "%";
}
var panoramioView = false;
var panoramio;
function initialize() {
	setHeightPercent('map_canvas', <?= MAPS_FIX_HEIGHT ?>);
	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+0 ?>;
	vpoint[<?= $adr_cnt ?>]["lng"] = <?= $lng+0 ?>;
	vpoint[<?= $adr_cnt ?>]["status"] = '<?= $status ?>';
<?php
		++$adr_cnt;
	//	usleep(GETLATLNG_SLEEP_TIME);
	}
?>
	geocoder = new google.maps.Geocoder();
	for (var ix=0; ix<<?= $adr_cnt ?>; ix++) {
		if (vpoint[ix]["status"] == 'OK') {
			var lat = vpoint[ix]["lat"];
			var lng = vpoint[ix]["lng"];
			if (maxLat < lat) maxLat = lat;
			if (minLat > lat) minLat = lat;
			if (maxLng < lng) maxLng = lng;
			if (minLng > lng) minLng = lng;
		}
	}
	if (minLat == maxLat && minLng == maxLng) {
		minLat -= 0.002;		// 1地点の場合、拡大されすぎるのを抑止するため
		minLng -= 0.002;		// initialize()時点では
		maxLat += 0.002;		// map.fitBounds()後にsetZoom()が効かないため
		maxLng += 0.002;		// Lat, Lngを調整してからfitBounds()する
	}
	southWest = new google.maps.LatLng(minLat,minLng);
	northEast = new google.maps.LatLng(maxLat,maxLng);
	bounds = new google.maps.LatLngBounds(southWest,northEast);
	var myOptions = {
		zoom: 15,
		center: new google.maps.LatLng(minLat + maxLat / 2, minLng + maxLng / 2),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		streetViewControl: true
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	panoramio = new google.maps.panoramio.PanoramioLayer();
	map.fitBounds(bounds);
	showMarker(vpoint, <?= $adr_cnt ?>);
}
function showMarker(vpoint, cnt) {
	for (var ix=0; ix<cnt; ix++) {
		if (vpoint[ix]["status"] == 'OK') {
			var lat = vpoint[ix]["lat"];
			var lng = vpoint[ix]["lng"];
			createMarker(vpoint[ix]["address"], vpoint[ix]["popstr"], lat, lng);
		} else {
			notFound += vpoint[ix]["address"] + '&nbsp;';
		}
	}
	document.getElementById('side_bar').innerHTML = "<ul>"+side_bar_html+"</ul>";
	document.getElementById('not_found').innerHTML = notFound;
}
function createMarker(addr, popstr, lat, lng) {
	html = '<a href="http://maps.google.com/maps?q=' + encodeURL(addr);
	html += '" target="_blank">≪' + addr + '≫</a><br>';
	html += popstr;
	var infowindow = new google.maps.InfoWindow({
		content: html
	});
	var latlng = new google.maps.LatLng(lat, lng);
/*
	var marker = new google.maps.Marker({
		position: latlng,
		map: map,
		title: addr
	});
*/
	var marker_label = zen2han(addr).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(8, 36);
	icon_s.scaledSize = new google.maps.Size(str_width(marker_label)*5+20, 28);
	var marker = new google.maps.Marker({
		position: latlng,
		map: map,
		title: addr,
		icon: icon_s
	});
	google.maps.event.addListener(marker, 'click', function() {
		if (current_infowin) {
			current_infowin.close();
		}
		infowindow.open(map,marker);
		current_infowin = infowindow;
	});
	gmarkers[markerCnt] = marker;
	side_bar_html += '<li><a href="javascript:myClick(' + markerCnt + ')">' + addr + '</a></li>';
	markerCnt++;
}
function myClick(markerCnt) {
	google.maps.event.trigger(gmarkers[markerCnt], 'click');
}
function str_width(str) {
// 文字列の文字幅(漢字は2)を求める。
	var r = 0;
	for (var i = 0; i < str.length; i++) {
		var c = str.charCodeAt(i);
		// Shift_JIS: 0x0 ～ 0x80, 0xa0 , 0xa1 ～ 0xdf , 0xfd ～ 0xff
		// Unicode : 0x0 ～ 0x80, 0xf8f0, 0xff61 ～ 0xff9f, 0xf8f1 ～ 0xf8f3
		if ((c >= 0x0 && c < 0x81) || (c == 0xf8f0) || (c >= 0xff61 && c < 0xffa0) || (c >= 0xf8f1 && c < 0xf8f4)) {
			r += 1;
		} else {
			r += 2;
		}
	}
	return r;
}
function zen2han(text) {
// 全角を半角にする
	var i, charCode, charArray = [];
	for(i=text.length-1;0<=i;i--) {
		charCode = charArray[i] = text.charCodeAt(i);
		switch(true) {
			case (charCode <= 0xff5e && 0xff01 <= charCode):
				charArray[i] -= 0xfee0;
				break;
			case (charCode == 0x3000):
				charArray[i] = 0x0020;
				break;
			case (charCode == 0x30FC):
				charArray[i] = 0x002D;
				break;
		}
	}
	return String.fromCharCode.apply(null, charArray);
}
</script>
<div id="map_canvas"></div>
<div id="side_bar">Loading...</div>
<div id="not_found_box">Not found: <span id="not_found" style="color: red;"></span></div>
<div id="panorama" style="display:none;">
人形マークを、道路上にドラッグ＆ドロップしてください。
<a href="javascript:StreetViewOff()">閉じる</a><br>
<div id="panowin"></div></div>
<?php
}
function getLatLngV2($address, &$lat, &$lng) {		// Geocoding API V2
	$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];
}
function getLatLng($address, &$lat, &$lng) {		// Geocoding API V3
	$json = my_file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false');
	$latLng = json_decode($json, true);
	if ($latLng['status'] <> 'OK') return 'NotFound';
	$lat = $latLng['results'][0]['geometry']['location']['lat'];
	$lng = $latLng['results'][0]['geometry']['location']['lng'];
	return 'OK';
}
?>
