var search_url = '';


/*
 * Submit callback for the search form.
 */
function geoSearchSubmit(e) {
  e.preventDefault();
  var form = jQuery(e.target);
  var query = form.find('#id_query');
  var location = form.find('#id_location');
  var market_val = form.find('#id_market').val();

  form.find('.submit').addClass('submitted');

  search_url = (market_val)? market_val + 'search/': form.attr('action');
  search_url += '?q=' + escape(query.val());

  if (query.val() && location.val()) {
    var geocoder = new GClientGeocoder();
    geocoder.getLocations(location.val()+' USA', onLocationGeocoded);
  }
  else if(!query.val() && market_val) {
    window.location = market_val;
  }
  else {
    window.location = search_url;
  }
}


/*
 * Callback that Geocodes the location field on the search form.
 */
function onLocationGeocoded(response) {
  if (response['Status']['code'] == 200) {
    var placemarks = response['Placemark'];
    parseLatLongs(placemarks);
  }
  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(placemarks) {
  var latlng_url = '';
  for (var i=0; i<placemarks.length; i++) {
    try {
      var coordinates = placemarks[i]['Point']['coordinates'];
      latlng_url += (latlng_url)? '|'+coordinates[0]+','+coordinates[1]: coordinates[0]+','+coordinates[1]
    }
    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<placemarks.length; j++) {
          var latlngs_array = latlngs[i].split(',');
          var coordinates = placemarks[j]['Point']['coordinates'];
          if ((coordinates[0] == latlngs_array[0]) && (coordinates[1] == latlngs_array[1])) {
	    li = '<li><a href="'+search_url+'&location='+placemarks[j]['address']+'&lat='+coordinates[1]+'&long='+coordinates[0]+'&rad=20">'+placemarks[j]['address']+'</a></li>';
            div += li;
	    if (placemarks[j]['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', geoSearchSubmit);

  // 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_query').val()) {
      if (jQuery('#id_location')) {
        window.location = jQuery(this).val()+'?location='+jQuery('#id_location').val();
      }
      else {
        window.location = jQuery(this).val();
      }
    }
  });
});
