/*
 * Common Functions
 * Pablo Ricco - 2009
 */


function is_null(value)
{
	return (typeof(value) == 'undefined' || value == null)
}

function show_ok(elementId, text)
{
	$(elementId).update(text);
	$(elementId).show();
	return true;
}

function hide_ok(elementId, text)
{
	$(elementId).hide();
	return true;
}

function show_error(elementId, text)
{
	$(elementId).update(text);
	$(elementId).show();
	return false;
}

function hide_error(elementId, text)
{
	$(elementId).hide();
	return true;
}

/*
 * Validators
 */
FormValidator = Class.create({
  initialize: function(formId, validators, events) {
  	
  	this.__validateFunction = this.validate.bind(this);
  	
  	this.form = $(formId);
  	this.validators = validators;
  	this.events = $H(events);
    this.events.keys().each(function(eventName, index) {
    	this.form.observe(eventName, this.__validateFunction);
    }, this);
    
  },
  validate: function(event) {
  	var result = true;
    this.validators.each(function(value, index) {
      result = value.form_validate(event) && result;
    });
 		if (!result)
 			Event.stop(event);
 		else
 		{
	 		var f = this.events.get(event.type);
	  		if (f != null)
		  		f(event);
  	}
  },
  add: function(validator) {
  	this.validators[this.validators.length] = validator;
  },
  remove: function(id) {
  	for(i=0; i<this.validators.length; i++)
  	{
  		if(id == this.validators[i].id)
  		{
  			this.validators[i].remove();
  			this.validators[i] = null;
  		}
  	}
  	this.validators = this.validators.compact();
  }
});

Validator = Class.create({
  initialize: function(elementId, events, form_events, extra) {
  	
  	this.__validateFunction = this.validate.bind(this);
  	
  	this.id = elementId;
  	this.element = $(elementId);
  	this.extra = extra;
  	this.form_events = $H(form_events);
  	this.events = $H(events);  	
    this.events.keys().each(function(eventName, index) {
    	this.element.observe(eventName, this.__validateFunction);
    }, this);
  },
  form_validate: function(event) {
  	var f = this.form_events.get(event.type);
  	if (f != null)
  		return f(event, this.element, this.extra);
  	else
  		return true;
  },
  validate: function(event) {
  	var f = this.events.get(event.type);
  	if (f != null)
  		f(event, this.element);
  },
  remove: function() {
    this.events.keys().each(function(eventName, index) {
    	this.element.stopObserving(eventName, this.__validateFunction);
    }, this);
  }
});
