// for form input validation
ValidationForm = Class.create({
  initialize: function(css) {
    this.form = $$(css)[0];
    this.validation_errors = [];
    this.error_classname = 'field_with_error'
  },
  validate: function() {
    // reset the validation_errors array
    this.validation_errors = [];
    // we lose the context of 'this' in the each loop
    f = this
    this.form.getElements().each(function(el){
      f.validateOneElement(el);
    });
    if(this.validation_errors.length == 0) {
      // if no errors, submit the form
      this.message = "There weren't any errors";
      return true;
    }else{
      this.message = "There were errors with the following fields:\n\n";
      m = this.message
      this.validation_errors.each(function(er){
        m += ("-- " + er + "\n");
      });
      this.message = m;
      alert(this.message);
      return false;
    }
  },
  validateOneElement: function(element){
    if(!element.hasClassName('required')) {
      return;
    }

    if(element.getValue() == ''){
      element.addClassName(this.error_classname);
      this.validation_errors.push(element.id + " cannot be blank.");
      return;
    }else{
      element.removeClassName(this.error_classname);
    }
    if(element.hasClassName('email')){
      this.validateEmailAddress(element);
    }
  },
  validateEmailAddress: function(email){
    if (email.getValue().indexOf("@") == -1 || email.getValue().indexOf(".") == -1){
       this.validation_errors.push(email.id + " must be a valid email address.");
       email.addClassName(this.error_classname)
    }else{
      email.removeClassName(this.error_classname);
    }
  }
});

Event.observe(window, 'load', function(e){
  // right now this will only work to validate mailer-forms. Need to make it more flexible...
  f = new ValidationForm('form.mailer-form');
  if(f.form){
    Event.observe(f.form, 'submit', function(e){
      if(!f.validate()){
        Event.stop(e);
      }
    });
  }
});