$(function () {
  TAB_ORDER = {
    Residential: 0,
    Rental: 1,
    Commercial: 2,
    Land: 3
  };

  // Artificially "click" the active tabs
  function setActiveTab() {
    if (window.currentSearchListingType) {
      $("#revise_search_form .tabs").tabs().click(TAB_ORDER[currentSearchListingType]);
    }
  }

  // Reloads the counts on the revise search form
  function reloadCounts() {
    var defaultTabName = "residential";

    if (window.currentSearchListingType) {
      defaultTabName = currentSearchListingType.toLowerCase();
    }

    $("#revise_search_form #" + defaultTabName + "_form .field").each(function () {
      getSearchCount(this);
    });
  }

  // Go to the server and get the count for the search
  function getSearchCount(field_div) {
    var field = $(field_div);
    var count = field.find('.count');
    count.html('Counting...');
    var data = {};
    field.prevAll(".field").andSelf().find(":input").each(function () {
      data[this.name] = $(this).val();
    });
    $.get('/listings/count', data, function (response) {
      if (response == '1000') {
        response = '1000+';
      }
      count.html(response + ' Results');
    });
  }

  function openSearchPanel(panelId) {
    $("#" + panelId).jqmShow();

    // It doesn't make sense to make a round trip for counts for new searches
    if (panelId === "revise_search_form") {
      reloadCounts();
    }
  }

  // Make search form popups
  $('.search_form').jqm({
    modal: false
  });

  // Add class to close button so closes Search Popup
  $(".search_form .close_button a").addClass("jqmClose");

  // Search Form Tabs
  $("#new_search_form .tabs").tabs("#new_search_form .pane");
  $("#revise_search_form .tabs").tabs("#revise_search_form .pane");

  $(".search_button a").click(function (e) {
    openSearchPanel($(this).parent('.search_button').attr('id').replace('_button', '_form'));
    e.stopPropagation();

    return false;
  });

  setActiveTab();

  function post_search(field_div) {
    var field = $(field_div);
    field.nextAll(".field").find(":input").each(function () {
      $(this).attr('disabled', true);
    });
    field.parent("form").submit();
  }

  // Reset form with "Start a New Search" button
  $(".search_form form .reset a").click(function () {
    f = $(this).parents('form');
    // no easy way to reset in jquery, apparently
    f.find(":input").not(':button, :submit, :reset').val('');
    f.find('.field').hide().find('.results .count').html('&nbsp;');
    f.find('.field:first').show();
    return false;
  });

  // Submit whole form with "Save Search" button
  $(".search_form form .save a").click(function (event) {
    $(this).parents('form').submit();
    event.stopPropagation();
    return false;
  });

  // Use JS to append View Results links to each field
  $(".search_form form .field:not(.submit)").each(function () {
    $(this).append($(
      "<div class='results'>" +
        "<a href='#' class='submit_link'>" +
        "<span class='view'>View all</span>" +
        "<span class='count'>&nbsp;</span>" +
        "</a>" +
      "</div>"
    ));

    $(this).find('.submit_link').click(function () {
      post_search($(this).parents('.field'));
      return false;
    });

    $(this).find('input:not(#location_search), select').change(function () {
      field = $(this).parents('.field');
      getSearchCount(field);
      field.nextAll('.field:visible').each(function () {
        getSearchCount(this);
      });
      field.next('.field').show();
    });
  });
});
