var clickHandler;
var map;
var lat;
var lng;
var locations = new Array();
var infos = new Array();
var bounds;
var lid;
var lname;

$(document).ready(function() {
	if (!GBrowserIsCompatible()) return;
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl(true));
	map.setCenter(new GLatLng(35.67, 138.25), 4);

	//クリックして座標を取得する
	clickHandler = GEvent.addListener(map, "click", function(marker, point) {
		setNewMarker(point);
	});
//	GEvent.addListener(map, "load", function() {
//		alert("load Compleated the map.");
//	});
	//MAPボタン
	$("#button_marker").click(function(){
		setMyPoint();
	});
	//住所クリアボタン
	$("#button_addressclear").click(function(){
		$("#serchaddress").attr('value','');
		$("#serchaddressitem").attr('latitude','');
		$("#serchaddressitem").attr('longitude','');
		$("p#location_info").html("");
	});
	$('#gmapwindow').parents('.block_contents').hide();
});

//住所を得る
function getAddress(adr) {
	if(adr == '') return;
	$("#metropolis").children().each(function(){
		$(this).attr('selected','');
		if($(this).attr('value')) {
			if(adr.indexOf($(this).attr('value')) > -1) {
				$(this).attr('selected','selected');
				adrs = adr.replace($(this).attr('value'), '');
				$("#serchaddress").attr('value', adrs);
			}
		}
	});
}

//MAPボタン
function setMyPoint() {
	gGeo = new GClientGeocoder();
	var metropolis = null;
	var adrs = null;
	$('#serchform select').each(function () {
		metropolis = this.options[this.selectedIndex].value;
	});
	adrs = $("#serchaddress").attr('value');
	if(!metropolis && !adrs) {
		alert("住所を入力してください");
		return;
	}
	if(adrs) {
		m = adrs.match('〒[0-9]+-[0-9]+ ', '');
		adrs = adrs.replace(m, '');
		x = adrs.indexOf(' ');
		if(x > 0) adrs = adrs.substr(0, x);
		xx = adrs.indexOf('　');
		if(xx > 0) adrs = adrs.substr(0, xx);
	} else {
		adrs = "";
	}
	//住所から座標を取得する 太田市飯田町542
	gGeo.getLatLng(metropolis + adrs, function(point) {
		if (point) {
			$('#serchaddressitem').attr('latitude',point.lat());
			$('#serchaddressitem').attr('longitude',point.lng());
			$("p#location_info").html("緯度"+$('#serchaddressitem').attr('latitude')+":経度"+$('#serchaddressitem').attr('longitude')+" 周辺検索をします");
			if(map) map.clearOverlays();
			locations = new Array();
			infos = new Array();
			infos[0] = new Array();
			infos[0].id = "serchaddressitem";
			infos[0].name = $("#serchaddress").attr("value");
			pit = {
				'i': 0,
				'id': 'serchaddressitem',
				'name': $("#serchaddress").attr("value"),
				'latitude': $('#serchaddressitem').attr('latitude'),
				'longitude': $('#serchaddressitem').attr('longitude'),
				'created': '2007-03-03 20:20:20'
			}
			processLocations(pit);
		}
	});
}

//クリックして座標を取得する
function setNewMarker(point) {
	if(!point) return;
	$('#serchaddressitem').attr('latitude',point.lat());
	$('#serchaddressitem').attr('longitude',point.lng());
				$("p#location_info").html("緯度"+$('#serchaddressitem').attr('latitude')+":経度"+$('#serchaddressitem').attr('longitude')+" 周辺検索をします");
	if(map) map.clearOverlays();
	locations = new Array();
	infos = new Array();
	infos[0] = new Array();
	infos[0].id = "serchaddressitem";
	infos[0].name = $("#serchaddress").attr("value");
	pit = {
		'i': 0,
		'id': 'serchaddressitem',
		'name': '',
		'latitude': $('#serchaddressitem').attr('latitude'),
		'longitude': $('#serchaddressitem').attr('longitude'),
		'created': '2007-03-03 20:20:20'
	}
	processLocations(pit);
}

//マーカー一覧を生成する
function genLocations() {
	locations = new Array();
	infos = new Array();
	if (!GBrowserIsCompatible()) return;
	if(map) map.clearOverlays();
	gGeo = new GClientGeocoder();

	$(".locationitem").each(function(i){
		infos[i] = new Array();
		infos[i].id = $(this).attr("id");
		infos[i].name = $(this).attr("name");
		infos[i].marker = $(this).attr("marker");
		if(!$(this).attr("latitude") && $(this).attr("Address") != '') {
			//住所から座標を取得する
			gGeo.getLatLng($(this).attr("Address"), function(point) {
			if (point) {
				pit = {
					'i': i,
					'id': lid,
					'name': lname,
					'latitude': point.y,
					'longitude': point.x,
					'created': $(this).attr("created")
				}
				processLocations(pit);
         }
			});
		} else if($(this).attr("latitude") != '' && $(this).attr("longitude") != ''){
			//じゃらん日本測地系を世界測地系に変換する
			if($(this).attr("latitude") > 3600000) {
				jx = $(this).attr("latitude") / 3600000.0;
				jy = $(this).attr("longitude") / 3600000.0;
				y = jx - jy * 0.000046038 - jx * 0.000083043 + 0.010040;
				x = jy - jy * 0.00010695 + jx * 0.000017464 + 0.0046017;
			} else {
				x = $(this).attr("latitude");
				y = $(this).attr("longitude");
			}

				pit = {
					'i': i,
					'id': $(this).attr("id"),
					'name': $(this).attr("name"),
					'latitude': x,
					'longitude': y,
					'marker': $(this).attr("marker"),
					'created': $(this).attr("created")
				}
				if(x) processLocations(pit);
		}
	});
}

//マーカーを追加する
function processLocations(loc) {
	loc.id = infos[loc.i].id;
	loc.name = infos[loc.i].name;
	loc.marker = infos[loc.i].marker;
	locations.push(loc);
	var opt = new Object();
	opt.title = loc.name;
	if(loc.marker) {
		var picon = new GIcon();
		picon.image = "http://mup.tonttu.net/img/marker_"+loc.marker+".gif";
		picon.iconSize = new GSize(30, 30);
		picon.iconAnchor = new GPoint(0, 30);
		picon.infoWindowAnchor = new GPoint(0, 30);
		opt.icon = picon;
	} else {
		opt.icon = G_DEFAULT_ICON;
	}
	var marker = new GMarker(new GLatLng(loc.latitude, loc.longitude), opt);
	map.addOverlay(marker);
	$('#' + loc.id).click(function(){
		moveMapTo(loc.latitude, loc.longitude);
	});
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml('<b>'+loc.name+'</b>');
  });

	$("#gmapwindow").parent(".block_contents").show();
	zoomShowAll();
}

//座標に移動する
function moveMapTo(x,y) {
  map.panTo(new GLatLng(x, y));
}

//移動とズームしてポイントを収める
function zoomShowAll() {
	bounds = new GLatLngBounds();
	map.setCenter(new GLatLng(0,0),0);

	$.each(locations,function(id) {
		bounds.extend(new GLatLng(locations[id].latitude, locations[id].longitude));
	});
	z = map.getBoundsZoomLevel(bounds);
	if(z > 15) z = 15;
	map.setZoom(z);
	var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
	var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
	map.setCenter(new GLatLng(clat,clng));
	$('#gmapwindow').parents('.block_contents').show();
}
