var NewsletterBox = new Class({
	Implements: Options,

	initialize: function(options){
		this.setOptions(options);
		this.form = $('newsletter_form');
		this.checkControls();
	},

	checkControls: function(){
		this.form.addEvent('submit', this.inserisciEmail.bindWithEvent(this));
	},

	inserisciEmail: function(e){
		var e = new Event(e);
		e.stop();
		var email = $('newsletter_email').get('value');
		if (!$defined(email) || (email==''))
			this.printMsg("ERRORE! Inserisci la tua email.");
		else {
			if (this.checkEmail(email)) {
				new Request.JSON({
					url: this.form.get('action'),
					method: this.form.get('method'),
					data:{
						operation:'iscrizione',
						email:email
					}, onComplete: function(r){
						this.printMsg(r.msg);
					}.bind(this)
				}).send();
			} else this.printMsg("ERRORE! Indirizzo email non valido.");
		}
	},

	checkEmail: function(email){
		var pattern  = new RegExp('^([a-z0-9_\.-])+@(([a-z0-9_-])+\\.)+[a-z]{2,6}$');
		if (email.search(pattern)!=-1) return true;
		else return false;
	},

	printMsg: function(msg){
		var box_msg = '';
		if (!$defined(this.form.getElement('#newsletter_msg'))){
			box_msg = new Element('div',{
				id:'newsletter_msg',
				styles:{
					visibility:'hidden',
					opacity:0
				}
			});
			box_msg.inject(this.form,'top');
		} else box_msg = this.form.getElement('#newsletter_msg');
		box_msg.tween('opacity',0);
		box_msg.set('html',msg);
		box_msg.tween('opacity',1);
	}
});

window.addEvent('domready',function(){
	new NewsletterBox();
});
