var map;
var geocoder;
var marker;

function initialize() {

	geocoder = new google.maps.Geocoder();
	var latlng = new google.maps.LatLng(35.68923, 139.693995);
	var myOptions = {
		zoom: 4,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
		}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	marker = new google.maps.Marker({
		position: latlng,
		map: map  });
	marker.setMap(null);

	//イベント追加
	google.maps.event.addListener(map, 'click', function(event){placeMarker(event.latLng);});

}

function initialize_detail() {

	geocoder = new google.maps.Geocoder();
	var latlng = new google.maps.LatLng(35.68923, 139.693995);
	var myOptions = {
		zoom: 4,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
		}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	marker = new google.maps.Marker({
		position: latlng,
		map: map  });
	marker.setMap(null);

}


function placeMarker(location){

	var clickedLocation = new google.maps.LatLng(location);
	marker.setMap(null);
	marker = new google.maps.Marker({
				position: location,
				map: map
			});
	map.setCenter(location);
	getAddress(location);

}

function markerinit(location){

	if(location != ""){
		location = location.substring(1,location.length - 1);
		arrLat = location.split(",");
		var latlng = new google.maps.LatLng(arrLat[0], arrLat[1]);

		marker.setMap(null);
		marker = new google.maps.Marker({
					position: latlng,
					map: map
				});
		map.setCenter(latlng);
		map.setZoom(14);
	}

}

function mapread(obj){

	if(obj.id == "p_pref"){
		params = "mode=readcity&p_pref=" + obj.value;
		$(function() {
			$.ajax( {
				url: "ajax_dataloader.php",
				data: params,
				async: false,
				type: "POST",
				success:function(data) {
					document.getElementById("p_cityset").innerHTML = data;
				}
			});
		});
	}
	var address = "";
	if(document.getElementById("p_pref").value != ""){
		address = address + document.getElementById("p_pref").value;
		zoomlevel = 10;
		if(document.getElementById("p_city").value != ""){
			address = address + document.getElementById("p_city").value;
			zoomlevel = 14;
		}

		geocoder.geocode( { 'address': address}, function(results, status) {
			if(status == google.maps.GeocoderStatus.OK) {
				map.setCenter(results[0].geometry.location);
				map.setZoom(zoomlevel);
			}else{
				alert("指定された地域が見つかりませんでした。");
			}
		});
	}else{

	}

}

function getAddress(location){

	geocoder.geocode({latLng: location}, function(results, status){
		if(status == google.maps.GeocoderStatus.OK){
			if(results[0].geometry){
				var address = results[0].formatted_address.replace(/^日本, /, '');
				document.getElementById("p_house_address").value = address;
				document.getElementById("p_house_location").value = location;
	    	}
	    }
	});

}
