'use strict';

$(function() {
	var $imagesContainer = $('.js-images-container'),
		$sliders = {
			heading: $('.js-heading-slider'),
			fov: $('.js-fov-slider'),
			pitch: $('.js-pitch-slider')
		};

	/**
	 * Setup Foundation components and default values
	 */
	$(document).foundation();
	$sliders.heading.foundation('slider', 'set_value', 0);
	$sliders.fov.foundation('slider', 'set_value', 90);
	$sliders.pitch.foundation('slider', 'set_value', 0);

	$('.js-random-address').click(function(e) {
		var $target = $(e.target),
			input = $($target.data('selector')),
			latlong = leopard.getRandomLatLong(),
			addressDfd = $.Deferred(),
			/**
			 * Converts the given latitude/longitude values into a human
			 * readable address. Continues to loop if the values given
			 * do not return a valid address.
			 * @param  {Object} location
			 */
			getAddress = function(location) {
				$.ajax({
					url: new leopard.tpl(leopard.api.geocode).apply({
						location: location.latitude + ',' + location.longitude,
						key: leopard.api.key
					})
				}).done(function(data) {
					if (data.status !== 'OK') {
						latlong = leopard.getRandomLatLong();
						return getAddress(latlong);
					}

					addressDfd.resolve(data);
				});

				return true;
			};

		getAddress(latlong);

		// Wait for valid address to be returned
		addressDfd.done(function(data) {
			input.val(data.results[0].formatted_address);
		});
	});

	/**
	 * Form submit functionality
	 */
	$('form').on('submit', function(e) {
		var heading = $sliders.heading.attr('data-slider'),
			fov = $sliders.fov.attr('data-slider'),
			pitch = $sliders.pitch.attr('data-slider'),
			location, url;

		// TODO: Validate longitude/latitude values
		location = $('#address-start').val();

		url = new leopard.tpl(leopard.api.streetview).apply({
				key: leopard.api.key,
				width: leopard.images.width,
				height: leopard.images.height,
				location: location,
				heading: heading,
				fov: fov,
				pitch: pitch
		});

		$imagesContainer.append($('<img/>').attr('src', url)).fadeIn();

		e.preventDefault();
	});
});

@@ -1095,9 +1095,8 @@
 tus 
-!
 == '
@@ -1098,24 +1098,146 @@
  == 'OK') %7B%0A
+%09%09%09%09%09%09return addressDfd.resolve(data);%0A%09%09%09%09%09%7D else if (data.status == 'ZERO_RESULTS' %7C%7C data.status == 'UNKNOWN_ERROR') %7B%0A
 %09%09%09%09%09%09latlon
@@ -1320,37 +1320,36 @@
 %09%09%09addressDfd.re
-solve
+ject
 (data);%0A%09%09%09%09%7D);%0A
@@ -1475,16 +1475,16 @@
 data) %7B%0A
-
 %09%09%09input
@@ -1524,16 +1524,70 @@
 dress);%0A
+%09%09%7D).fail(function(data) %7B%0A%09%09%09input.val(data.status);%0A
 %09%09%7D);%0A%09%7D

Add check for additional errors from geocode API