$(function(){

	$("input[name='email']").focus(function () {
            $(this).val("");
	});
        $("input[name='email']").blur(function () {
            if($(this).val()==""){
                $(this).val("tua@email.qui");
            }
	});

});



function NewsletterBox(){

	this.constructor = function(){
		this.title = 'Titolo';
		this.body = [];
		this.buttons = [{text: 'OK',callback: function(){}},{text: 'Cancel',callback: function(){}}];
		this.$box = $('<div class="newsletterBox" />').css({display: 'none',zIndex: 1200});
		$(document.body).append(this.$box);
	};

	this.show = function(loading){
		var withOverlay = true;
		if(arguments.length > 1) withOverlay = arguments[1];
		if(loading){
			this.loadingState();
		}else{
			this.generateHTML(this.$box);
		}
		this.applyCSS();
		if(withOverlay){
			var t = this;
			var b = this.$box;
			var o = this.getOverlay();
			o.click(function(){t.close()});
			o.show();
			b.fadeIn()
		}else{
			this.$box.fadeIn();
		}
	};

	this.close = function(){
		var o = this.getOverlay();
		this.$box.fadeOut('normal',function(){
			o.hide();
		});
	}

	this.loadingState = function(){
		this.$box.empty().append('<p>&nbsp;</p>');
		this.$box.addClass('loading');
	};

	this.showMessage = function(){
		this.$box.empty().removeClass('loading');
		var d = $('<div />');
		this.generateHTML(d);
		this.$box.append(d.css('display','none'));
		var tmpH = this.$box.height();
		d.fadeIn();
		this.$box.animate({height: 'show'});
	};

	this.applyCSS = function (){
		var b = this.$box;
		var scrollTop = (window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop);
		b.css({
			position: $.browser.msie && parseInt($.browser.version) <= 6 ? 'absolute' : 'fixed',
			top:	$.browser.msie && parseInt($.browser.version) <= 6 ? scrollTop+50 : 50,
			left: ($(document).width() - b.width())/2
		});
	};

	this.generateHTML =  function (obj){
		var t = this;
		obj.empty();
		var $h1 = $('<h1/>');
		$h1.html(this.title);
		obj.append($h1);
		$(this.body).each(function(i,o){
			obj.append('<p>' + o + '</p>');
		});
		var $buttons = $('<p class="actions" />');
		$(this.buttons).each(function(i,o){
			if(o===null) return true;
			var $l = $('<a href="#" />');
			$l.addClass('link' + (i+1));
			$l.text(o.text);
			$l.click(function(e){t.callback = o.callback;t.callback();e.preventDefault()});
			$buttons.append($l);
		});
		obj.append($buttons);
	}

	// Overlay
	this.getOverlay = function(){
		if(!CartAddBox.prototype.$overlay){
			var o = $('<div id="overlay" />');
			if($.browser.msie && parseInt($.browser.version) <= 6){
				o.css({
					position: 'absolute',
					height: $(document).height(),
					width: $(document).width()
				});
			}
			o.css('opacity',0.5);
			$(document.body).append(o.css({display: 'none',zIndex:999}));
			CartAddBox.prototype.$overlay = o;
		}
		return CartAddBox.prototype.$overlay;
	};

	this.constructor();
};

$(function(){
	$("#newsletter-submit").submit(function(e){
		addNewsletterMsg = new NewsletterBox();
		addNewsletterMsg.show(true);
		ajaxAddNewsletter(this);
		e.preventDefault();
	});
});

$(function(){
	$("#deletenewsletter-submit").submit(function(e){
		addNewsletterMsg = new NewsletterBox();
		addNewsletterMsg.show(true);
		ajaxRemoveNewsletter(this);
		e.preventDefault();
	});
});

function ajaxAddNewsletter(a){
	var email = $("input[@name=email]", a).val();
	addRequestNewsletter(email, function(){/*window.location = '/register.html?email=' + email*/});
}

function ajaxAddFrasegiorno(a){
    var email = $(".frase_giorno_link").attr("id");
    frasegiornoRequestNewsletter(email, function(){/*window.location = '/register.html?email=' + email*/});
}

function ajaxRemoveNewsletter(a){
	var email = $("input[@name=email]", a).val();
	removeRequestNewsletter(email, function(){/*window.location = '/'*/});
}


function frasegiornoRequestNewsletter(email,error){
	var data = {
		action: 'frasegiorno',
		mail: email
	};
	$.ajax({
		data: data,
		cache: false,
		dataType: 'json',
		url: json_ws_url + 'json/newsletter.json',
		type: 'GET',
		success: ajaxFrasegiornoNewsletterSuccess,
		error: error
	});
}


function addRequestNewsletter(email,error){
	var data = {
		action: 'add',
		mail: email
	};
	$.ajax({
		data: data,
		cache: false,
		dataType: 'json',
		url: json_ws_url + 'json/newsletter.json',
		type: 'GET',
		success: ajaxAddNewsletterSuccess,
		error: error
	});
}


function removeRequestNewsletter(email,error){
	var data = {
		action: 'rem',
		mail: email
	};
	$.ajax({
		data: data,
		cache: false,
		dataType: 'json',
		url: json_ws_url + 'json/newsletter.json',
		type: 'GET',
		success: ajaxRemoveNewsletterSuccess,
		error: error
	});
}



function ajaxFrasegiornoNewsletterSuccess(data){
	var continua = {
		text: 'Continua la navigazione',
		callback: function(){this.close()}
	};
	addNewsletterMsg.buttons = [null,continua];
	if(data.success){
		addNewsletterMsg.title = 'Iscrizione avvenuta con successo!';
		addNewsletterMsg.body = [
			"Riceverai giornalmente una brocardo nella tua casella di posta."
		];
		if (typeof(pageTracker)!='undefined') {
			pageTracker._trackPageview("/ajax_newsletter_new_user");
		}
	}else{
		switch(data.error){
			case 'genericError':
				addNewsletterMsg.title = 'Errore nella registrazione';
				addNewsletterMsg.body = [
					"Non è stato possibile registrare correttamente la tua e-mail.",
					"Riprova inserendo un indirizzo email valido."
				];
				break;
			case 'alreadyUsed':
				addNewsletterMsg.title = 'L\'e-mail inserita risulta già in uso';
				addNewsletterMsg.body = [
					"L'indirizzo inserito risulta <strong>già presente</strong> nel nostro archivio."
				];
				break;
		}
	}
	addNewsletterMsg.showMessage();
}




function ajaxAddNewsletterSuccess(data){
        var continua = {
		text: 'Continua la navigazione',
		callback: function(){this.close()}
	};
	addNewsletterMsg.buttons = [null,continua];
	if(data.success){
		addNewsletterMsg.title = 'Iscrizione avvenuta con successo!';
		addNewsletterMsg.body = [
			"Vuoi ricevere quotidianamente anche un brocardo nella tua casella di posta elettronica?",
                        "<p style=\"width:100%;text-align:center\"><strong><a style=\"color:#660000\" class=\"frase_giorno_link\" id=\"" + data.mail + "\" href=\"#\">SI</a></strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>"
                        +"<a style=\"color:#660000\" class=\"frase_giorno_link_2\" id=\"" + data.mail + "\" href=\"#\">NO</a></strong></p>"
		];
		if (typeof(urchinTracker)!='undefined') {
			urchinTracker("/ajax_newsletter_new_user");
		}
	}else{
		switch(data.error){
			case 'genericError':
				addNewsletterMsg.title = 'Errore nella registrazione';
				addNewsletterMsg.body = [
					"Non è stato possibile registrare correttamente la tua e-mail.",
					"Riprova inserendo un indirizzo email valido."
				];
				break;
			case 'alreadyUsed':
				addNewsletterMsg.title = 'L\'e-mail inserita risulta già in uso';
				addNewsletterMsg.body = [
					"L'indirizzo inserito risulta <strong>già presente</strong> nel nostro archivio."
				];
				break;
		}
	}
	addNewsletterMsg.showMessage();
        var layerattuale = addNewsletterMsg;
        $(".frase_giorno_link").click(function(e){
            layerattuale.close();
            addNewsletterMsg = new NewsletterBox();
            addNewsletterMsg.show(true);
            ajaxAddFrasegiorno(this);
            e.preventDefault();
        });
        $(".frase_giorno_link_2").click(function(e){
            layerattuale.close();
            e.preventDefault();
        });
}


function ajaxRemoveNewsletterSuccess(data){
	var continua = {
		text: 'Continua la navigazione',
		callback: function(){this.close()}
	};
	addNewsletterMsg.buttons = [null,continua];
	if(data.success){
		addNewsletterMsg.title = 'Disiscrizione effettuata correttamente';
		addNewsletterMsg.body = [
			"Abbiamo provveduto a disiscriverti dalla newsletter.",
			"Se sei già registrato al nostro sito potrai comunque continuare ad accedere alla tua area utente."
		];
	}else{
		switch(data.error){
			case 'genericError':
				addNewsletterMsg.title = 'Errore nella cancellazione';
				addNewsletterMsg.body = [
					"Non è stato possibile cancellare la tua e-mail.",
					"Riprova inserendo un indirizzo email valido."
				];
				break;
			case 'notFound':
				addNewsletterMsg.title = 'L\'e-mail non è stata trovata';
				addNewsletterMsg.body = [
					"L'indirizzo inserito <strong>non è presente</strong> nel nostro archivio."
				];
				break;
		}
	}
	addNewsletterMsg.showMessage();
}

