jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});

$(document).ready(function() {
  $('.text_field').focus(function() {
    $(this).parent().next().children('.good').hide();
    $(this).parent().next().children('.form_error').hide();
    $(this).parent().next().children('.info').show();
  });
  $('.text_field').blur(function() {
    // find any errors 
    var val = $(this).val();
    var isValid = true;
    var errMsg = "";
    if ($(this).hasClass('vrequired')) {
      if (val.length == 0) {
        isValid = false;
        errMsg = "required";
      }
    }
    else if ($(this).hasClass('vemail')) {
      var Regex =/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      if (!Regex.test($(this).val())) {
        isValid = false;
        errMsg = "invalid email address";
      }
    }
    else if ($(this).hasClass('vpassword')) {
      if (val.length < 6) {
        isValid = false;
        errMsg = "must be at least 6 characters long";
      }
    }
    else if ($(this).hasClass('vpasswordconfirm')) {
      if (val.length < 6) {
        isValid = false;
        errMsg = "must be at least 6 characters long";
      }
      else {
        //we need to find the other password field and check it
        $el = $(this);
        //locate the form so we can search for the other field
        while($el.attr("tagName").toLowerCase() != "form"){$el = $el.parent();}
        $el = $el.find(".vpassword");
        //store text of other password field
        var checkValue = $el.val();
        if (val != checkValue) {
          isValid = false;
          errMsg = "confirmation doesn't match";
        }
      } 
    }
    else if ($(this).hasClass('vusername')) {
      if (val.length == 0) {
        isValid = false;
        errMsg = "Required";
      }
      else {
        var Regex = /^[a-zA-Z0-9]+$/;
        if (!Regex.test(val)) {
          isValid = false;
          errMsg = "Invalid username.  Use letters and numbers only."
        }
      }
    }

    // update the status
    $(this).parent().next().children('.info').hide();
    if (isValid) {
      $(this).parent().next().children('.good').show();
    }
    else {
      $(this).parent().next().children('.form_error').show();
      $(this).parent().next().children('.form_error').html(errMsg);
    }

  });
  $('.text_field')[0].focus();
});
