search_url = '';

/*
 * Submit callback for the search form.
 */
function geoSearchSubmit(e, advanced) {
  e.preventDefault();
  search_url = '';
  var form = jQuery(e.target);
  var attrib = jQuery('#drilldown');
  var query = form.find('#id_query');
  var location = form.find('#id_location');
  var content_type = '';
  var market_val = form.find('#id_market').val();
  form.find('.submit').addClass('submitted');
  if (form.find('#content_type').val()) {
    content_type = form.find('#content_type').val() + "/";
  }
  search_url = (market_val)? market_val + 'search/' + content_type : form.attr('action');
  search_url += '?' + form.serialize();
  if (advanced) {
   search_url += '&' + attrib.serialize();
   search_url += '&advanced=on';
  }

  if (query.val() && location.val()) {
    var geocoder = new google.maps.Geocoder();
    if(typeof(marketplace_state) != 'undefined') {
        geocoder.geocode({'address': location.val()+' ' + marketplace_state + ' USA'}, onLocationGeocoded);
    } else {
        geocoder.geocode({'address': location.val()+' USA'}, onLocationGeocoded);
    }
  }
  else if(!query.val() && market_val) {
      window.location = market_val;
  }
  else {
    window.location = search_url;
  }
}

/*
 * Submit callback for the save search form.
 */
function saveSearchSubmit(e) {
  search_url = "";
  e.preventDefault();
  var form = jQuery('#search form');
  var attrib = jQuery('#drilldown');
  var query = form.find('#id_q');
  search_url += '?' + form.serialize();
  if (attrib.serialize()) {
   search_url += '&' + attrib.serialize();
  }
  jQuery('#save_search_string').attr('value', search_url);
  jQuery(this).unbind('submit');
  jQuery(this).submit();
}


/*
 * Callback that Geocodes the location field on the search form.
 */
function onLocationGeocoded(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    parseLatLongs(results);
  }
  else {
    window.location = search_url+'&status=geoerror';
  }
}


/*
 * Parses latlong by sending them to Marketplace to parse out
 * zipcodes that aren't serviced by Marketplace. Makes user choose
 * address if there are multiple locations.
 */
function parseLatLongs(results) {
  var latlng_url = '';
  for (var i=0; i<results.length; i++) {
    try {
      var coordinates = results[i].geometry.location;
      latlng_url += (latlng_url)? '|'+coordinates.lng()+','+coordinates.lat(): coordinates.lng()+','+coordinates.lat()
    }
    catch(e) {}
  }

  jQuery.get('/marketplace/validate_coords/', {'coordinates': latlng_url}, function(response) {
    if (response) {
      var found_match = false;
      var latlngs = response.split('|');
      var div = '<div id="choose_address" class="highlight"><ul>';
      div += '<li>We\'ve found multiple locations matching your search, please choose one:</li>';
      for (var i=0; i<latlngs.length; i++) {
        for (var j=0; j<results.length; j++) {
          var latlngs_array = latlngs[i].split(',');
          var coordinates = results[j].geometry.location;
          if ((coordinates.lng() == latlngs_array[0]) && (coordinates.lat() == latlngs_array[1])) {
	    var href = search_url+'&lat='+coordinates.lat()+'&long='+coordinates.lng();
            var li = '<li><a href="'+href+'">'+results[j].formatted_address+'</a></li>';
            div += li;
            if (results[j].formatted_address == jQuery('#id_location').attr('value')) {
              found_match = true;
              window.location = jQuery(li).children('a').attr('href');
            }
          }
        }
      }
      div += '</ul></div>';
      jQuery('#search form').append(div);
      urls = jQuery('#search form #choose_address li a');
      if (urls.length == 1) {
        found_match = true;
        window.location = urls.attr('href');
      }
      if (found_match) {
        jQuery('#search form #choose_address').hide();
      }
    }
    else {
      window.location = search_url+'&status=geoerror';
    }
  }, 'text');
}


jQuery(function() {
  jQuery('#search_form').bind('submit', {advanced: ""}, geoSearchSubmit);
  jQuery('#drilldown').change(function() {
    jQuery('#search_form').trigger('submit', ["on"]);
  });
  // Refresh page if market select box is changed and there
  // are no search terms in the box.
  jQuery('body.directory #id_market').change(function() {
    if (!jQuery('#id_q').val()) {
      if (jQuery('#id_location')) {
        window.location = jQuery(this).val()+'?location='+jQuery('#id_location').val();
      }
      else {
        window.location = jQuery(this).val();
      }
    }
  });
});

