// This file validates forms on this site to make sure
// they filled out required fields and that certain fields
// have properly formatted information
$(document).ready(function() {
  
  // Bind event to form
  $("#content form").bind("submit", function() {
    
    // Setup variables for errors
    var err = new Array();
    
    // Clean up all errors on the form before proceeding
    $("#content form p.error").remove();
    $("#content form ul.error").remove();
    
    $.each($("#content form input[type='text']"), function() {
      if ($(this).hasClass("error")) {
        $(this).removeClass("error");
      }
    });
    
    // Check if all the required form fields have values that are not empty
    $.each($("#content form input[type='text']"), function() {
      
      // Grab the label to see if this field is required
      var required = false;
      if ($("#content form label[for='" + $(this).attr("id") + "'] span.req").length != 0) {
        required = true;
      }
      
      if (required) {
        
        if ($(this).val() == "") {
          
          // Grab the label
          var labelTxt = $("#content form label[for='" + $(this).attr("id") + "']").html();
          err.push(labelTxt + " needs to be added");
          
          // assign a class to the input field
          $(this).addClass("error");
          
        } else if ($(this).attr("id") == "email" || $(this).attr("id") == "friendemail1") {
          
          // Check to see if they have a valid email address
          var emailPattern = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
          if (!emailPattern.test( $(this).val() )) {
            var labelTxt = $("#content form label[for='" + $(this).attr("id") + "']").html();
            err.push(labelTxt + " is not valid");
          }
          
          // assign a class to the input field
          $(this).addClass("error");
          
        }
      
      }
    });
    
    if (err.length != 0) {
      
      // Display the errors
      $("#content form p").after("<p class=\"error\">Please correct the following fields:</p>");
      $("#content form p.error").after("<ul class=\"error\"></ul>");
      
      $.each(err, function(i, val) {
        $("#content ul.error").append("<li>" + err[i] + "</li>");
      });
      
      return false;
      
    }
    
  });
  
});