FormCheck = Class.create();
FormCheck.prototype =
{
  initialize: function(form)
	{
    var options = Object.extend(
		{
			errore: 'empty',
			alertError: true
		}, options || {});

    this.form = $(form);
		this.options = options;

		// Faccio il bind delle funzioni
    this.eventSubmit = this.onSubmit.bindAsEventListener(this);

		// Registro i vari eventi
    this.registerEvents();
  },

	registerEvents: function()
	{
		Event.observe(this.form, "submit", this.eventSubmit);

		// Scorro tutti i campi del form e vedo se devo controllare che siano o meno vuoti
		var fc = this;

		this.form.getElements().each(function(input)
		{
			var validate = input.readAttribute('validate');
			if (validate != null)
			{
				if ((input.type == 'text') || (input.type == 'password') || (input.type == 'file'))
				{
					Event.observe(input, 'blur', fc.updateStatus.bindAsEventListener(fc,input));
					Event.observe(input, 'keyup', fc.updateStatus.bindAsEventListener(fc,input));
				}
				else if (input.type == 'select-one')
					Event.observe(input, 'change', fc.updateStatus.bindAsEventListener(fc,input));
				else
					alert('Unknown type '+input.type);

				fc.updateStatus(fc,input,false);
			}
		});
	},

	updateStatus: function(evento,input,showError)
	{
		var validate = input.readAttribute('validate').split(" ");
		var type = input.type;
		var value = input.value;

		input.removeClassName(this.options.errore);
		for (i = 0; i < validate.length; i++)
		{
			var valo = validate[i].split("=");

			var check = valo[0];
			var opt = valo[1];
			if (checker.verify[check] != undefined)
			{
				if (!checker.verify[check](value,type,opt))
				{
					input.addClassName(this.options.errore);

					if (showError)
					{
						var errore = checker.error[check];
						errore = errore.replace("{opt}",opt);
						this.showError(input,errore);
					}

					return false;
				}
			}
		}

		return true;
	},

	showError: function(input,error)
	{
		input.focus();
		if (this.options.alertError)
			alert(error);
	},

	onSubmit: function(evento)
	{
		// Scorro tutti i campi del form e vedo se devo controllare che siano o meno vuoti
		var fc = this;
		var allOk = true;

		try
		{
			this.form.getElements().each(function(input)
			{
				var validate = input.readAttribute('validate');
				if ((input.visible()) && (validate != null))
				{
					var ok = fc.updateStatus(fc,input,true);
					if (!ok)
					{
						allOk = false;
						if (fc.options.alertError)
							throw 'uscita';
					}
				}
			});
		}
		catch (e)
		{
			if (e !== 'uscita')
				throw e;
		}

		if (allOk)
			return true;
		else
		{
			Event.stop(evento);
			return false;
		}
	},
  destroy: function()
	{
		// Tolgo gli osservatori sui vari eventi
    Event.stopObserving(this.form, "submit", this.eventSubmit);
  }
};

var checker =
{
	verify:
	{
		notempty: function(value,type)
		{
			if ((type == 'text') || (type == 'password'))
			{
				if (value != '')
					return true;
				else
					return false;
			}
			else if (type == 'select-one')
			{
				if ((value != '') && (value != '-1') && (value != '0'))
					return true;
				else
					return false;
			}
			else if (type == 'file')
			{
				if (value != '')
					return true;
				else
					return false;
			}
			else
				alert('Uknown type:'+type);
		},
		min: function(val,type,opt)
		{
			if (val.length >= opt)
				return true;
			else
				return false;
		},
		max: function(val,type,opt)
		{
			if (val.length <= opt)
				return true;
			else
				return false;
		},
		alpha: function(val)
		{
			var reg = /^[a-zA-z\s]*$/;
			return reg.test(val);
		},
		digit: function(val)
		{
			var reg = /^[-]?\d*(\.\d*)?$/;
			return reg.test(val);
		},
		number: function(val)
		{
			var reg = /^[\d\s]*$/;
			return reg.test(val);
		},
		alphanum: function(val)
		{
			var reg = /^[a-zA-Z0-9\s]*$/;
			return reg.test(val);
		},
		cf: function(val)
		{
			if (val.length == 16)
				return true;
			else
				return false;
		},
		email: function(val)
		{
			var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			return reg.test(val);
		},
		cc: function(val)
		{
			var reg = /^((4\d{3})|(5[1-5]\d{2})|(6011))([- ])?\d{4}([- ])?\d{4}([- ])?\d{4}|3[4,7]\d{13}$/;
			return reg.test(val);
		},
		iban: function(val)
		{
			if ((val.length == 27) || (val == ''))
				return true;
			else
				return false;
		}
	},
	error:
	{
		notempty: 'Il campo non puo\' essere vuoto',
		min: 'Inserisca almeno {opt} caratteri',
		max: 'Inserisca al massimo {opt} lettere',
		alpha: 'Inserisca solo testo',
		digit: 'Inserisca solo numeri',
		alphanum:'Inserisca solo lettere e numeri',
		number: 'Inserisca solo numeri',
		cf: 'Inserisca un codice fiscale valido',
		email: 'Inserisca un e-mail valida',
		cc: 'Inserisca una carta di credito',
		iban: 'Inserisci un codice IBAN corretto'
	}
};

function addFormCheck()
{
	for (var i = 0; i < document.forms.length; i++)
		new FormCheck(document.forms[i]);
}
//Event.observe(window, 'load', addFormCheck);
FastInit.addOnLoad(addFormCheck);
