/**
*
*  UTF-8 data encode / decode
*  http://www.webtoolkit.info/
*
**/


var Utf8 = {

	// public method for url encoding
	encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// public method for url decoding
	decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}

function SuggestsEvents(ean_originale){
	$('.sugg_carrello').click(function(e) {
        if (typeof(pageTracker)!='undefined') {
            pageTracker._trackEvent(getCategory() + ' - consiglia', 'Suggeriti - Aggiungi al carrello', ean_originale);
        }
        jq132('.apple_overlay .close').trigger('click');
        addToCartMsg.close();
        addToCartMsg = new CartAddBox();
		addToCartMsg.show(true);
		ajaxAddToCart(this);
		e.preventDefault();
	});
	$('.prevPage').click(function() {
      	if (typeof(pageTracker)!='undefined') {
            pageTracker._trackEvent(getCategory() + ' - consiglia', 'Suggeriti - Precedenti Suggeriti', ean_originale);
        }
	});

	$('.nextPage').click(function() {
  	  	if (typeof(pageTracker)!='undefined') {
            pageTracker._trackEvent(getCategory() + ' - consiglia', 'Suggeriti - Prossimi Suggeriti', ean_originale);
        }
	});
}


function CartAddBox(){

	this.constructor = function(){
		this.title = 'Titolo';
		this.body = [];
		this.buttons = [{text: 'OK',callback: function(){}},{text: 'Cancel',callback: function(){}}];
		this.$box = $('<div class="addCartBox" />').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.showMessageWithList = function(){
		this.$box.empty().removeClass('loading');
		var d = $('<div />');
		this.generateHTMLWithList(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.generateHTMLWithList =  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" />');
		var $list = $('<ul />');
		$(this.buttons).each(function(i,o){
			if(o===null) return true;
			var $i = $('<li />');
			var $l = $('<a href="#" />');
			$l.text(o.text);
			$l.click(function(e){t.callback = o.callback;t.callback();e.preventDefault()});
			$i.append($l);
			$list.append($i);
		});
		$buttons.append($list);
		obj.append($buttons);
	}

	this.generateHTML =  function (obj){
		var t = this;
		obj.empty();
		var $h1 = $('<h1/>');
		$h1.html(this.title);
		var $h2 = $('<h2/>');
                $h2.html(this.title);
                if(this.title == 'Prodotto aggiunto al carrello'){
                    obj.append($h2);
                }
                else{
                    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));
            if (o.text == 'Conferma') {
                $l.addClass('accept');
            }
            if (o.text == 'Annulla') {
                $l.addClass('cancel');
            }
            if (o.text == '--> Continua la navigazione'){
                $l.addClass('gonavigate');
            }
            if (o.text == '--> Vai al carrello'){
                $l.addClass('seecart');
            }
			$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(){

	$("a[@href^='/cart.html?add,']").click(function(e){
		if (window.location.pathname == '/cart.html') {
			if (typeof(pageTracker)!='undefined') {
				pageTracker._trackEvent(getCategory(), 'Aggiunto prodotto al carrello senza popup');
			}
			return true;
		}
		addToCartMsg = new CartAddBox();
		addToCartMsg.show(true);
		ajaxAddToCart(this);
		e.preventDefault();
	});
});

function ajaxAddToCart(a){
	var isbn = (/\?add,([0-9]{13})/i.exec(a.href))[1];
	/* Controllo se il prodotto va preso a magazzino perchè ha un prezzo speciale */
	var specialprice = (/\?add,([0-9]{13}),(\d+),(\d+)/i.exec(a.href));
	var producttype = (/\?add,([0-9]{13}),(\d+),(\d+)/i.exec(a.href));
	if(specialprice !== null){
		specialprice = specialprice[2];
	}
	if(producttype !== null){
		producttype = producttype[3];
	}
        /*if (typeof ClickTaleExec != 'undefined') {
		ClickTaleExec('cartAddBox.call(document.getElementById("'+this.id+'")');
	}*/
	if (typeof(pageTracker)!='undefined') {
		pageTracker._trackEvent(getCategory(), 'Aggiungi al Carrello', isbn);
	}
	precheckRequest(isbn,undefined,specialprice,producttype,function(){window.location = a.href});
};

function precheckRequest(isbn,qnt,specialprice,producttype,error){
	var data = {
		action: 'precheck',
		ean: isbn
	};
	if(qnt !== undefined){
		data['qnt'] = parseInt(qnt);
	}
	if(producttype){
		data['producttype'] = producttype;
	}
	if(specialprice){
		data['specialprice'] = specialprice;
	}
	$.ajax({
		data: data,
		cache: false,
		dataType: 'json',
		url: json_ws_url + 'json/cart.json',
		type: 'GET',
		success: ajaxPrecheckSuccess,
		error: error
	});
}

function addRequest(isbn,qnt,specialprice,producttype,error, callback, index){
	var data = {
		action: 'add',
		ean: isbn
	};
	if (typeof eval(callback) == 'undefined')
		callback = ajaxAddToCartSuccess;
	if(qnt !== undefined){
		data['qnt'] = parseInt(qnt);
	}
	if(producttype){
		data['producttype'] = producttype;
	}
	if(specialprice){
		data['specialprice'] = specialprice;
	}
	if(index){
		data['index'] = index;
	}
	$.ajax({
		data: data,
		cache: false,
		dataType: 'json',
		url: json_ws_url + 'json/cart.json',
		type: 'GET',
		success: callback,
		error: error
	});
}

function remindRequest(isbn, email, error){
	var data = {
		action: 'remind',
		ean: isbn,
		mail: email
	};
	$.ajax({
		data: data,
		cache: false,
		dataType: 'json',
		url: json_ws_url + 'json/cart.json',
		type: 'GET',
		success: ajaxRemindRequestSuccess,
		error: error
	});
}

function ajaxPrecheckSuccess(data){
	var book = data.titolo;
	var continua = {
		text: '--> Continua la navigazione',
		callback: function(){this.close()}
	};
	var annulla = {
		text: 'Annulla',
		callback: function(){this.close()}
	};
	var carrello = {
		text: '--> Visualizza il contenuto del carrello',
		callback: function(){window.location = '/cart.html';this.close();}
	};
	if(data.success){
		var qntinput = "<input type=\"text\" id=\"qnt\" style=\"width:20px;text-align:center;margin-left:10px;\" value=\"1\" onfocus=\"this.select()\" \>";
		addToCartMsg.title = 'Aggiungi il prodotto al carrello';
		addToCartMsg.body = [
			'Stai aggiungendo al carrello il prodotto "<em><strong>' + book + '</strong></em>".',
			'Inserisci la quantità che desideri ' + qntinput
		];
		var conferma = {
			text: 'Conferma',
			callback: function(){
			newqnt = $('#qnt').val();
			addRequest(data.ean,newqnt,data.specialprice,data.producttype,function(){window.location = 'cart.html?add,' + data.ean + (data.specialprice?',' + data.specialprice + ',' + data.producttype : '')})}
		};
		addToCartMsg.buttons = [annulla,conferma];
	}else{
		switch(data.error){
			case 'cartFull':
				addToCartMsg.title = 'Impossibile aggiungere il prodotto al carrello';
				addToCartMsg.body = [
				                     'Il prodotto "<em><strong>' + book + '</strong></em>" non è stato aggiunto al carrello.',
				                     "Siamo spiacenti, hai raggiunto il limite massimo di prodotti inseribili nel carrello."
				                     ];
				var concludi = {
						text: '--> Concludi l\'acquisto',
						callback: function(){window.location = '/cart.html';this.close();}
					};
				addToCartMsg.buttons = [null,concludi];
			break;
			case 'invalidEan':
				addToCartMsg.title = 'Impossibile procedere';
				addToCartMsg.body = [
					'Il prodotto selezionato non è stato aggiunto al carrello.',
					'Questo perchè il relativo codice EAN non è valido. Ti invitiamo a <a href="mailto:informazioni@libreriadelgiurista.it">contattarci</a> per segnalare il problema.'
				];
				addToCartMsg.buttons = [{
						text: 'Contattaci',
						callback: function(){window.location='mailto:informazioni@libreriadelgiurista.it';this.close();}
					},continua];
				break;
			case 'flagUnavailable':
				addToCartMsg.title = 'Impossibile aggiungere il prodotto al carrello';
				addToCartMsg.body = [
					'Il prodotto "<em><strong>' + book + '</strong></em>" non è stato aggiunto al carrello.',
					"Questo perchè questo prodotto non è momentaneamente disponibile all'acquisto."
				];
				addToCartMsg.buttons = [null,continua];
				break;
			case 'notPurchasable':
				addToCartMsg.title = 'Impossibile aggiungere il prodotto al carrello';
				addToCartMsg.body = [
					'Il prodotto "<em><strong>' + book + '</strong></em>" non è stato aggiunto al carrello.',
					"Questo perchè questo prodotto si trova in uno dei seguenti stati: Fuori Catalogo/Esaurito/In Ristampa."
				];
				addToCartMsg.buttons = [null,continua];
				break;
			case 'reminder':
				var mailinput = "<input type=\"text\" id=\"email\" style=\"width:50%;text-align:center;margin-left:10px;color:#666\" value=\"" + (data.mail ? data.mail : "---- tua email ----") + "\" onfocus=\"this.select()\"\>";
				addToCartMsg.title = 'Il prodotto è ' + data.pstate;
				if (data.pstate == 'in ristampa breve') {
					addToCartMsg.body = [
					                     'Il prodotto "<em><strong>' + book + '</strong></em>" non è stato aggiunto al carrello ' + 
					                     'perchè è <em>' + data.pstate + '</em>.',
					                     "Puoi chiedere di essere avvisato tramite email non appena sarà disponibile." ,
					                     "Recapito email:</span> " + mailinput
					                     ];
					var remindme = {
							text: 'Avvisatemi quando sarà disponibile',
							callback: function() {
								remindRequest(data.ean, $('#email').val(), function(){})
							}
					};
				} else {
					addToCartMsg.body = [
					                     'Il prodotto "<em><strong>' + book + '</strong></em>" non è stato aggiunto al carrello ' + 
					                     'perchè è <em>' + data.pstate + '</em>.',
					                     "Lo cercheremo nei nostri magazzini di libri usati.",
					                     "Puoi chiedere di essere avvisato tramite email non appena l'avremo reperito." ,
					                     "Recapito email:</span> " + mailinput
					                     ];
					var remindme = {
							text: 'Si avvisatemi',
							callback: function() {
								remindRequest(data.ean, $('#email').val(), function(){})
							}
					};
				}
				
				var nothx = {
						text: 'No grazie',
						callback: function() {
							this.close();
						}
				};
				addToCartMsg.buttons = [remindme,nothx];
				break;
			case 'alreadyPurchased':
				addToCartMsg.title = 'Hai già acquistato questo prodotto';
				addToCartMsg.body = [
					'Il prodotto "<em><strong>' + book + '</strong></em>" non è stato aggiunto al carrello.',
					"Questo perchè hai già comprato questo prodotto, ed è disponibile al download <a href=\"/utenti/downloads/\">nella tua area download</a>."
				];
				addToCartMsg.buttons = [null,continua];
				break;
			case 'alreadyInCart':
				var addqntinput = "<input type=\"text\" id=\"addqnt\" style=\"width:20px;text-align:center;margin-left:10px;\" value=\"1\" onfocus=\"this.select()\"\>";
				addToCartMsg.title = 'Prodotto già presente nel carrello';
				addToCartMsg.body = [
					(data.qnt==1 ? 'Una copia' : data.qnt + ' copie') + ' del prodotto "<em><strong>' + book + '</strong></em>" ' + (data.qnt == 1 ? 'è già presente' : 'sono già presenti') + ' nel tuo carrello.',
					"Puoi scegliere se aggiungerne altre copie o se annullare l'inserimento e continuare la navigazione.",
					'Inserisci il numero di copie che desideri aggiungere ' + addqntinput
				];
				var addACopy = {
					text: "--> Aggiungi altre copie di questo prodotto",
					callback: function(){
						var addqnt = 0;
						addqnt = parseInt($('#addqnt').val());
						addRequest(data.ean,data.qnt+addqnt,data.specialprice,data.producttype,function(){window.location = '/cart.html'});
						this.loadingState();
					}
				};
				addToCartMsg.buttons = [addACopy,continua];
				break;
		}
	}
	addToCartMsg.showMessage();
}
function ajaxSuggestsSuccess(dati){
    $(addToCartMsg).find("div.box-suggests").removeClass("loading-suggests");
    if(dati.length > 0){
    var correlato_item = '';
    var tipologia = '';
    var scrollable_type ='';
    var overlays = '';
    for (i=0; i<dati.length; i++) {
        if(dati[i].type=="cd"){
            correlato_item = correlato_item + '<div class="cont_cd"><a href="/'+dati[i].type+'/'+dati[i].ean+'" target="_blank" onFocus="this.blur()"><img class="cd" src="'+dati[i].image_m+'"/></a><br/><br/><a class="sugg_carrello" href="/cart.html?add,'+dati[i].ean+'&xref='+dati[i].url+'" target="_blank" onFocus="this.blur()"><img src="' + theme_url + 'layout/images/cart-icon-white.gif"/></a></div>';
        }
        else{
            if(dati[i].type=="libri"){
                correlato_item = correlato_item + '<div class="cont"><a rel="#'+dati[i].ean+'"><img class="libri" src="'+dati[i].image_m+'"/></a><br/><p class="dettagli"><a rel="#'+dati[i].ean+'">Dettagli<a/></p><br/><a class="sugg_carrello" href="/cart.html?add,'+dati[i].ean+'&xref='+dati[i].url+'" target="_blank" onFocus="this.blur()"><img src="' + theme_url + 'layout/images/cart-icon-white.gif"/></a></div>';
            }
            else{
                correlato_item = correlato_item + '<div class="cont"><a href="/'+dati[i].type+'/'+dati[i].ean+'" target="_blank" onFocus="this.blur()"><img class="libri" src="'+dati[i].image_m+'"/></a><br/><br/><a class="sugg_carrello" href="/cart.html?add,'+dati[i].ean+'&xref='+dati[i].url+'" target="_blank" onFocus="this.blur()"><img src="' + theme_url + 'layout/images/cart-icon-white.gif" /></a></div>';
            }
        }
        tipologia = dati[i].type;
    }
    if(tipologia=='cd'){
        scrollable_type = '<div class="scrollable_cd">'+
                            '<div class="items_cd">'+
                               correlato_item+
                            '</div>'+
                          '</div>'
    }
    else{
        scrollable_type = '<div class="scrollable_altro">'+
                            '<div class="items">'+
                               correlato_item+
                            '</div>'+
                          '</div>'
    }
    if(tipologia=="libri"){
        for(i=0; i<dati.length; i++){
            var overlay = '<div class="apple_overlay" id="'+ dati[i].ean +'">'+
                                    '<div class="close"></div>'+
                                        '<div class="container_info_big">'+
                                            '<img src="'+dati[i].image_l+'"/>'+
                                            '<div class="container_info_small">'+
                                                '<div class="item_book">'+
                                                    '<span class="left_item">Tipo:</span><span class="right_item">'+'Libro'+'</span>'+
                                                '</div>';
            if(dati[i].title != "" && dati[i].title != null){
                overlay = overlay + '<div class="item_book">'+
                                        '<span class="left_item">Titolo:</span><span class="right_item">'+dati[i].title+'</span>'+
                                    '</div>';
            }
            if(dati[i].authors != "" && dati[i].authors != " "){
                overlay = overlay + '<div class="item_book">'+
                                        '<span class="left_item">Autore:</span><span class="right_item">'+dati[i].authors+'</span>'+
                                    '</div>';
            }
            if(dati[i].publisher != "" && dati[i].publisher != null){
                overlay = overlay + '<div class="item_book">'+
                                        '<span class="left_item">Editore:</span><span class="right_item">'+dati[i].publisher+'</span>'+
                                    '</div>';
            }
            if(dati[i].series != "" && dati[i].series != null){
                overlay = overlay + '<div class="item_book">'+
                                        '<span class="left_item">Collana:</span><span class="right_item">'+dati[i].series+'</span>'+
                                    '</div>';
            }
            if(dati[i].ean != "" && dati[i].ean != null){
                overlay = overlay + '<div class="item_book">'+
                                        '<span class="left_item">Ean:</span><span class="right_item">'+dati[i].ean+'</span>'+
                                    '</div>';
            }
            if(dati[i].price != "" && dati[i].price != null){
                prezzo = dati[i].finalprice +" Euro";
                if(dati[i].discountpercent != ""){
                    prezzo = '<strike>' + dati[i].price + " Euro</strike> - <span class=sconto_overlay>"+dati[i].discountpercent+" di sconto</span> -> "+dati[i].finalprice+" Euro";
                }
                overlay = overlay + '<div class="item_book">'+
                                        '<span class="left_item">Prezzo:</span><span class="right_item">'+prezzo+'</span>'+
                                    '</div>';
            }
            if(dati[i].pages != "" && dati[i].pages != null){
                overlay = overlay + '<div class="item_book">'+
                                        '<span class="left_item">Pagine:</span><span class="right_item">'+dati[i].pages+'</span>'+
                                    '</div>';
            }
            if(dati[i].publishdate != "" && dati[i].publishdate != null){
                overlay = overlay + '<div class="item_book">'+
                                        '<span class="left_item">Data:</span><span class="right_item">'+dati[i].publishdate+'</span>'+
                                    '</div>';
            }
            if(dati[i].weight != "" && dati[i].weight != null){
                overlay = overlay + '<div class="item_book">'+
                                        '<span class="left_item">Peso:</span><span class="right_item">'+dati[i].weight+'</span>'+
                                    '</div>';
            }
            if(dati[i].dimensions != "" && dati[i].dimensions != null){
                overlay = overlay + '<div class="item_book">'+
                                        '<span class="left_item">Dimensioni:</span><span class="right_item">'+dati[i].dimensions+'</span>'+
                                    '</div>';
            }
            if(dati[i].stato != "" && dati[i].stato != null){
                 stato = '';
                 if(dati[i].stato == "Disponibilità immediata"){
                    stato = '<span class="immediata">'+dati[i].stato+'</span>';
                 }
                else{
                    stato = '<span class="nonimmediata">'+dati[i].stato+'</span>';
                }
                overlay = overlay + '</br><div class="item_book">'+
                                        '<span class="left_item">Disponibilità:</span><span class="right_item">'+stato+'</span>'+
                                    '</div>';
                                    
            }
            overlay = overlay + '<br/><div class="item_book"><span class="left_item"></span><span class="right_item"><a id="CartButton" class="sugg_carrello" href="/cart.html?add,'+dati[i].ean+'&xref='+dati[i].url+'" TARGET="_blank" onFocus="this.blur()"/></span></div>';
            descrizione = dati[i].description;
            if(dati[i].description=="" || dati[i].description==null){
                descrizione = "<p>Nessuna descrizione disponibile</p>";
            }
            overlay = overlay +'</div><br/>'+
                                '<div class="contenitore_descrizione">'+
                                    '<span class="description"><strong>Descrizione:</strong><span class="truncated">'+descrizione+'</span></span>'+
                                                '<br/>'+
                                                '<br/>'+
                                    '<p class="centered_fullwidth"><a href="/'+dati[i].type+'/'+dati[i].ean+'">Visualizza i dettagli completi</a></p>'+
                                 '</div>'+
                                '</div>'+
                              '</div>';
        overlays = overlays + overlay;
        }
    }
    $(addToCartMsg).find("div.box-suggests").html(
    '<div class="suggeriti">'+
    '<a class="prevPage browse left"></a>'+
        scrollable_type+
    '<a class="nextPage browse right"></a><br/>'+
    '</div>');
    $("body").append(overlays);

    // initialize scrollable
    if(tipologia=="cd"){
        jq132("div.scrollable_cd").scrollable({
            size: 3
        });
        api = jq132("div.items_cd a[rel]").overlay({effect: 'apple',top:'3%',oneInstance: false, api: true});

    }
    else{
        jq132("div.scrollable_altro").scrollable({
            size: 3
        });
        api = jq132("div.items a[rel]").overlay({effect: 'apple',top:'3%',oneInstance: false, api: true});
    }
    }
    else{
        $('#suggests_title').hide();
    }
	var ean_originale = dati[0].ean_originale;
	SuggestsEvents(ean_originale);
}

function ajaxAddToCartSuccess(data){
	var book = data.titolo;
	var continua = {
		text: '--> Continua la navigazione',
		callback: function(){this.close()}
	};
	var annulla = {
		text: 'Annulla',
		callback: function(){this.close()}
	};
	var carrello = {
		text: '--> Vai al carrello',
		callback: function(){window.location = '/cart.html';this.close();}
	};
	if(data.success){
                var dati = {
                    ean_prodotto: data.ean
                };
                $.ajax({
                    data: dati,
                    cache: false,
                    dataType: 'json',
                    url: json_ws_url + 'json/suggests.json',
                    type: 'GET',
                    success: ajaxSuggestsSuccess,
                    error: function(){}
                });
		addToCartMsg.title = 'Prodotto aggiunto al carrello';
		addToCartMsg.body = [
                    //'<p class="centered" id="suggests_title">Ti consigliamo anche:</p><div class="loading-suggests box-suggests">',
                    //'</div>'
                ];
		addToCartMsg.buttons = [continua, carrello];
		addToCartMsg.showMessage();
		if (typeof(pageTracker)!='undefined') {
			pageTracker._trackEvent(getCategory(), 'Prodotto aggiunto al carrello', data.ean);
		}
	}else{
		switch(data.error){
			case 'invalidQnt':
				addToCartMsg.title = 'Impossibile aggiungere il prodotto al carrello';
				addToCartMsg.body = [
					'Quantità <strong>' + data.qnt + '</strong> non valida per il prodotto "<em><strong>' + book + '</strong></em>"'
				];
				addToCartMsg.buttons = [null,continua];
				addToCartMsg.showMessage();
				break;
			case 'invalidEan':
				addToCartMsg.title = 'Impossibile aggiungere il prodotto al carrello';
				addToCartMsg.body = [
					'Il prodotto selezionato non è stato aggiunto al carrello.',
					'Questo perchè il relativo codice EAN non è valido. Ti invitiamo a <a href="mailto:informazioni@libreriadelgiurista.it">contattarci</a> per segnalare il problema.'
				];
				addToCartMsg.buttons = [{
						text: 'Contattaci',
						callback: function(){window.location='mailto:informazioni@libreriadelgiurista.it';this.close();}
					},continua];
				addToCartMsg.showMessage();
				break;
			/* ci si riferisce al prezzo di listino ma si tratta del nuovo prezzo con lo sconto maggiore disponibile */
			case 'notEnough':
				addToCartMsg.title = 'Disponibilità limitata';
				addToCartMsg.body = [
				    (data.availability > 1 ? ' Sono disponibili' : ' E\' disponibile') + ' solamente ' + data.availability + (data.availability > 1 ? ' pezzi' : ' pezzo') + ' del prodotto "<em><strong>' + book + '</strong></em>" a questo prezzo speciale.',
					"Puoi scegliere se"
				];
				var compradisponibili = {
					text: 'Acquistare ' + data.availability + (data.availability > 1 ? ' pezzi' : ' pezzo') + ' a prezzo speciale',
					callback: function(){
						this.loadingState();
						addRequest(data.ean,data.availability,data.specialprice,data.producttype,function(){window.location = a.href});
						//window.location=unescape(window.location.pathname);
					}
				};
				var compratutto = {
					text: 'Acquistare ' + data.availability + (data.availability > 1 ? ' pezzi' : ' pezzo') + ' a prezzo speciale e ' + (data.qnt-data.availability)+ ' a prezzo di listino',
					callback: function(){
						this.loadingState();
						addRequest(data.ean,data.qnt-data.availability,null,null,function(){window.location = a.href});
						addRequest(data.ean,data.availability,data.specialprice,data.producttype,function(){window.location = a.href});
						//window.location=unescape(window.location.pathname);
					}
				};
				addToCartMsg.buttons = [compradisponibili,compratutto,annulla];
				addToCartMsg.showMessageWithList();
				break;
			case 'notPurchasable':
				addToCartMsg.title = 'Impossibile aggiungere il prodotto al carrello';
				addToCartMsg.body = [
					'Il prodotto "<em><strong>' + book + '</strong></em>" non è stato aggiunto al carrello.',
					"Questo perchè questo prodotto si trova in uno dei seguenti stati: Fuori Catalogo/Esaurito/In Ristampa."
				];
				addToCartMsg.buttons = [null,continua];
				addToCartMsg.showMessage();
				break;
		}
	}

}

function ajaxRemindRequestSuccess(data){
	var book = data.titolo;
	var continua = {
		text: '--> Continua la navigazione',
		callback: function(){this.close()}
	};
	if(data.success){
		addToCartMsg.title = 'Abbiamo preso in consegna la tua richiesta';
		addToCartMsg.body = [
			"Non appena il prodotto sarà disponibile te lo notificheremo all'indirizzo email che ci hai segnalato"
		];
		addToCartMsg.buttons = [continua,null];
		addToCartMsg.showMessage();
	}else{
		switch(data.error){
			case 'genericError':
				addToCartMsg.title = 'Email non valida';
				addToCartMsg.body = [
					"Non è stato possibile registrare correttamente la tua e-mail.",
					"Riprova inserendo un indirizzo email valido."
				];
				addToCartMsg.buttons = [continua,null];
				break;
		}
		addToCartMsg.showMessage();
	}

}