$(document).ready(function() {
	var $form = $('#distance-calculator'),
			formH = $form.height() + 60;
	
	$('#distance-calculator input[type="submit"]').click(function(e) {
		e.preventDefault();
		
		var origin = $('#origin').val(),
				destination = $('#destination').val();
		
		if(origin.length && destination.length) {
			$form
				.animate({'height':formH+'px'},100, function() {
					$form.children('.result').fadeOut(100, function() { $(this).remove(); });
					$form.children('input[type="submit"]').fadeOut(100, function() {
						$form.append('<img class="loading" src="img/loading.gif" height="42" width="42">')
							.children('img').fadeIn(200);
					});
				});
				
				var service = new google.maps.DistanceMatrixService();
				service.getDistanceMatrix(
				{
					origins: [origin],
					destinations: [destination],
					travelMode: google.maps.TravelMode.DRIVING,
					unitSystem: google.maps.UnitSystem.IMPERIAL,
					avoidHighways: false,
					avoidTolls: false
				}, callback);
				
				function callback(response, status) {
					if (status == google.maps.DistanceMatrixStatus.OK) {
						var origins = response.originAddresses;
						var destinations = response.destinationAddresses;
						
						for (var i = 0; i < origins.length; i++) {
							var results = response.rows[i].elements;
							for (var j = 0; j < results.length; j++) {
								var element = results[j];
									var meters = element.distance.value;
									var miles = meters * 0.000621371192;
								var distance = Math.round(miles*Math.pow(10,1))/Math.pow(10,1);
								
								var tmpTime = setTimeout(function() {
									displayMileage(distance);
								}, 1000);
							}
						}
					} else if(status == google.maps.DistanceMatrixStatus.OVER_QUERY_LIMIT) {
						alert('Error: Rate limit reached.');
					} else {
						alert('Error: unable to calculate distance.');
					}
				}
				
				function displayMileage(distance) {
					$form.children('img').fadeOut(100, function() {
						$(this).remove();
						$form.append('<p class="result">Mileage = '+distance+' mi</p>')
							.children('input[type="submit"], .result').fadeIn(200);
						$('#mileage').val(distance);
					});
				}
			
		} else {
			alert('Error: you have to enter both an origin and destination');
		}
	});	
	
	
	$('#fare-calculator input[type="submit"]').click(function(e) {
		e.preventDefault();
		
		if($('#mileage').val().length > 0) {
			var rawCost = 2.7 * $('#mileage').val() + 3,
					roundCost = Math.round(rawCost*Math.pow(10,2))/Math.pow(10,2);
			
			$('#calculation .num-of-miles').html($('#mileage').val());
			/* $('#calculation .cost-of-trip').html(roundCost); */
			$('#calculation .cost-of-trip').html(parseFloat(roundCost).toFixed(2));
		} else {
			alert('Error: you must enter a number for mileage.');
		}
		
	});
	
	
});
