$('document').ready(function() {
  var TERM_TO_NUMBER = {
    "weekly": 52,
    "biweekly": 27,
    "monthly": 12,
    "bimonthly": 6,
    "semimonthly": 24,
    "quarterly": 4,
    "semiannually": 2,
    "annually": 1,
    "special": 1
  };

  // Easy money formatting
  function formatMoneyString(money) {
    return '$' + Number(money).toFixed(2);
  }

  // Update pledge total DOM elements
  function setPledgeTotal(value) {
    $('p#pledgeTotalView').text(formatMoneyString(value));
    $('input#pledgeTotal').val(value);
  }

  // Parses pledge rate input and returns pledge amount
  function computePledgeTotal() {
    var pledgeRate = $('input#rate').val();
    var pledgeTerm = $('select#terms').val();
    var pledgeTermMultipler = TERM_TO_NUMBER[pledgeTerm] || 0;
    return parseFloat(pledgeRate, 10) * pledgeTermMultipler;
  }

  // Computes pledge total and updates DOM
  function updatePledgeTotal() {
    var newPledgeTotal = computePledgeTotal();
    if (isNaN(newPledgeTotal)) {
      newPledgeTotal = 0;
    }
    setPledgeTotal(newPledgeTotal);
  }

  // Bind updatePledgeTotal to all pledgeChanger elements
  $('.pledgeChanger').each(function() {
    var el = $(this);
    el.bind('propertychange keyup input paste change', function(e) {
      updatePledgeTotal();
    });
  });

  // Checks is an el is empty and handles missing class
  function checkEmptyInput(el) {
    var isEmpty = '' + el.val() === '';
    if (isEmpty) {
      el.addClass('missing');
    } else {
      el.removeClass('missing');
    }
    return isEmpty;
  }

  // Validates an email field and returns valid status
  function validateEmail(el) {
    var validEmailRegex = /(.)+@(.)+\.(.){2,4}/;
    var emailString = el.val();
    var isValidEmail = validEmailRegex.test(emailString);
    if (!isValidEmail) {
      el.addClass('missing');
    } else {
      el.removeClass('missing');
    }
    return isValidEmail;
  }

  // Bind required value checker
  $('.rqrd').each(function() {
    var el = $(this);
    el.bind('propertychange keyup input paste', function(e) {
      checkEmptyInput(el);
    });
  });

  // Validate email fields
  $('.validateEmail').each(function () {
    var el = $(this);
    el.bind('propertychange keyup input paste', function(e) {
      validateEmail(el);
    });
  });

  // Bind submit handler to validate required form fields
  $('form').submit(function(e) {
    // Ensure all required fields exist
    var allValuesExist = true;
    $('.rqrd').each(function() {
      var el = $(this);
      var isEmpty = checkEmptyInput(el);
      if (isEmpty) {
        allValuesExist = false;
      }
    });

    // Ensure the email address is valid
    var emailEl = $('.validateEmail');
    var isValidEmail = validateEmail(emailEl);

    if (!allValuesExist || !isValidEmail) {
      e.preventDefault();
      return false;
    }
  });

  // Let's go
  updatePledgeTotal();
  $('#noScriptMsg').remove();
});
