(function($){

$.fn.validate = function(options,reset){
  var defaults = {
    submitBy: 'input[type=submit]',
    ignore: '',
    errorClass: 'error',
    onSubmit: null,
    validations: []
  };
  options = $.extend(defaults, options);
  options.scope = this;
  this.data('validate.options',options);
  var submit = $(options.submitBy,this);
  $('*',this).removeClass(this.data('validate.options').errorClass);
  if(reset == true)
    submit.unbind('click');
  $.fn.validate.exec = function(){
    $('*',options.scope).removeClass(options.errorClass);
    $('[error]',options.scope).each( function(){ $($(this).attr('error')).hide() } );
    $.fn.validate.isNull(options.scope, options.ignore);
    $.fn.validate.isEmail(options.scope, options.ignore);
    $.fn.validate.format(options.scope, options.ignore);
    $.each( options.validations, function(){ this(options.scope, options.ignore); })
    var errors = $('.'+options.errorClass,options.scope);
    if(options.onSubmit!=null)
      return options.onSubmit(errors,scope);
    return errors.size()==0? true:false;
  }
  submit.click($.fn.validate.exec);
}
$.extend( 
  $.fn.validate,
  { 
    showError: function($this,scope){
      $this.addClass(scope.data('validate.options').errorClass);
      $($this.attr('error')).show();
    },
    isNull: function(scope,ignore){
      $('[isnull=false]',scope).not(ignore).each(
        function(){
          if( $(this).val() == '' )
            $.fn.validate.showError($(this), scope );
        }
      );
    },
    isEmail: function(scope,ignore){
      $('[isemail]',scope).not(ignore).each(
        function(){
          if(! /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test($(this).val()))
            $.fn.validate.showError($(this), scope );
        }
      );
    },
    format: function(scope,ignore){
      $('[format]',scope).not(ignore).each(
        function(){
          if(!(new RegExp( $(this).attr('format') )).test($(this).val()) )
            $.fn.validate.showError($(this), scope );
        }
      );
    }
  }
);

})(jQuery);

