/**
 * Handles basic validation and error messaging on the "contact us" form.
 */
$(function () {
  var form = $("#signup"),
      hasErrors;

  function inputName(el) {
    var selector = "input [for='" + $(el).attr("id") + "']";
    return $(selector).text();
  }

  function errorMessageSelector(el) {
    return "#" + $(el).attr("id") + "-error-message";
  }

  function showError(el, message) {
    $(errorMessageSelector(el)).text(message);
    $(errorMessageSelector(el)).show();
    $(el).addClass("error");
  };

  function hideError(el) {
    $(errorMessageSelector(el)).hide();
    $(el).removeClass("error");
  };

  function checkRequiredFields(form) {
    form.find('input[type="text"], input[type="email"]').each(function () {
      if ($.trim($(this).val()) === "") {
        hasErrors = true;
        showError(this, inputName(this) + " is required.");
      } else {
        hideError(this);
      }
    });
  }

  function checkEmailFormat(form) {
    form.find('input[type="email"]').each(function () {
      if (!$(this).val().match(/^[^@]+@[^@]+\.[^@]+$/)) {
        hasErrors = true;
        showError(this, inputName(this) + " must be a valid email address.");
      } else {
        hideError(this);
      }
    });
  }

  form.submit(function () {
    hasErrors = false;

    checkRequiredFields(form);
    checkEmailFormat(form);

    return !hasErrors;
  });
});

