/**
 * JavaScript for property management.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS\module\property
 * @copyright Copyright (c) 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * Get the position from the postcode.
 *
 * @param string address The address to look up.
 * @param function callback The function to call once the look up has completed.
 */
function getPosition(address, callback) {
	// set up our geoCoder
	var geocoder = new google.maps.Geocoder();

	//send value to google to get a longitude and latitude value
	geocoder.geocode({
		'address': address,
		'region': $fl('#countrycode').val()
	}, function(results, status)
	{
		// callback with a status and result
		if (status == google.maps.GeocoderStatus.OK)
		{
			// send the values back in a JSON string
			callback({
				latt: results[0].geometry.location.lat(),
				long: results[0].geometry.location.lng()
			});
		}
	});
}

/**
 * Setup google maps.
 *
 * @param float latitude
 * @param float longitude
 */
function setupMap(latitude, longitude) {
	// create a JSON object with the values to mark the position
	var _position = { lat: latitude, lng: longitude};

	// add our default mapOptions
	var mapOptions = {
		zoom: 16, // zoom level of the map
		center: _position // position to center
	}

	// load a map within the "map" div and display
	var map = new google.maps.Map(document.getElementById('map-container'), mapOptions);

	// add a marker to the map with the position of the longitude and latitude
	var marker = new google.maps.Marker({
		position: mapOptions.center,
		map: map,
		draggable: true
	});

	google.maps.event.addListener(marker, 'dragend', function() {
		var p = marker.getPosition();
		$fl('#lat').val(p.lat());
		$fl('#lng').val(p.lng());
	});
}

/**
 * Convert address to lat/lng pair.
 */
function addressToLocation() {
	mapShown = false;

	var address =
		$fl('#street1').val() + ' ' +
		$fl('#street2').val() + ' ' +
		$fl('#city').val() + ' ' +
		$fl('#state').val() + ' ' +
		$fl('#postcode').val();

	getPosition(address, function(position){

		// log the position returned
		$fl('#lat').val(position.latt);
		$fl('#lng').val(position.long);

		// update the map with the new position
		setupMap(position.latt, position.long);
	});


}

/**
 * Update the map from a change in the text boxes.
 */
function latlngChange() {
	setupMap(parseFloat($fl('#lat').val()), parseFloat($fl('#lng').val()));
}

$fl(document).ready(function() {
	latlngChange()
});
