// this is needed to focus on the first field on initial display of the facebox
$(document).bind('reveal.facebox', function() {
  $('input.lead_first_name').focus();
});

function updateLeadForm() {
  if(!$('.lead_form_wrapper h4').length)
    $('.lead_form_wrapper').prepend("<h4>Contact This Property Manager</h4>");
  
  var required = '<span class="red">*</span>';
  
  $('.lead_first_name > label').html('Name ' + required);              
  $('input.lead_first_name').focus();
  $('.lead_email > label').html('Email ' + required);              
  $('.lead_move_date > label').html('Move Date');
  $('input.lead_move_date').datepicker({beforeShow: reset_datepicker_position});
  $('.lead_message > label').html('Message ' + required);
  
  if($('.lead_message > textarea').html() == "")
    $('.lead_message > textarea').html("Please contact me regarding your listing on RentalHouses.com");
  
  $('.field_error').each( function() {
    var error = $(this).html();
    var label = $(this).siblings('label');
    label.append(" " + error);
    label.addClass("red");
  });
  
  $('.full_errors').css("font-weight", "normal");
  $('.full_errors').addClass("red");
  
  $('.lead_submit').html(
    '<div style="height: 50px;">' +
    '  <input type="image" src="/images/btn_send.gif" id="lead_submit_tag" alt="Send"/>' +
    '</div>'
  );
}

function reset_datepicker_position(input, datepicker) {
  $("#ui-datepicker-div").css('z-index', 100);
  return {};
}

function custom_form_params(overrides){
  defaults = {
    website: "rentalhouses",
    entity_type_id : '0',
    required_fields: ['first_name', 'email', 'message']
  };
  return jQuery.extend(defaults, overrides);
}

function thank_you(params) {
  var queryParameters = [];
  $.each(params, function(key, value) {
    var keyValueString = escape(key) + "=" + escape(value);
    queryParameters.push(keyValueString);
  });
  $('#leadFormDiv').load("/leads/thank_you?" + queryParameters.join("&"));
}

function lead_service_facebox(listing_id) {
  jQuery.facebox($("<div id='leadFormDiv'><img src='/facebox/loading.gif'/></div>").lead_service({
    update_form: updateLeadForm,
    form_params: custom_form_params({
      endeca_id: listing_id,
      entity_id: listing_id
    }),
    lead_saved: function() { 
      thank_you({
        listing_id: listing_id,
        name: $("input.lead_first_name").val(),
        email: $("input.lead_email").val()
      }); 
    }
  }));
}