<?php
function maps_proc($http_arg, $item_tbl) {
	$con = my_mysql_connect(_DB_SCHEMA);
?>
<div id="maps_filter">
<div id="mp_list_filter" class="block">
<script language="JavaScript">
<!--
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) ?>">
	<div 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, '');
?>
	</div>
	<div id="mp_list_filter_key_select" class="block_left">
<?php
	mp_list_filter_key_select($http_arg['key'], $http_arg);
?>
	</div>
</form>
</div>
<div id="mp_list_add_filter" class="block_left">
<script type="text/javascript">
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;
	}
}
</script>
<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' : '' ?>>全件表示
</div>
<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);
		} else {
			echo "<script type='text/javascript'>function init(){}</script>\n";
			error_msg('該当するデータがありません。');
		}
		$con = mysql_close($con);
	}
}
?>
<?php
function google_maps($rs, $row) {
	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 language="javascript" src="../scripts/encodeURL.js" type="text/javascript"></script>
<script type="text/javascript">
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 ?>);
}
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);
	});
	return marker;
}
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('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 = '';
}
</script>
<div id="map3d"></div>
<div>Not found: <span id="not_found" style="color: red;"></span></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];
}
function my_file_get_contents($url) {
	static $me_called = False;
	static $proxy_context;
	if (!$me_called) {
		if (HTTP_PROXY_HOST.'' <> '') {
			$proxy = array(
				'http' => array(
					'proxy' => 'tcp://'.HTTP_PROXY_HOST.':'.HTTP_PROXY_PORT,
					'request_fulluri' => true,
				),
			);
			$proxy_context = stream_context_create($proxy);
		} else	{
			$proxy_context = False;
		}
	}
	$me_called = True;
	// httpsはエラーになる
	if ($proxy_context) {
		$html = @file_get_contents($url, False, $proxy_context);
	} else {
		$html = @file_get_contents($url);
	}
	return $html;
}
?>
