$(function() {
  $('#filter-zip').submit(function(e) {
    e.preventDefault();
    var zip = $(this).find('input[name=zip-field]')[0].value.toLowerCase();
    if (zip.length == 0 || zip == 'narrow companies by zip/state') {
      showAllCompanies();
    } else {
      $('#narrow-text').remove();
      $('.company').hide();
      $('#companies').prepend(narrowText(zip).hide().show('slow'));
      $('#companies .zip_' + zip + ', #companies .state_' + zip).
	parents('.company').show('slow');
    }
    return false;
  });
});

function showAllCompanies() {
  $('input[name=zip-field]')[0].value = 'narrow companies by zip/state';
  $('#narrow-text').hide().remove();
  $('.company').show('slow');
  return false;
}

function narrowText(zip) {
  return $('<p id="narrow-text">' +
	   'Showing companies in zip code / state ' +
	   zip + '.' +
	   ' (<a href="#companies" id="clear-zip-filter" '
	   + 'onclick="showAllCompanies(); return false;">Clear filter</a>)' +
	   '</p>');
}