(function($) {
  $.fn.nf_validate = function () {
    this.submit(function (event) {
      
      $('.error-message').remove();
      
      var errorFree = true;
      var form = $(this);
      var inputs = form.find(':input').not(':submit');
      var input = {
        
        // Private Methods
        valid:function(obj) {
          
          var valid = true;
          var $obj = $(obj);
          var value = $obj.val();
          var name = $obj.attr('name');
          
          // Email Validation Method
          var isValid = {
            email:function(id) {
              var reg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
              return reg.test(id);
            }
          };
          
          // Checkbox Validation Method
          // var isChecked = {
          //   byId:function(id) {
          //     var checked = $("input[@id="+id+"]:checked").length;
          //     if ( checked === 0 ) {
          //       return false;
          //     }
          //     else { return true; }
          //   }
          // };
          
          // Text Field Conditionals
          if ( $obj.is(':text') ) {
            if ( value === '' ) {
              $obj.prev().append('<span class="error-message">This field is required.</span>');
              valid = false;
            }
            else { 
              if ( name === 'email') {
                if( !isValid.email(value) ) {
                  $obj.prev().append('<span class="error-message">This email is invalid.</span>');
                  valid = false;
                } 
                else { valid = true; }
              }
            }
          }
          
          // Checkbox Conditionals
          // if ( $obj.is(':checkbox') ) {
          //  if ( !isChecked.byId('signup') ) { valid = false; } 
          //  else { valid = true; }
          // }
          
          return valid;
          
        }
      };
      
      // Public
      inputs.each(function() {
        if ( input.valid(this) === false ) { errorFree = false; }
      });
      
      // Prevent Default
      event.preventDefault();
      
      // Ajax
      if (errorFree) {
        $.facebox.loading();             
        $.ajax({
          url: $(this).attr('action'),
          data: $(this).serialize(),
          success: function() {
            $.facebox('<div id="lightbox-success">Thanks for subscribing!</div>');
          }
        });
      }
      
      return errorFree;
      
    });
  };
})(jQuery);
