var APPLICATION = 'AG';
var channel = "apartments";
var valid_key = false;
var default_records_per_page = 20;
var dummy_search_options = ['Price-Min','Price-Max','Bedrooms','Bathrooms','Property Name'];

$(document).ready(function() {
	
	$("form#search_form").onesearch();
	$("input#search_input").oneautocomplete({ highlight: highlightItem });

	$("body").bind("onesearch-success", seoPathSuccess);
	$("body").bind("onesearch-error-noresults", seoPathError);
	$("body").bind("onesearch-error-invalid", invalidSearchTerm);
	
	INVALID_QUERIES = ["City, State or Zip", "College, State", "Military Base, State", ""];
});

function highlightItem(value, term) {
  return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
}

function exists(value) {
  return ((value != null) && (value.length > 0) && ($.inArray(value, dummy_search_options) == -1) );
}


function get_search_parameters(){
  var opts = {};
  opts.pricerange    = $("#pricerange").val();
  opts.bedrooms      = $("#bedrooms").val();
  opts.bathrooms     = $("#fullbaths").val();  
  opts.property_name = $("#property").val();
  opts.user_search   = $("#user_search").val();
  opts.sort_by       = $('#search_form #sort_by').val();
  return opts;
}

function build_query_params() {
  var query_params = "";
  var parts = [];
	var dimensionIds = []
  var search_opts = get_search_parameters();

  if (exists(search_opts.pricerange)) {
    dimensionIds.push(search_opts.pricerange);
  }

  if (exists(search_opts.bedrooms)) {
    dimensionIds.push(search_opts.bedrooms);
  }

  if (exists(search_opts.bathrooms)) {
    dimensionIds.push(search_opts.bathrooms);
  }
  
  if(channel == 'corporate' && exists($("#term").val())) {
    parts.push("term=" + $("#term").val());
  }

  if(exists(search_opts.property_name)) { 
    jQuery("#search_form").append("<input type='hidden' name='propertyname' value='" + search_opts.property_name + "'/>");
  }

  if(exists(search_opts.sort_by)) { 
    parts.push("sort_by=" + search_opts.sort_by);
  }

  parts.push("limit=" + default_records_per_page);
  
  for (var i=0; i< parts.length; i++) {
    if (i > 0) {
      query_params += "&";
    }
    query_params += parts[i];
  }

	jQuery(dimensionIds).each(function(index, value){
		if (index == 0) {
			query_params += "&node=";
		}
		query_params += value;
		if (index < dimensionIds.length - 1) {
			query_params += " ";
		}
	});
	
  return query_params;
}

function seoPathSuccess(event) {

   var query_params = build_query_params();
  $('#search_form').append("<input type=\"hidden\" id=\"options\" name=\"options\" value=\"" + query_params +  "\"/>");
   var search_val = $("#search_input").val();
   //if the search_val contains 5 digits (a possible zip code), replace the field value with just the 5 digits
	var vals = search_val.match(/.*(\d{5,5})/);
	if(vals != null && vals[1] != null) {
		search_val = vals[1];
		$("#user_search").val(search_val);
	}
	var post_url = APARTMENTGUIDE_URL + event.seoPath;
  $("#search_form").attr("action", post_url);
  $("#search_form").submit();

}

//Rails/Application should repond with HTML status 422 upon error to ensure the error callback is executed.
function seoPathError(event) {
	searchErrorMessage(event.message);
}

function invalidSearchTerm(event) {
	searchErrorMessage("You must enter a city, state or a zip code before this search can be performed.");
}

function searchErrorMessage(message){
  $("#search_errors").text(message).show();
  if ($.browser.msie) { 
    $("#searchCitiesStates, #searchOptions").hide();
  }
  $("body").bind('click.search_errors', function(){
    $("#search_errors").hide();
    if ($.browser.msie) { 
      $("#searchCitiesStates, #searchOptions").show();
    }
    $("body").unbind('click.search_errors');
  });
}



