//enable geolocation
function enableGeoLocation()
{
	//if current url is home page
	if ($('span.findMe').length > 0)
	{
		//toggle findMeBox on hover
		$('span.findMe').live('hover', function ()
		{
			$('.findMeBox').css('display', 'block');
		});
		$('.findMeBox').live('mouseleave', function ()
		{
			$(this).toggle();
		});
	}
	//get current location on click
	$('span.btn').live('click', function ()
	{
		//if current url is home page
		if ($('span.findMe').length > 0)
		{
			$('.findMeBox').css('display', 'none');
		}
		//for other pages
		else
		{
			$('.geoButton').css('display', 'none');
		}
		//check if browser supports geolocation 
		if (navigator.geolocation)
		{
			var timeoutVal = 10 * 1000 * 1000;
			navigator.geolocation.getCurrentPosition(
				displayPosition,
				displayError,
			{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 });
		}
		else
		{
			alert("Geolocation is not supported by this browser");
		}

		function displayPosition(position)
		{
			//if current url is home page
			if ($('span.findMe').length > 0)
			{
				$('span.findMe').css('display', 'none');
				$('.findMeBox').css('display', 'none');
				$('span.carBrand').css('display', 'block');
			}
			getClosestLocation(position);
		}
	});
}

function displayError(error) {
	var errors = {
		1: 'Permission denied',
		2: 'Position unavailable',
		3: 'Request timeout'
	};
	alert("Error: " + errors[error.code]);
}

//pick carBrand
$('span.carBrand').live('hover', function () {
	$('.brandPicker').css('display', 'block');
});

$('.brandPicker').live('mouseleave', function () {
	$(this).css('display', 'none');
});

//select car brand
function getClosestLocation(position) {
	var currentLatitude = position.coords.latitude;
	var currentLongitude = position.coords.longitude;
	var distanceData = [];
	
	var currentPosition = position;
	//find out current url so that carBrand variable can get value of brand for getting closest locations
	var carBrand = "";
	var url = window.location.pathname;
	url = url.substring(1);
	url = url.split("/");

	//if current url is home page
	if (url[0] == 'naslovna')
	{
		carBrand = "all";
	}
	//if current url is car brand page
	else if (url[0] == 'audi' || url[0] == 'vw' || url[0] == 'skoda' || url[0] == 'seat')
	{
		if (url[0] == 'vw')
		{
			var carBrand = url[1];
			if (carBrand == 'gospodarska-vozila')
			{
				carBrand = "vw gospodarska";
			}
			else
			{
				carBrand = "vw";
			}
		}
		else
		{
			carBrand = url[0];
		}
	}
	//if current page is used cars other vehicles
	else
	{
		url = url[url.length - 2];
		if (url == 'ostala-vozila')
		{
			carBrand = 'weltauto';
		}
		else
		{
			carBrand = url;
		}
	}

	if (carBrand == 'all') {
		$.getJSON("/naslovna/closestAZ", function (data) {
			
			for (i = 0; i < data.length; i++) {
				var lat = data[i].latitude;
				var lng = data[i].longitude
				data[i].distance = distance(lat, lng);
			}

			function formatOutput(num) {
				return parseInt(num);
				return num;
			}

			function validate(num, name) {
				if (isNaN(num)) {
					alert("Invalid input for " + name);
					return 1;
				}
				return 0;
			}

			function distance(lat2, lng2) {
				// Get numeric values out of form elements.
				var lat_1 = parseFloat(currentLatitude);
				var lon_1 = parseFloat(currentLongitude);
				var lat_2 = parseFloat(lat2);
				var lon_2 = parseFloat(lng2);

				// input validation
				var errorCount = 0;
				errorCount += validate(lat_1, "the first latitude");
				errorCount += validate(lon_1, "the first longitude");
				errorCount += validate(lat_2, "the second latitude");
				errorCount += validate(lon_2, "the second longitude");
				if (errorCount > 0)
					return;

				// Compute spherical coordinates
				var rho = 3960.0; // earth diameter in miles
				// convert latitude and longitude to spherical coordinates in radians
				// phi = 90 - latitude
				var phi_1 = (90.0 - lat_1) * Math.PI / 180.0;
				var phi_2 = (90.0 - lat_2) * Math.PI / 180.0;
				// theta = longitude
				var theta_1 = lon_1 * Math.PI / 180.0;
				var theta_2 = lon_2 * Math.PI / 180.0;
				// compute spherical distance from spherical coordinates
				// arc length = \arccos(\sin\phi\sin\phi'\cos(\theta-\theta') + \cos\phi\cos\phi')
				// distance = rho times arc length
				var d = rho * Math.acos(Math.sin(phi_1) * Math.sin(phi_2) * Math.cos(theta_1 - theta_2) + Math.cos(phi_1) * Math.cos(phi_2));
				// Display result in miles and in kilometers
				var output = "Distance = " + formatOutput(d) + " miles or " + formatOutput(1.609344 * d) + " kilometers";

				return (formatOutput(1.609344 * d));
			}

			data.sort(function (a, b) {
				return a.distance - b.distance;
			});

			html = "";
			for (i = 0; i < 3; i++) {
				if (i == 2) {
					html += "<li class='last-item'>";
				}
				else {
					html += "<li>";
				}
				html += "<p><strong>" + data[i].grad + " / " + data[i].vrsta.toLowerCase() + "</strong> <span>" + "~" + data[i].distance + " km</span> </p>";
				html += "<p>" + data[i].adresa + "</p>";
				html += "<input type='hidden' name='vrsta' value=" + data[i].vrsta.toLowerCase() + ">";
				html += "<input type='hidden' name='id' value=" + data[i].id + ">";
				html += "</li>";
			}

			$('ul#nearest').html(html);

		});
	}
	else {

		$.getJSON("/naslovna/closestAZ", function (data) {
			var filter = [];
			for (i = 0; i < data.length; i++) {
				if (data[i][carBrand] == "Da") {
					filter.push(data[i]);
				}
			}

			for (i = 0; i < filter.length; i++) {
				var lat = filter[i].latitude;
				var lng = filter[i].longitude
				filter[i].distance = distance(lat, lng);
			}

			function formatOutput(num) {
				return parseInt(num);
				return num;
			}

			function validate(num, name) {
				if (isNaN(num)) {
					alert("Invalid input for " + name);
					return 1;
				}
				return 0;
			}

			function distance(lat2, lng2) {
				// Get numeric values out of form elements.
				var lat_1 = parseFloat(currentLatitude);
				var lon_1 = parseFloat(currentLongitude);
				var lat_2 = parseFloat(lat2);
				var lon_2 = parseFloat(lng2);

				// input validation
				var errorCount = 0;
				errorCount += validate(lat_1, "the first latitude");
				errorCount += validate(lon_1, "the first longitude");
				errorCount += validate(lat_2, "the second latitude");
				errorCount += validate(lon_2, "the second longitude");
				if (errorCount > 0)
					return;

				// Compute spherical coordinates
				var rho = 3960.0; // earth diameter in miles
				// convert latitude and longitude to spherical coordinates in radians
				// phi = 90 - latitude
				var phi_1 = (90.0 - lat_1) * Math.PI / 180.0;
				var phi_2 = (90.0 - lat_2) * Math.PI / 180.0;
				// theta = longitude
				var theta_1 = lon_1 * Math.PI / 180.0;
				var theta_2 = lon_2 * Math.PI / 180.0;
				// compute spherical distance from spherical coordinates
				// arc length = \arccos(\sin\phi\sin\phi'\cos(\theta-\theta') + \cos\phi\cos\phi')
				// distance = rho times arc length
				var d = rho * Math.acos(Math.sin(phi_1) * Math.sin(phi_2) * Math.cos(theta_1 - theta_2) + Math.cos(phi_1) * Math.cos(phi_2));
				// Display result in miles and in kilometers
				var output = "Distance = " + formatOutput(d) + " miles or " + formatOutput(1.609344 * d) + " kilometers";

				return (formatOutput(1.609344 * d));
			}

			filter.sort(function (a, b) {
				return a.distance - b.distance;
			});

			html = "";
			for (i = 0; i < 3; i++) {
				if (i == 2) {
					html += "<li class='last-item'>";
				}
				else {
					html += "<li>";
				}
				html += "<p><strong>" + filter[i].grad + " / " + filter[i].vrsta.toLowerCase() + "</strong> <span>" + "~" + filter[i].distance + " km</span> </p>";
				html += "<p>" + filter[i].adresa + "</p>";
				html += "<input type='hidden' name='vrsta' value=" + filter[i].vrsta.toLowerCase() + ">";
				html += "<input type='hidden' name='id' value=" + filter[i].id + ">";
				html += "</li>";
			}

			$('ul#nearest').html(html);

		});
	}

	$('ul.brandPicker li span').live('click', function () {
		$('ul.brandPicker li span').removeClass("selected");
		$(this).addClass("selected");
		$('ul.brandPicker').css('display', 'none');
		var carBrand = $(this).attr('id');
		carBrand = carBrand.toLowerCase();

		if (carBrand == 'all') {
			$.getJSON("/naslovna/closestAZ", function (data) {
				var filter = [];
				for (i = 0; i < data.length; i++) {
					var lat = data[i].latitude;
					var lng = data[i].longitude
					data[i].distance = distance(lat, lng);
				}

				function formatOutput(num) {
					return parseInt(num);
					return num;
				}

				function validate(num, name) {
					if (isNaN(num)) {
						alert("Invalid input for " + name);
						return 1;
					}
					return 0;
				}

				function distance(lat2, lng2) {
					// Get numeric values out of form elements.
					var lat_1 = parseFloat(currentLatitude);
					var lon_1 = parseFloat(currentLongitude);
					var lat_2 = parseFloat(lat2);
					var lon_2 = parseFloat(lng2);

					// input validation
					var errorCount = 0;
					errorCount += validate(lat_1, "the first latitude");
					errorCount += validate(lon_1, "the first longitude");
					errorCount += validate(lat_2, "the second latitude");
					errorCount += validate(lon_2, "the second longitude");
					if (errorCount > 0)
						return;

					// Compute spherical coordinates
					var rho = 3960.0; // earth diameter in miles
					// convert latitude and longitude to spherical coordinates in radians
					// phi = 90 - latitude
					var phi_1 = (90.0 - lat_1) * Math.PI / 180.0;
					var phi_2 = (90.0 - lat_2) * Math.PI / 180.0;
					// theta = longitude
					var theta_1 = lon_1 * Math.PI / 180.0;
					var theta_2 = lon_2 * Math.PI / 180.0;
					// compute spherical distance from spherical coordinates
					// arc length = \arccos(\sin\phi\sin\phi'\cos(\theta-\theta') + \cos\phi\cos\phi')
					// distance = rho times arc length
					var d = rho * Math.acos(Math.sin(phi_1) * Math.sin(phi_2) * Math.cos(theta_1 - theta_2) + Math.cos(phi_1) * Math.cos(phi_2));
					// Display result in miles and in kilometers
					var output = "Distance = " + formatOutput(d) + " miles or " + formatOutput(1.609344 * d) + " kilometers";

					return (formatOutput(1.609344 * d));
				}

				data.sort(function (a, b) {
					return a.distance - b.distance;
				});

				html = "";
				for (i = 0; i < 3; i++) {
					if (i == 2) {
						html += "<li class='last-item'>";
					}
					else {
						html += "<li>";
					}
					html += "<p><strong>" + data[i].grad + " / " + data[i].vrsta.toLowerCase() + "</strong> <span>" + "~" + data[i].distance + " km</span> </p>";
					html += "<p>" + data[i].adresa + "</p>";
					html += "<input type='hidden' name='vrsta' value=" + data[i].vrsta.toLowerCase() + ">";
					html += "<input type='hidden' name='id' value=" + data[i].id + ">";
					html += "</li>";
				}

				$('ul#nearest').html(html);

			});
		}
		else {

			$.getJSON("/naslovna/closestAZ", function (data) {
				var filter = [];
				for (i = 0; i < data.length; i++) {
					if (data[i][carBrand] == "Da") {
						filter.push(data[i]);
					}
				}

				for (i = 0; i < filter.length; i++) {
					var lat = filter[i].latitude;
					var lng = filter[i].longitude
					filter[i].distance = distance(lat, lng);
				}

				function formatOutput(num) {
					return parseInt(num);
					return num;
				}

				function validate(num, name) {
					if (isNaN(num)) {
						alert("Invalid input for " + name);
						return 1;
					}
					return 0;
				}

				function distance(lat2, lng2) {
					// Get numeric values out of form elements.
					var lat_1 = parseFloat(currentLatitude);
					var lon_1 = parseFloat(currentLongitude);
					var lat_2 = parseFloat(lat2);
					var lon_2 = parseFloat(lng2);

					// input validation
					var errorCount = 0;
					errorCount += validate(lat_1, "the first latitude");
					errorCount += validate(lon_1, "the first longitude");
					errorCount += validate(lat_2, "the second latitude");
					errorCount += validate(lon_2, "the second longitude");
					if (errorCount > 0)
						return;

					// Compute spherical coordinates
					var rho = 3960.0; // earth diameter in miles
					// convert latitude and longitude to spherical coordinates in radians
					// phi = 90 - latitude
					var phi_1 = (90.0 - lat_1) * Math.PI / 180.0;
					var phi_2 = (90.0 - lat_2) * Math.PI / 180.0;
					// theta = longitude
					var theta_1 = lon_1 * Math.PI / 180.0;
					var theta_2 = lon_2 * Math.PI / 180.0;
					// compute spherical distance from spherical coordinates
					// arc length = \arccos(\sin\phi\sin\phi'\cos(\theta-\theta') + \cos\phi\cos\phi')
					// distance = rho times arc length
					var d = rho * Math.acos(Math.sin(phi_1) * Math.sin(phi_2) * Math.cos(theta_1 - theta_2) + Math.cos(phi_1) * Math.cos(phi_2));
					// Display result in miles and in kilometers
					var output = "Distance = " + formatOutput(d) + " miles or " + formatOutput(1.609344 * d) + " kilometers";

					return (formatOutput(1.609344 * d));
				}

				filter.sort(function (a, b) {
					return a.distance - b.distance;
				});

				html = "";
				for (i = 0; i < 3; i++) {
					if (i == 2) {
						html += "<li class='last-item'>";
					}
					else {
						html += "<li>";
					}
					html += "<p><strong>" + filter[i].grad + " / " + filter[i].vrsta.toLowerCase() + "</strong> <span>" + "~" + filter[i].distance + " km</span> </p>";
					html += "<p>" + filter[i].adresa + "</p>";
					html += "<input type='hidden' name='vrsta' value=" + filter[i].vrsta.toLowerCase() + ">";
					html += "<input type='hidden' name='id' value=" + filter[i].id + ">";
					html += "</li>";
				}

				$('ul#nearest').html(html);

			});
		}
	});	
}
