if(console == null) {
  var console = {
    log: function() {
      // do nothing
    }
  };
}

function isDefined(variable) {
  return (typeof(window[variable]) !== "undefined");
}

function mortgage_constant(monthly_interest_rate, month_count) {
  return ((monthly_interest_rate) * Math.pow((1 + (monthly_interest_rate)), month_count)) / ((Math.pow((1 + (monthly_interest_rate)), month_count)) - 1);
}

function monthly_payment_for(rate, price, years) {
  var mrate = (rate / 12) / 100;
  return price * mortgage_constant(mrate, 12 * years);
}

function flashSuccess() {
  $(".success").fadeIn(1000).animate({opacity: 1.0}, 5000, function () {
    $(".success").animate({opacity: 0.0}, 1000).slideUp(250, function () {
      $(".success").remove();
    });
  });
}

function flashFailure() {
  $(".failure").fadeIn(1000).animate({opacity: 1.0}, 10000, function () {
    $(".failure").animate({opacity: 0.0}, 1000).slideUp(250, function () {
      $(".failure").remove();
    });
  });
}

$(document).ready(function () {
  // autocompletion for location search fields
  $(".location_search_fields").livequery(function () {
    // w = $(this).width();
    // 
    // if (isNaN(w) || w == 0) {
      w = 300;
    // }

    $(this).find("input:text").autocomplete("/locations.mini", {
      minChars: 0,
      width: w,
      cacheLength: 0,
      matchContains: true,
      autoFill: false
    }).result(function (event, data, formatted) { 
      hidden_field = $(this).siblings("input:hidden");

      if (hidden_field.size() === 0) {
        // If there's no hidden field, this input is not within a form.
        // So let's redirect to them the same page but for the new location.
        window.location.href = window.location.href.replace(/locations\/\d+/, "locations/" + data[1]);
      } else {
        // There is a hidden field, so set its value.
        // The user can submit the form at their convenience.
        hidden_field.val(data[1]);
        hidden_field.trigger('change');
      }
    });
  });

  // Make registration and login form popups
  $('#person_registration_login, #send_to_friend_form, #schedule_showing_form').jqm({
    modal: false
  });

  // Registration links should open registration popup instead
  $("[href='/register'],[href='/login']").click(function () {
    $.scrollTo(0, 0, { duration: 1000 });
    $('#person_registration_login').jqmShow();
    $('#person_name').blur(); // auto-focus is hiding the hint
    return false;
  });

  // Invite Friend links should trigger popup
  $("[href='/share/friend_invite']").click(function (event) {
    $('#friend_invite_form').jqmShow(); 
    event.stopPropagation();
    return false;
  });

  // Print button
  $("#main_actions .print").click(function () {
    window.print();
    return false;
  });

  // Friend Invite Popup
  $('#friend_invite_form').jqm({
    modal: false
  });

  // Next Step button in registration form
  $(".steptwo_trigger").click(function () {
    $(this).removeAttr("href").animate({opacity: 0.6}, 500).addClass("disabled");
    $("#login").fadeOut(500);
    $("#register_step_two").animate({ opacity: 1.0 }, 500, function () {
      $(this).fadeIn(500);
    });
  });

  // Reset registration form when closed
  $(".jqmOverlay, .jqmClose").click(function () {
    $(".steptwo_trigger").attr("href", "#").animate({opacity: 1.0}, 500).removeClass("disabled");
    $("#register_step_two").fadeOut(500);
    $("#login").animate({ opacity: 1.0 }, 500, function () {
      $(this).fadeIn(500);
    });
  });

  // AJAX-ify the invite a friend form
  $("#friend_invite_form form").ajaxForm({ 
    success: function (data) { 
      $("#friend_invite_form").jqmHide();
      $("#page").prepend('<p class="success" style="display: none;">Your invitation has been successfully sent to ' + $('#friend_invite_recipient_name').val() + '.</p>');
      flashSuccess();
    },
    error: function () {
      $("#friend_invite_form").append('<p class="failure" style="display: none;">There has been an error in submitting the form. Please wait a few moments and try to submit the form again.</p>');
      flashFailure();
    }
  });

  // Add ajax uploading for profile image
  $('#image_uploader img').each(function () {
    AjaxUpload(this, {
      action: '/avatar',
      name: 'avatar',
      responseType: 'json',
      autoSubmit: true,
      onSubmit: function (file, extension) {
        $('#image_uploader img').hide();
        $('#image_uploader').append("<div class='spinner'>Uploading...</div>");
      },
      onComplete: function (file, response) {
        $('#image_uploader .spinner').remove();
        if (response.url) {
          $('#image_uploader img').attr('src', response.url).fadeIn();
        } else if (response.error) {
          alert("Error uploading file: " + response.error);
          $('#image_uploader img').fadeIn();
        } else {
          alert("Error uploading file.");
          $('#image_uploader img').fadeIn();
        }
      }
    });
  });

  // Ajaxify the login
  $("#login form").ajaxForm({
    success: function (data) {
      var json = eval('(' + data + ')');
      window.location = json.url;
    },
    error: function () {
      $("#login .failure").remove();
      $("#login form").append('<p class="failure" style="display: none;">Sorry, we were unable to find a login with that email and password.</p>');
      flashFailure();
    }
  });

  // use proxy_click attribute to proxy the click event to another node
  $("[proxy_click]").live('click', function (event) {
    $($(this).attr('proxy_click')).click();
    event.stopPropagation();
    return false;
  });

  // Lock down links to listing pages unless logged in
  if (!logged_in) {
    // this runs when a matching item is added to the dom
    $("[href^='/listings/']").livequery(function () {
      var $this = $(this);
      // Change text, unless the link wraps an image
      if ($this.find('img')[0] == null) {
        $this.html("Login to View");
      }
      $this.addClass('login_for_details');
      $this.attr('title', "Login to View");

      // Add IDX logos to all feed listing information clickthrus
      var wrapper = $this.parents('.listing').find('.item_content');

      if (wrapper.find('.idx')[0] === null) {
        wrapper.append("<img src='/images/logos/idx_thumb.gif' class='idx' />");
      }

      // Add IDX logos to all slider listing information clickthrus
      var container = $this.parents('.listing');
      wrapper = (container).find('.image_link');
      if (container.find('.idx')[0] === null) {
        wrapper.before("<img src='/images/logos/idx_thumb.gif' class='idx' />");
      }
    });

    $("[href^='/listings/']").live('click', function (event) {
      $.scrollTo(0, 0, { duration: 1000});
      // set return_to inputs to return to target link
      $("#login_return_to, #registration_return_to").val($(this).attr('href'));
      // reveal login
      $('#person_registration_login').jqmShow();
      $('#person_name').blur(); // auto-focus is hiding the hint
      event.stopPropagation();
      return false;
    });
  }

  // Fix IE bug where clicking a checkbox or radio button doesn't trigger
  // the change handler until blurred.
  if ($.browser.msie) {
    $('input:radio, input:checkbox').click(function () {
      this.blur();
      this.focus();
    });
  }

  // Submit button revert to sending and deactivate during send to prevent multi-clicks
  $("input:submit").click(function () {
    var text = $(this).val();
    $(this).ajaxStart(function () {
      $(this).val("Sending...").attr("disabled", "disabled");
    }).ajaxStop(function () {
      $(this).attr('disabled', null).val(text);
    });
  });

  // Post a Comment Sidebar
  form = $("#location_comment_form");
  if (form[0]) {
    form.jqm();
    $("#main_actions .post_comment a").click(function (event) {
      $("#location_comment_form").jqmShow();
      event.stopPropagation();
      return false;
    });
  }

  // Make save form a popup
  $('#save_form').jqm({
    modal: false
  });

  $(".save").click(function (event) {
    $('#save_form').jqmShow();
    event.stopPropagation();
    return false;
  });

  // Close the Smart Bar Modals
  $(".close_button a").click(function (event) {
    var close = $(this).parent().parent();
    $(close).jqmHide();
    event.stopPropagation();
    return false;
  });

  // Saved searches box toggle
  $('#searches_button').click(function (event) {
    $this = $(this);
    $('#search_container').slideToggle();
    if ($this.hasClass("closed")) {
      $this.removeClass("closed")
           .find('img')
           .attr('src', "/images/buttons/smart_bar_searches_open.png");
    } else {
      $this.addClass("closed")
           .find('img')
           .attr('src', "/images/buttons/smart_bar_searches_closed.png");
    }

    event.stopPropagation();
    return false;
  });

  // Searches Promotion
  $("#search_container .promote_search").click(function (event) {
    _this = this;
    $.ajax({
      url: $(this).attr('href'),
      type: 'POST',
      data: '_method=put',
      success: function () {
        var search = $(_this).parent();
        $("#my_preferred_search .search_title").html(search.find('.search_title').html());
        search.remove();
      },
      error: function () {
        alert('Unable to make this your preferred search.');
      }
    });
    event.stopPropagation();
    return false;
  });

  // Searches Deletion
  $("#search_container .delete_search").click(function (event) {
    _this = this;
    $.ajax({
      url: $(this).attr('href'),
      type: 'POST',
      data: '_method=delete',
      success: function () {
        $(_this).parent().fadeOut();
      },
      error: function () {
        alert('Unable to remove this search.');
      }
    });
    event.stopPropagation();
    return false;
  });

  //Save Search Reveal Naming Form
  $(".pane .save").click(function (event) {
    $("#save_form").slideToggle(100);
    event.stopPropagation();
    return false;
  });

  // Help Request Form
  $("#help_request form").ajaxForm({
    beforeSubmit: function () {
      // stops submission if valid() returns false;
      return $("#help_request form").valid();
    },
    success: function () {
      $("#help_request form").
        html("<p>Thanks for your thoughts, we will respond as soon as possible. " +
             "<a href='#' class='cancel'>Close</a></p>");
    },
    error: function () {
      alert("Sorry, the server didn't respond, please try again.");
    }
  });

  $("#help_request .open").live('click', function (event) {
    openHelpRequest();
    event.stopPropagation();
    return false;
  });

  $("#help_request .cancel, #help_request .close").live('click', function (event) {
    closeHelpRequest();
    event.stopPropagation();
    return false;
  });

  function openHelpRequest() {
    $("#help_request").animate({left: '50px'}, 1000)
      .find('.open')
      .removeClass('open')
      .addClass('close');
  }

  function closeHelpRequest() {
    $("#help_request").animate({left: '-450px'}, 1000)
      .find('.close')
      .removeClass('close')
      .addClass('open');
  }

  // enable validation on all forms
  $('form').each(function () { 
    $(this).validate({
      'messages': {
        'person[email]': {
          'remote': "An account with this email already exists."
        }
      }
    });
  });
});

// Add Array#indexOf to Internet Explorer
if (!Array.indexOf) {
  Array.prototype.indexOf = function (obj) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] == obj) {
        return i;
      }
    }
    return -1;
  };
}
