// $Id:$
if (Drupal.jsEnabled) {
  $(document).ready(function() {
		
		$('#webform-component-subscribe_nearest_deli_location').hide();
		
		$('#edit-submitted-subscribe-zip-code').blur( function () {
			
      var postalCode = $(this).val();
      
			// Validation
      if (postalCode.length == 0) {
				return false;
      }
			
			if (postalCode.length != 5 || postalCode != parseInt(postalCode)) {
				alert('Please enter a valid zip code.');
				return false;
			}
			
			// Remove an existing dropdown
      $('#webform-component-subscribe_nearest_deli_location').hide();
			// Add a throbber
			$('#webform-component-subscribe_zip_code').after('<div id="location-select-throbber"></div>');
			
			
			// AJAX success function
			var limitLocResults = function(data) {
				$('#edit-submitted-subscribe-nearest-deli-location').html(data.options);
				$('#location-select-throbber').remove();
				$('#webform-component-subscribe_nearest_deli_location').fadeIn();
			}
      
      var xhr = $.ajax({
				type: 'POST',
				url: '/ajax/jasons-subscribe/locations',
				dataType: 'json',
				success: limitLocResults,
				data: {
					'ajax' : true,
					'postal_code' : postalCode
				}
			});
			
			// If someone attempts to resubmit while an existing ajax query is running
			// stop what we've started
			$('#edit-submitted-subscribe-zip-code').change( function() {
				// Abort the existing query
				xhr.abort();
			});
      
      return false;
      
    });
		
  });
}

