$(document).ready(function() {
  jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
  }
});

function calc_payment() {
  var ratef = $('#rate');
  var prinf = $('#principal');
  var numf = $('#payments');
  var resf = $('#result');
  var resDiv = resf.parent();
  
  var rate = eval(ratef.val());
  var principal = eval(prinf.val());
  var num = eval(numf.val());
  
  var good = false;
  
  if (typeof(rate) == "number") {
      good = true;
      ratef.css('background-color', 'white');
  } else {
      good = false;
      ratef.css('background-color', '#ffff99');
  }
  
  if (typeof(principal) == "number") {
      if (good != false) good = true;
      prinf.css('background-color', 'white');
  } else {
      good = false;
      prinf.css('background-color', '#ffff99');
  }
  
  if (typeof(num) == "number") {
      if (good != false) good = true;
      numf.css('background-color', 'white');
  } else {
      good = false;
      numf.css('background-color', '#ffff99');
  }
  
  if (good) {
      rate = rate / 1200;
      var top_eq = Math.pow((1 + rate), num) * rate * principal;
      var bot_eq = Math.pow((1 + rate), num) - 1;
      var eq = top_eq / bot_eq;
      var final_result = "$" + (Math.round(eq * 100) / 100);
      var dec = (final_result.length - final_result.indexOf('.')) - 1;
      
      if (dec == 1) final_result = final_result + '0';
      else if (dec > 2) final_result = final_result + '.00';
      
      resf.html(final_result);
      resDiv.show();
  } else {
      resDiv.hide();
  }
}

function display_calc() {
  calc_payment();
  $('#calculator').toggle().center().find('#principal').focus();
}

function close_calc() {
  $('#calculator').toggle();
}

function change_image(id, src, captid, str) {
  document.getElementById(id).src = src;
  document.getElementById(captid).innerHTML = str;
}
