/*
 * using jQuery to start google maps and bind horizon files to it
 */
$(document).ready(function() {
	// initialize google map
	var geocoder;
	var elevator;
	var map;
	var marker;

	// MAP
	var latlng = new google.maps.LatLng(48,12);
	$("#lat").val(48);
	$("#long").val(12);

	var mapOptions = {
			zoom: 2,
			center:  latlng,
			streetViewControl: true,
			panControl : false,
			zoomControl: true,
			zoomControlOptions: {
				style: google.maps.ZoomControlStyle.SMALL
			},
			style: google.maps.ZoomControlStyle.SMALL,
			mapTypeId: google.maps.MapTypeId.HYBRID
	};

	map = new google.maps.Map(document.getElementById("pvc_map"),mapOptions);
	
	// add click listener to place markers on the map
	google.maps.event.addListener(map, 'click', function(event) {
		show_location(event.latLng,map.getZoom());
		$("#address").val("");
	});

	// add listener to the end of dragging marker
	google.maps.event.addListener(map, "dragend", function() {
		show_location(map.getCenter(),map.getZoom());
		$("#address").val("");
	});
	
	// crosshair marker
	var crosshair = new google.maps.MarkerImage(
			  '_images/crosshairs.png',
			  new google.maps.Size(25,25),
			  new google.maps.Point(0,0),
			  new google.maps.Point(12,12)
			);

	marker = new google.maps.Marker({
		map: map,
		draggable: true,
		icon: crosshair
	});
	
	// GEOCODER
	geocoder = new google.maps.Geocoder();	


	// start geocoder from form action
	$("#searchform").submit(function(){
		var search_address = $("#address").val();
		if(search_address.length > 0) {
			geocode_address(search_address);
		}
		return false;
	});

	// try to geocode address and get lat, lon back
	function geocode_address(search_address) {
		geocoder.geocode( {'address': search_address }, function(results, status) {
			if(status == "OK") {
				show_location(results[0].geometry.location,16);
			} else {
				$("#address").val(status);
			}
		});
		return;
	}

	// shows lat lon in html and drop a marker on location
	function show_location(location, zoom_level) {
		$("#lat").val(round_coordinate(location.lat()));
		$("#long").val(round_coordinate(location.lng()));
		
		marker.setPosition(location);
		map.setCenter(location);
		map.setZoom(zoom_level);
		map.setMapTypeId(google.maps.MapTypeId.HYBRID);
		
		// show altitude
		show_altitude(location);
		return;
	}
	
	/* get altitude per lat/lon and show in form field */
	function show_altitude(latlon) {
		// try to find altitude
		// Create an ElevationService
		elevator = new google.maps.ElevationService();
		
		var locations = [];
		locations.push(latlon);
		var positionalRequest = {
				'locations': locations
		}
		elevator.getElevationForLocations(positionalRequest, function(results, status) {
			if (status == google.maps.ElevationStatus.OK) {
				// Retrieve the first result
				if (results[0]) {
					$("#altitude").val(Math.round(results[0].elevation));
				}
			} else {}
		});
		return;
	}
	
	//autocomplete
	$("#address").autocomplete({
		minLength: 4,
		//This bit uses the geocoder to fetch address values
		source: function(request, response) {
			geocoder.geocode( {'address': request.term }, function(results, status) {
				response($.map(results, function(item) {
					return {
						label:  item.formatted_address,
						value: item.formatted_address,
						latitude: item.geometry.location.lat(),
						longitude: item.geometry.location.lng(),
						location: item.geometry.location
					}
				}));
			})
		},
	
		//This bit is executed upon selection of an address
		select: function(event, ui) {
			show_location(ui.item.location,16);
		}
	});
	
	// check coordinate, show coordinate on map
	$("#check_coordinate").click(function() {
		var lat = $("#lat").val();
		var lon = $("#long").val();
		//default 0
		lat = (isNaN(lat)) ? 0 : lat;
		lon = (isNaN(lon)) ? 0 : lon;
		
		var myLatlng = new google.maps.LatLng(lat,lon);
		show_location(myLatlng,map.getZoom());
	});
	
});
	

/* round any coordinate to 5 decimal numbers */
function round_coordinate(coord){
	coord = coord * 100000;
	coord = Math.round(coord);
	coord = coord / 100000;
	return coord;
}
