// ---- GESTION GOOGLE MAPS
var map;
var marker;

// Fonction qui affiche une google map "map" et un repere a partir de la latitude et la longitude (issu du formulaire)
function affMap() {
	var myLatlng = new google.maps.LatLng($("input[name=lat]").val(), $("input[name=lng]").val());
	
	var myOptions = {
		zoom: 8,
		center: myLatlng,
		scaleControl: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
		navigationControl: true,
		navigationControlOptions: {style: google.maps.NavigationControlStyle.DEFAULT}
	}
	map = new google.maps.Map(document.getElementById("map"), myOptions);
	marker = new google.maps.Marker({
		icon: 'img/pointer.png',
		position: myLatlng, 
		draggable: true,
		map: map
	});
}

// Fonction qui géolocalise une adresse selon le format ADRESSE, VILLE
function codeAddress(address) {
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode( { address: address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK && results.length) {
			// You should always check that a result was returned, as it is
			// possible to return an empty results object.
			if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
				map.setCenter(results[0].geometry.location);
				map.setZoom(12);
				marker.setPosition(results[0].geometry.location);
			}
		} else {
			pos = address.indexOf(',');
			if(pos > 0) {
				newAddress = address.substring(pos+2);
				codeAddress(newAddress);
			} else {
				alert("Impossible de localiser votre bien");
			}
		}
	});
}

function getLatLng () {
	if(marker) {
		$("input[name=lat]").val(marker.getPosition().lat());
		$("input[name=lng]").val(marker.getPosition().lng());
	}
}

