var map = null;
var dispAddress;
var iconPath = null;

var prefecture;
var cityTown;
var houseNumber;
var building;
var shopName;

var m_address;
var i_address;

function load(path) {
	iconPath = path;

	if (GBrowserIsCompatible()) {
		lat = document.getElementById('latitude').value;
		lng = document.getElementById('longitude').value;

		prefecture = document.shopInfoForm.prefecture.value;
		cityTown = document.shopInfoForm.cityTown.value;
		houseNumber = document.shopInfoForm.houseNumber.value;
		building = document.shopInfoForm.building.value;
		shopName = document.shopInfoForm.shopName.value;

		m_address = prefecture + cityTown + houseNumber;
		i_address = m_address + '<br />' + building + '<br />' + shopName;

		if (lat != '' && lng != '') {
			var latLng = new GLatLng(lng, lat);
			showMarker(latLng, i_address);
		} else if (m_address != '') {
			geocoding();
		} else {
			var latLng = new GLatLng(35.68137872227962, 139.76606011390686);
			showMarker(latLng, '東京駅');
		}
	}
}

function callback_latLng(latLng) {

	if (!latLng) {
		alert(m_address + " not found");
	} else {
		showMarker(latLng, i_address);
	}
}

// 指定座標にマーカーと吹き出しを表示する。マーカーはドラッグ可能。
function showMarker(latLng, dispAddress) {

	var markerOptions = {
		draggable : true,
		icon : orgIcon(iconPath)
	};

	var marker = new GMarker(latLng, markerOptions);

	GEvent.addListener(marker, "dragend", function() {
		point = marker.getLatLng();
		// ※緯度経度が逆になっているが、表ページとの互換性を考えてそのまま。
		document.getElementById('longitude').value = point.lat();
		document.getElementById('latitude').value = point.lng();
	});

	map = new GMap2(document.getElementById("map"));
	map.setCenter(marker.getLatLng(), 15);
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addOverlay(marker);
	marker.openInfoWindowHtml(dispAddress);

	point = marker.getLatLng();
	document.getElementById('longitude').value = point.lat();
	document.getElementById('latitude').value = point.lng();
}

function geocoding() {

	prefecture = document.shopInfoForm.prefecture.value;
	cityTown = document.shopInfoForm.cityTown.value;
	houseNumber = document.shopInfoForm.houseNumber.value;
	building = document.shopInfoForm.building.value;
	shopName = document.shopInfoForm.shopName.value;

	m_address = prefecture + cityTown + houseNumber;
	i_address = m_address + '<br />' + building + '<br />' + shopName;

	geocoder = new GClientGeocoder();
	geocoder.getLatLng(m_address, callback_latLng);

}

function orgIcon(iconPath) {
	var icon = new GIcon();
	icon.image = iconPath;
	icon.iconSize = new GSize(30, 50);
	icon.iconAnchor = new GPoint(14, 50);
	icon.infoWindowAnchor = new GPoint(18, 11);
	return icon;
}

