if(!Iooma) var Iooma = {};

Iooma.FChecker = {};

Iooma.FChecker.Element = Class.create({
 initialize: function(args) {
  this.args = {
   id: '',
   test: Prototype.emptyFunction,
   onChange: Prototype.emptyFunction,
   onFocus: Prototype.emptyFunction
  };
  Object.extend(this.args, args || {});

  this.form = null;
  this.el = $(this.args.id);
  this.ok = false;
  this.focus = false;

  this.el.observe('blur', this.onBlur.bind(this))
         .observe('keyup', this.onAction.bind(this))
	 .observe('focus', this.onFocus.bind(this));
 },

 setForm: function(form) {
  this.form = form;
  if(!this.el.value.blank()) this.onAction();
 },

 onFocus: function() {
  this.focus = true;
  this.args.onFocus(this.el);
 },

 onBlur: function() {
  this.focus = false;
  this.onAction();
 },

 onAction: function() {
  var ok = this.args.test(this.el.value);
  if(this.ok != ok) {
   this.form.onChange(ok);
   this.ok = ok;
  }
  this.args.onChange(this);
 }
});

Iooma.FChecker.Form = Class.create({
 initialize: function(args) {
  this.args = {
   onOk: Prototype.emptyFunction,
   onKo: Prototype.emptyFunction
  };
  Object.extend(this.args, args || {});

  this.count = 0;
 },
 
 observe: function(input) {
  if(!this.ok) this.onChange(false);
  input.setForm(this);
  return this;
 },

 onChange: function(ok) {
  var count = this.count + (ok?-1:1);
  if(count == 0 && this.count != 0) this.args.onOk();
  else if(count != 0 && this.count == 0) this.args.onKo();
  this.count = count;
 }
});

Iooma.FChecker.mailTest = function(val) {
 return /^[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,4}$/.test(val);
};

Iooma.FChecker.blackTest = function(val) {
 return !val.blank();
};

