var contactForm = null;
var APPLICATION = 'RH';
var channel = 'apartments';

var RentalHouses = {
  encode_string:function(val){
        return encodeURIComponent(val);
  },	
  form_token:function(){
        return RentalHouses.encode_string(jQuery("[name=authenticity_token]").val());
  }
}

function ajax_call(path){
  jQuery.get(path, {authenticity_token: RentalHouses.form_token}, function(data) { 
    eval(data);
    expand_first_refinement();
  });
}

function expand_first_refinement() {
  jQuery(".search_refinements li:first").addClass("expand").removeClass("collapse");
}

jQuery(document).ready(function($) {
  jQuery("#show_all_cities").click(function(){
  	document.getElementById('all_cities').style.display = "block";
  	document.getElementById("popular_cities").style.display = "none";
  });
  expand_first_refinement();
  
  if ( jQuery('a[rel*=facebox]').length ) jQuery('a[rel*=facebox]').facebox({ iframe: true});
  if ( jQuery('#facebox').length ) jQuery('#facebox').bgiframe();

  jQuery("div.searchhdr").live("click", function(){
    var element = jQuery(this).parent("li");
    element.toggleClass("expand").toggleClass("collapse");
  });
  
  jQuery("#search_form").onesearch();
  jQuery("#user_search").oneautocomplete({});
  
  jQuery("body").live("onesearch-success", searchSuccess);
  jQuery("body").live("onesearch-error-noresults", noResults);
  jQuery("body").live("onesearch-error-invalid", invalidSearch);
  
  INVALID_QUERIES = ["Enter a city, state or zip", ""];
  jQuery('#user_search').click(function(){
    if(this.value == "Enter a city, state or zip") this.value = "";
  }).blur(function(){
    if(this.value == "") this.value = "Enter a city, state or zip";
  });
  
  jQuery("#search_submit").click(function(){ removeStateFromZip(); });
});

function searchSuccess(data) {
  removeStateFromZip();
  jQuery("#geocode").attr("value", data.geocode);
  jQuery("#miles").attr("value", data.radius);
  jQuery("#sortfield").attr("value", data.sortfield);
  jQuery("#search_form").attr("action", data.seoPath);
  jQuery("#search_form").submit();
}

function removeStateFromZip(){
  var search_val = $("#user_search").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];
    jQuery("#user_search").val(search_val);
  }
}

function noResults(data) {
  alert("No results.");
}

function invalidSearch(data) {
  searchErrorMessage("Invalid search.");
}

function searchErrorMessage(message){
  $("#searchErrors").text(message).show();
  $("body").bind('click.searchErrors', function(){
    $("#searchErrors").hide();
    $("body").unbind('click.searchErrors');
  });
}

function show_more_links(){
  jQuery('.link_none').removeClass('link_none');
  jQuery('.show_more').addClass('link_none');
}

function ext_link(link) {
  window.open(link);
}