// Display error message and highlight the input box
// Parameters:
//  field - form field
//  message - error-message to be displayed
function showError(field, message) {
  $(field).parent().append("<div class=\"errorMessage\">" + message + "</div>");

  if (message.length < 1) {
    return false;
  }
  $(field).addClass("hasError");
}

// Get the displayed label of the specified field
// Parameters:
//  field - form field
function getFieldLabel(field) {
  // Grab the text from the <label>-tag, related to the specified field
  var fieldId = $(field).attr("id");
  var s = $(field).parents("form").find("label[for=" + fieldId + "]").text();
  if (s.indexOf("*:") != -1) {
    // Remove "*:" from the end of the label
    s = s.substr(0, s.length - 2);
  }
  return s;
}

// Remove all error messages, displayed before
function resetErrors() {
  $(".hasError").removeClass("hasError");
  $("div.errorMessage").remove();
}

// Check if specified required field is valid
// If the field is "email" - check if it contains valid email address (has "@")
// Parameters:
//  field - type of the form field (specify tag, examples: input, textarea), or certain field (specify field id, examples: #name, #email)
// Returns: the amount of errors found
function isFieldValid(field) {
  var errorsFound = 0;

  $(field).each(function(){
    if($(this).hasClass("required")) {  // Find all required fields of specified type
      if ($(this).attr("value") == "") {  // If the field is empty
        label = getFieldLabel(this);      // Get the field's label
        if (label) {
          label = " \"" + label + "\"";
        }
        showError(this, "Please enter" + label + "!"); // Display the error message (example: Please enter "Name")
        errorsFound++;
      } else 
      if ($(this).attr("id") == "email") {  // If the field is not empty and marked as email
        if ($(this).attr("value").indexOf("@") == -1) { // Attempt to find "@" symbol
          showError(this, "This email address is not valid!");
          errorsFound++;
        }
      }
    }
  })

  return errorsFound;
}

// Validate form
// Returns:
//  true - if there is no errors on the form,
//  false - otherwise
function validateForm() {
  var errorsFound = 0;

  errorsFound += isFieldValid("input");
  errorsFound += isFieldValid("textarea");

  return errorsFound == 0;
}

// Add form validation action to the FormSubmit event
$(document).ready(function(){
  $("form").submit(function(){
    resetErrors();
    return validateForm();
  });

});


