
function positionLightbox() {
  $(".lead_form").addClass("lightbox").css({
    "zIndex": 2002,
    "left": $(window).width() / 2 - $(".lead_form").width() / 2,
    "top": $(window).height() / 2 - $(".lead_form").height() / 2
  });
}

function generateRefinements() {
  var refinements = [];
  var selected = selectedRefinements();
  if (selected.baths) { refinements.push(selected.baths.text().replace('+', '') + '-baths') }
  if (selected.beds) { refinements.push(selected.beds.text().replace('+', '') + '-beds') }
  if (selected.property_type) { refinements.push(PROPERTY_TYPES_HASH[selected.property_type.text()]) }
  if (selected.min_price) { refinements.push(selected.min_price.text().replace(/\$|,/g, '') + '-minimum-price') }
  if (selected.max_price) { refinements.push(selected.max_price.text().replace(/\$|,/g, '') + '-maximum-price') }
  if (selected.miles) { refinements.push(selected.miles.val()); }

  var endeca_ids = [];
  if (selected.baths) { endeca_ids.push(Number(selected.baths.val()).toString(36)); }
  if (selected.beds) { endeca_ids.push(Number(selected.beds.val()).toString(36)); }
  if (selected.property_type) { endeca_ids.push(Number(selected.property_type.val()).toString(36)); }
  if (selected.min_price) { endeca_ids.push(Number(selected.min_price.val()).toString(36)); }
  if (selected.max_price) { endeca_ids.push(Number(selected.max_price.val()).toString(36)); }

  if (endeca_ids.length) {
    refinements.push(endeca_ids.join('+'));
  }

  return refinements.join('-').toLowerCase();
};

function selectedRefinements() {
  var refinements = {};
  var selections = $("#baths option:selected, #beds option:selected, #property_type option:selected, #min_price option:selected, #max_price option:selected, #miles option:selected", this.object);
  $.each(selections, function(index, element) {
    element = $(element);
    if (element.val() != "") {
      refinements[element.parent().attr('id')] = element;
    }
  });
  return refinements;
};

$(document).ready(function(){

  $("#rapid_request_submit").click(function() {
    
    var blankRegex = /^\s*$/
    var seoPath = $("#seopath").val()
    
    // make sure we have a valid search executed and stored
    if (blankRegex.exec(seoPath)) {
      show_error("Please search for a location");
      return
    }       
    
    // make sure all fields are filled in.
    var fields = ["#contact_first_name", "#contact_last_name", "#contact_zip", "#contact_email"];
    for (elId in fields) {
      var value = $(fields[elId]).val()
      if (blankRegex.exec(value)) {
        show_error("Please fill in all required fields")
        return
      }
    }

    var url = '/rapid_request' + normalizeSeopath(seoPath) + generateRefinements()
    $(this).parents("form").unbind("submit").attr("action", url).submit();
  })

  // make sure that the seoPath is NHG friendly. this is something that should ultimately be
  // fixed in onesearch
  function normalizeSeopath(seoPath) {
    return seoPath.replace(/^(zip|apartments)/,'')
  }

  function onesearchSuccess(event) {
    if ($(".rapid_request").length == 0) {
      window.location = "/New-Homes" + normalizeSeopath(event.seoPath);
    }
  }

  function onesearchNoResults(event) {
    show_error("There are no results matching the search terms.")
  }

  function onesearchInvalidQuery(event) {
    show_error("Please enter a city, state or a Zip code to search.")
  }

  $($("#user_search").parents("form").get(0)).onesearch();
  $("#user_search").oneautocomplete({});

  $("body").bind("onesearch-success", onesearchSuccess);
  $("body").bind("onesearch-error-noresults", onesearchNoResults);
  $("body").bind("onesearch-error-invalid", onesearchInvalidQuery);

  /* save the original search field text */
  $("#user_search").click(function() {
    if (!$(this).data("text")) {
      $(this).data("text", $(this).val());
    }
    
    // clear it if the text is the original text
    if ($(this).data("text") == $(this).val()) {
      $(this).val("");
    }
  })
  
  $("#user_search").blur(function() {
    if ($(this).val() == "") {
      $(this).val($(this).data("text"))
    }
  })

  $("#search_button").click(function() {
    $(this).parents("form").submit();
  })

  $.facebox.settings.opacity = 0.8;

  $('input[name=lead[phone]]').livequery(function() {
    $(this).mask("(999) 999-9999");
  });

  $("#message_body").keypress(function(e) {
    return e.which == 0 || e.which == 8 || $(this).val().length < 250;
  });
  
  /*
   * Handles the submit for all lead forms 
   */
  $('#consumer_lead form').livequery(function() {
    var container = $(this).parent('.lead_form');
    $(this).ajaxForm({
      dataType: "json",
      success: function(data) {
        if(data.location) {
          window.location = data.location;
        } else if(data.body) {
          container.replaceWith(data.body);
          $('#consumer_lead').bgiframe();
          //positionLightbox();
          //$.facebox(container);
        }
       }
     });
  });
  
  
  $("form input[name='lead[session_id]']").livequery(function() {
    var wt_session = "no_webtrend_session";
    if (WT.vt_sid) {
      wt_session = WT.vt_sid;
    }
    $(this).val(wt_session);
  });
  
  $('#new_lead #lead_submit').live('click', function(){
    $(this).parents('form').submit();
    $(this).attr('disabled', true);
    return false;
  });

  $('a.btn_free_brochure, a.btn_free_brochure2, a.btn_free_brochure3, a.special_offer').live('click',function(e) {
    e.preventDefault();
    var link = $(this);
    $('.brochure .lead_form, #featured_communities .lead_form, .special_offer .lead_form, .search_result .lead_form').remove();
    $.get(link.attr('href'),function(data) {
      var featured = link.parents('#featured_communities');
      var isFeatured = featured.length;
      if(isFeatured) {
        featured.find('a.btn_feature_pause:visible').click();
      }
      
      
/*
      $("#lead_lightbox").css("zIndex", 2001).after(data).show().live("click", function(){
        $(".lead_form").remove();
        $(this).hide();
      });
      
      positionLightbox();
      */
   
      $.facebox(data);
      $('#consumer_lead').bgiframe();
      
      if(!isFeatured && $.browser.msie && $.browser.version=="6.0") {
        $('.lead_form').hide();
        $('.lead_form').show();
      }
    });
  });

  $('a.btn_close').live('click',function(e) {
    $(this).parent().remove();
    // $("#lead_lightbox").hide();
    $(document).trigger('close.facebox');
    return false;
  });

  $('#featured_communities a.btn_close').live('click',function(e) {
    $("#featured_communities a.btn_feature_play:visible").click();
  });

  $('a.icon_video, a.icon_vtour').bind('click', function(e) {
    var link = $(this);
    var url = link.attr('href');
    var community_path = link.parents(".community").find("a[id*=community_path_]").attr('href');
    var width = '800px';
    var height = '600px';
    if (link.hasClass('icon_video')) {
      width = '620px';
      height = '400px';
    }
    window.open(url, null, 'width=' + width + ',height=' + height + ',menubar=no,scrollbars=yes,toolbar=no,status=no,left=0,top=0,resizable=no');
    if (community_path) {
      redirect(community_path);
    }
    return false;
  });

});

function hover_changes_background(optional_selector) {
  var selector = optional_selector || ".tier .search_result";
  var div = $(selector);
  div.mouseover(function() { $(this).addClass('hover') });
  div.mouseout(function() { $(this).removeClass('hover') });
}

function redirect(url) {
  location.href = url;
}

function show_error(msg) {
  msg = typeof(msg) == 'undefined' ? 'There were no results returned' : msg;
  $("#error_message").text(msg).show();
  var fadeError = function(){ $("#error_message").fadeOut(); }
  window.setTimeout(fadeError, 2000);
}

function PathTemplate(template) {
  var self = this;
  var path = template;

  this.replace = function(hash) {
    jQuery.each(hash, function(key, value){
      path = path.replace('[' + key + ']', value);
    });
    return path;
  };

  this.path = function(hash) {
    if (hash && typeof(hash) == "object") {
      self.replace(hash);
    }
    return path;
  };
}

function toggleTR(linkId) {
  var pTR = $("#"+linkId).parent().parent().get(0);
  if ($("#"+linkId).hasClass("btn_hide")) {
    $("#"+linkId).addClass("btn_expand");
    $("#"+linkId).removeClass("btn_hide");
	  $(pTR).next().css("display", "none");
  } else {
    $("#"+linkId).removeClass("btn_expand");
    $("#"+linkId).addClass("btn_hide");
	  $(pTR).next().css("display", "");
  }
}

