// Jasons module javascript file

if (Drupal.jsEnabled) {
  $(document).ready(function() {
    
		// Preload images
		(function($) {
			var cache = [];
			// Arguments are image paths relative to the current page.
			$.preLoadImages = function() {
				var args_len = arguments.length;
				for (var i = args_len; i--;) {
					var cacheImage = document.createElement('img');
					cacheImage.src = arguments[i];
					cache.push(cacheImage);
				}
			}
		})(jQuery)
		
		// Diasble some fields that we couldn't seem to using hook_form_alter()
    $('.fields-disable input').attr('disabled', 'disabled');
    $('.fields-disable select').attr('disabled', 'disabled');
    // Fade the text in disabled fields
    $('input:disabled').css('color', '#999');
    
    // AJAX success function
    var processLocSearch = function(data) {
      
      // Get AJAX results
      var result = data.result;
      
      // Add our dropdown box just inside the body
      $('body').prepend('<div id="loc-drop">' + result + '</div>');
      
      var dropWidth = $('#loc-drop').width();
      var searchHeight = $('#loc-search-bar').height();
      var windowWidth = $(window).width();
      var dropLeft = (windowWidth - dropWidth) / 2;
      
      // Position the dropdown and make it drop down
      $('#loc-drop').css({ left: dropLeft + 'px', top: searchHeight + 'px' }).slideDown();
			// Adjust for admin menu
			$('body.admin-menu #loc-drop').css({ top: searchHeight + 20 + 'px' });
			
			// Hide the throbber
			$('#loc-search-submit-throbber').hide();
			$('.loc-search-submit').css('margin-right', '20px');
      
      $('#loc-drop .close-link')
        // Close the dropdown when clicking the close link
        .click( function() {
          $('#loc-drop').slideUp();
        })
        // Add underline on hover
        .hover(
          function () {
            $(this).css('text-decoration', 'underline');
          },
          function () {
            $(this).css('text-decoration', 'none');
          }
        );
      
      // Close the dropdown when clicking elsewhere on the page
      $('#container').click( function() {
        $('#loc-drop').slideUp();
      })
      
    }
		
		// Add a throbber to the search submit and hide it
		$('.loc-search-submit').after('<div id="loc-search-submit-throbber"><img src="/sites/all/modules/jasons/images/ajax-loader.gif" /></div>');
		$('#loc-search-submit-throbber').hide();
    
    // AJAX submit behaviors for the location search form
    $('#jasons-location-zip-simple-form').submit( function () {
			
			// Remove an existing dropdown
      $('#loc-drop').remove();
      
      var postalCode = $(this).find('#edit-postal-code').val();
      var country = $(this).find('#edit-country').val();
      var distance = $(this).find('#edit-distance').val();
      var unit = $(this).find('#edit-unit').val();
      
      if (postalCode.length != 5 || postalCode != parseInt(postalCode)) {
        alert('Please enter a valid zip code.');
        return false;
      }
			
			// Show the throbber
			$('.loc-search-submit').css('margin-right', '0');
			$('#loc-search-submit-throbber').show();
      
      var xhr = $.ajax({
					type: 'POST',
					url: '/restaurants/search/ajax',
					dataType: 'json',
					success: processLocSearch,
					data: {
						'ajax' : 1,
						'postal_code' : postalCode,
						'country' : country,
						'distance' : distance,
						'unit' : unit
					}
				});
			
			// If someone attempts to resubmit while an existing ajax query is running
			// stop what we've started
			$('.loc-search-submit').click( function() {
				// Abort the existing query
				xhr.abort();
				// Remove the existing throbber
				$('#loc-search-submit-throbber').hide();
			});
      
      return false;
      
    });
    
    // Zip code form 
		var searchForm = $('#edit-postal-code-wrapper .form-text');
		var blurColor = searchForm.css('color');
    var focusColor = '#4d4d4d';
    var searchVal = searchForm.val();
		// Clear zip code form on focus 
    searchForm.focus(function() {
      searchForm.val('');
    });
		// Repopulate zipcode form on blur if nothing has been entered
    searchForm.blur(function() {
      if ($(this).val() == '') {
        $(this).val(searchVal);
      }
    });
    
  });
}