$(document).ready(function() {
  $('body').addClass('enhanced');
  
  $('div#mortgage-calculator form').submit(function() {
    var $this = $(this);
    
    // Retrieve the submitted values.
    var mortgage  = $this.find('#mortgage-required').val().replace(',', '');
    var duration  = $this.find('#repayment-period').val();
    var rate      = $this.find('#interest-rate').val();
    
    // Simple RegExp to match numbers (commas are not supported).
    var regexp    = /^\d*(\.?)\d+$/;
    
    // Test the submitted values.
    if (!regexp.test(mortgage) || !regexp.test(duration) || !regexp.test(rate)) {
      // Error code goes here.
      alert('Please enter some valid values.');
      return false;
    }
    
    // Calculate the results.
    rate /= 100;
    
    // Repayment at the specified rate.
    var std_repayment = ((mortgage * rate) / 12) * (1 / (1 - (Math.pow(1 / (1 + rate), duration))));
    var std_interest = (mortgage * rate) / 12;
    
    // Repayment at 8%.
    var eightpc_repayment = ((mortgage * 0.08) / 12) * (1 / (1 - (Math.pow((1 / 1.08), duration))));
    var eightpc_interest = (mortgage * 0.08) / 12;
    
    // Populate the results.
    $results = $this.parent('div').find('dl');      
    $results.find('dd:nth-child(2)').html('&pound;' + std_repayment.toFixed(2));
    $results.find('dd:nth-child(4)').html('&pound;' + std_interest.toFixed(2));
    $results.find('dd:nth-child(6)').html('&pound;' + eightpc_repayment.toFixed(2));
    $results.find('dd:nth-child(8)').html('&pound;' + eightpc_interest.toFixed(2));
    
    // Display the results.
    $results.slideDown(650, function() {
      $results.fadeIn(900);
    });
    
    return false;   // Don't submit the form.
  });
  
});