// OnLoad: Imposta gli handler Javascript x il form del carrello
var $cartForm;

$(function(){
	$cartForm = $('form.frmCart');

	$cartForm.find("div.buttons input").click(function(){$cartForm.buttonClicked = this.name;});
	
	if($cartStep == 1){
		
		$("div.promo").find("#getCode").keypress(function(e) {
			if (e.keyCode == '13')
				$("#applyCode").trigger('click');
		});
	
		$("div.promo").find("#applyCode").click(function(e) {
			e.preventDefault();
			if ($("#getCode").val() == '')
				return;
			$cartForm.buttonClicked = 'cartrefresh';
			$cartForm.find("input#codeSource").val($("#getCode").val());
			$cartForm.find("input#refreshTrigger").val(1);
			
			if (typeof(pageTracker)!='undefined') {
				pageTracker._trackEvent(getCategory(), 'Applicato codice promozione', $("#getCode").val());
			}			
			
			$cartForm.submit();
		});
		
		jq132("a.attentionContinue").live('click', function(e){
			e.preventDefault();
			
			if (typeof(pageTracker)!='undefined') {
				pageTracker._trackEvent(getCategory(), 'Leggi tutto');
			}
			
			$(this).parent().find(".truncate").removeClass('truncate');
			$(this).parent().find('a').toggle();
		});
		
		jq132("a.attentionCollapse").live('click', function(e){
			e.preventDefault();
			$(this).parent().find("div").addClass("truncate");
			$(this).parent().find('a').toggle();
		});
		
		// Carrello vero e proprio con i prodotti
		
		$cartForm.changed = false;
		$cartForm.codechanged = false;

		$("#getCode").change(cartCodeChanged);
		$cartForm.submit(cartFormSubmitStep1);
		
		var shippingDefault = $cartForm.find('input[name=spedizione]').filter(':checked').attr('id');
		
		jq132('input[name=spedizione]').live('click', function(){
			var clicked_input = $(this);
			$cartForm.find('input[name=spedizione]').each(function(){
				if ($(this).attr('id') != clicked_input.attr('id')) {
					$("#" + $(this).val() + "ShippingAlert").hide();
					unwrapTruncated($("#" + $(this).val() + "ShippingAlert"));
				}
			});
			if ($(this).attr('id') == "shippingChkEstero")
				cropCarta(true);
			else cropCarta(false);

			wrapTruncate($("#" + clicked_input.val() + "ShippingAlert"));
			$($("#" + clicked_input.val() + "ShippingAlert")).fadeIn();
			
			if (typeof(shippingDefault) == 'undefined' ||
					shippingDefault != this.id) {
					shippingDefault = undefined;
				if (typeof(pageTracker)!='undefined') {
					pageTracker._trackEvent(getCategory(), 'Cambiato tipo di spedizione', this.id);
				}
			}
		});
		
		$cartForm.find('input[name=spedizione]:checked').trigger('click');
		
		$('a.trackMe').click(function(e){
			if (typeof(pageTracker)!='undefined') {
				pageTracker._trackEvent(getCategory(), 'Altri prodotti', this.id);
			}
			e.preventDefault();
			var $a = this;
			setTimeout(function(){window.location = $a.href;}, 90);
		});
	}else if($cartStep == 11){
		$cartForm.submit(cartFormSubmitStep11);
	}
	else if ($cartStep == 2) {
		// Indirizzi
		$cartForm.submit(cartFormSubmitStep2);
	}
});

/* Funzioni Appoggio x Step 1 */

function wrapTruncate(element) {
	if (! element.hasClass('truncate'))
		return;
	if (element.parent().hasClass('truncateWrapper'))
		return;
	element.wrap('<div class="truncateWrapper attention">');
	element.parent().find('a.attentionContinue').remove();
	element.parent().find('a.attentionCollapse').remove();
	element.parent().append('<a class="attentionContinue" href="#">Leggi tutto</a>');
	element.parent().append('<a class="attentionCollapse" href="#">Chiudi</a>');
	element.parent().find('a.attentionCollapse').hide();
}

function unwrapTruncated(truncated) {
	if (truncated.parent().hasClass('truncateWrapper')) {
		truncated.addClass('truncate');
		truncated.parent().replaceWith(truncated);
	}
}

function cartCodeChanged(){
	if ($("#getCode").val() != '')
		$cartForm.codechanged = true;
	else $cartForm.codechanged = false;
}

function cropCarta(enabled) {
	$cartForm.find('input[type=radio][name=pagamento]').each(function(){
		if (enabled) {
			if ($(this).val() != 'carta')	
				$(this).attr('disabled', true);
		}
		else $(this).attr('disabled', false);
	});
}


function cartFormSubmitStep1(e){
	if ($cartForm.codechanged && $cartForm.buttonClicked == 'cartcheckout') {
		alert("E' necessario cliccare il pulsante 'Applica' per applicare il codice promozione inserito");
		e.preventDefault();
	}
	if($cartForm.buttonClicked == 'cartrefresh')
		return true;
	if($cartForm.buttonClicked != 'cartcheckout')
		return;
	
	var spedizioneOK = false;
	var spedizioneValue = null;
	var pagamentoOK = false;
	var pagamentoValue = null;

	$cartForm.find("input[@name='spedizione']").each(function(){
		if(this.checked == true){
			spedizioneOK = true;
			spedizioneValue = this.value;
		}
		if(this.type == 'hidden'){
			spedizioneOK = true;
			spedizioneValue = this.value;
		}
	});
	
	$cartForm.find("input[@name='pagamento']").each(function(){
		if(this.checked == true && !this.disabled){
			pagamentoOK = true;
			pagamentoValue = this.value;
		}
		if(this.type == 'hidden'){
			pagamentoOK = true;
			pagamentoValue = this.value;
		}
	});

	// FIXME: convertire in JQuery: se il controllo non esiste,
	// allora non richiederlo.
	var eform = document.getElementById('xfrmCart');

	if(!spedizioneOK  && $("input[@name='onlydigital']").val() != 1){
		alert('Devi specificare il metodo di spedizione');
		return false;
	}
	
	if(!pagamentoOK){
		alert('Devi specificare il metodo di pagamento');
		return false;
	}
	
	if(spedizioneValue == 'gratis' && pagamentoValue == 'contrassegno'){
		alert('Attenzione: La spedizione gratuita non è disponibile in contrassegno');
		return false;
	}

	// Tutto OK
	return true;
}

/* Funzioni Appoggio x Step 1.1 (GIFT) */
function cartFormSubmitStep11(e){
	if($cartForm.buttonClicked != 'cartgift') return;

	var giftOK = false;
	var giftValue = null;

	$cartForm.find("input[@name='gift']").each(function(){
		if(this.checked == true){
			giftOK = true;
			giftValue = this.value;
		}
	});

	if(!giftOK){
		alert('Devi specificare il prodotto in omaggio');
		return false;
	}

	// Tutto OK
	return true;
}

function cartFormSubmitStep2(e){
	var shippingOK = $("input[@name='shippingAddress']").val();
	if(!shippingOK && $("input[@name='onlydigital']").val() != 1) {
		alert("Devi specificare l'indirizzo");
		return false;
	}
}

//function
var carousel = {
	'selected': 1,
	'item_max': 1,
	'item_min': 1,
	'cart_cont': 1,
	'item_name': '#dayProduct-',
	'item_class': '#dayProductContainer .dayProduct',
	'container': '#dayProductContainer',
	'cont': '#dayProductCont',
	'init': function () {
		var that = this;
		$(that.container + ' a.prev').click(function () {
			this.blur();
			that.back();
			return false;
		});
		$(that.container + ' a.next').click(function () {
			this.blur();
			that.next();
			return false;
		});
		that.item_max = $(that.item_class).length;
		this.update_cont();
	},
	'update_cont': function () {
		$(this.cont).text(this.selected + '/' + this.item_max);
	},
	'next': function () {
		var that = this;
		$(that.container + ' ' + that.item_name + that.selected).animate({'left':'-280px'},'slow',function () {
			$(this).toggleClass('hide');
			$(this).css('left', 0);
			$(this).css('display', 'none');
			carousel.selected++;
			if (carousel.selected > carousel.item_max) {
				carousel.selected = carousel.item_min
			}
			$(carousel.container + ' ' + carousel.item_name + carousel.selected).fadeIn('slow', function() {
				$(this).toggleClass('hide');
			});
			if (typeof(pageTracker)!='undefined') {
				pageTracker._trackEvent(getCategory(), 'Sfoglia offerte', 'next');
			}
			carousel.update_cont();
		});
	},
	'back': function () {
		var that = this;
		$(that.container + ' ' + that.item_name + that.selected).animate({'left':'280px'},'slow',function () {
			$(this).toggleClass('hide');
			$(this).css('left', 0);
			$(this).css('display', 'none');
			carousel.selected--;
			if (carousel.selected < carousel.item_min) {
				carousel.selected = carousel.item_max
			}
			$(carousel.container + ' ' + carousel.item_name + carousel.selected).fadeIn('slow', function() {
				$(this).toggleClass('hide');
			});
			if (typeof(pageTracker)!='undefined') {
				pageTracker._trackEvent(getCategory(), 'Sfoglia offerte', 'back');
			}
			carousel.update_cont();
		});
	}
}
$(function() {carousel.init()});


$(function() {
	$("a.placeHolder").click(function(e){
		e.preventDefault();
	});
	
	$("#showPromoInfo").fadeOut('slow').fadeIn('slow').fadeOut('slow').fadeIn('slow');
	window.setTimeout(function() {
		$("#promoInfo").fadeOut('slow');
	}, 5000);
	$(".promoattention").hover(
		function() {
			$("#promoInfo").fadeIn();
		},
		function() {
			$("#promoInfo").fadeOut();
		}
	);

    function toggleGiftDetails() {
        if ($('#gift-yes').attr('checked')) {
            $('#gift-details').show();
        } else {
            $('#gift-details').hide();
        }
    }

    toggleGiftDetails();
    $('input.gift-switch').click(function() {
        toggleGiftDetails();
    });
	
	$("input[@name='gift']").click(function(){
		$("input[@name='gift']").each(function(){
			$(this).parent().parent().css({'background-color': '#fff', 'border': 'none'});
		});
		$(this).parent().parent().css({'background-color': '#EFF4FF',  'border': '1px solid #6897F7'});
	});
});

/*** GESTIONE AGGIORNAMENTO CARRELLO 	***/
/*** dipendenza stretta da cart-add.js 	***/
/*** dipendenza stretta da shipping.js 	***/

function load(element) {
		/* wrapping a mano */
		var text = element.html(); 
		element.empty();
		element.html('<span class="textWrapper">' + text + '</span>');
		element.addClass('loading');
		element.find('.textWrapper').width(element.width());
}

function endLoading(element) {
		var content = element.find(".textWrapper").html();
		element.html(content);
		element.removeClass('loading');
}

function updateError() {
	//window.location = "/cart.html";
}

$(function(){
$("td a.drop").click(function(e) {
	e.preventDefault();
	
	var $a = $(this);
	
	if (typeof(pageTracker)!='undefined') {
		pageTracker._trackEvent(getCategory(), 'Richiesta cancellazione', 
				$("input[name='item[" + $a.attr('id') + "]']").val());
	}
	
	var updateCartMsg = new CartAddBox();
	updateCartMsg.show(true);
	updateCartMsg.getOverlay().unbind('click');
	updateCartMsg.getOverlay().click(function(){/* disabled t.close()*/});
	updateCartMsg.title = 'Attenzione';
	var elimina = {
			text: 'Elimina',
			callback: function(){
				$("input[name='drop[" + $a.attr('id') + "]']").val(1);
				$('form.frmCart').buttonClicked = 'cartrefresh';
				$('form.frmCart').find("input#refreshTrigger").val(1);
				updateCartMsg.close();
				
				if (typeof(pageTracker)!='undefined') {
					pageTracker._trackEvent(getCategory(), 'Conferma cancellazione', 
							$("input[name='item[" + $a.attr('id') + "]']").val());
				}
				
				$('form.frmCart').submit();
			}
	};
	var annulla = {
			text: 'Non eliminare',
			callback: function(){
				$("tr#cartentry" + $a.attr('id')).find('td.quantity input').val($("input[name='js_qnts[" + $a.attr('id') + "]']").val());
				updateCartMsg.close();
			}
		};
	updateCartMsg.body = [
	      				'Desideri eliminare il prodotto dal carrello?'
	      			];
	updateCartMsg.buttons = [annulla,elimina];
	updateCartMsg.showMessage();
});
});

$(function(){
	var timeout = new Array();
	
	$("td.quantity input[name^='qnt[']").keyup(function(e){
		var input = $(this);
		timeout[this.name] = setTimeout(function(){
			input.trigger('change');
		}, 4000);
	});
	
	
	$("td.quantity input[name^='qnt[']").change(function(e) {
		var index = (/([0-9])/.exec(this.name))[1];
		
		if (isNaN(parseInt($(this).val()))) {
			$(this).val($("input[name='js_qnts[" + index + "]']").val());
			return;
		}
		
		if ($(this).val() == 0) {
			$("tr#cartentry" + index).find('a.drop').trigger('click');
			return;
		}
		
		if ($("input[name='js_qnts[" + index + "]']").val() == $(this).val())
			return;
		
		var ean = $("input[name='item[" + index + "]']").val();
		
		if (typeof(pageTracker)!='undefined') {
			pageTracker._trackEvent(getCategory(), 'Cambiata quantità', ean);
		}
		
		load($(this).parent().parent().find('td.price div.priceContent'));
		load($('table#cart td.total div.totalContent'));
		load($('p#bigTotal span.price'));
		
		var producttype = $("input[name='types[" + index + "]']").val();
		var qnt = $(this).val();
		if (producttype != '1') {
			var specialprice = $("input[name='prices[" + index + "]']").val();
		}
		if (typeof(eval(timeout + '[\'' + this.name + '\']')) != 'undefined')
			timeout[this.name] = clearTimeout(timeout[this.name]);
		timeout[this.name] = setTimeout(function() {
			addRequest(ean, qnt, specialprice, producttype, updateError, updateRequestSuccess, index);
		}, 2000);
		
		
	});        
});

function updateRequestSuccess(data) {
	var book = data.titolo;
	var $row = $("tr#cartentry" + data.index);
	
	var continua = {
		text: '--> Continua la navigazione',
		callback: function(){ this.close(); }
	};
	var annulla = {
		text: 'Annulla',
		callback: function(){ this.close(); }
	};
	
	endLoading($row.find('td.price div.priceContent'));
	endLoading($('table#cart td.total div.totalContent'));
	endLoading($('p#bigTotal span.price'));

	if (data.success){
		$row.find('td.price div.priceContent').html(data.single_total_tpl);
		$("#productsAmount").val(data.subtotal);
		$('table#cart td.total div.totalContent').text(data.subtotal_tpl + " €");
		$('input[name=spedizione]:checked').trigger('click');
		$("input[name='js_qnts[" + data.index + "]']").val($row.find('td.quantity input').val());
		
		$("table.shippingType tbody").html(data.shipping_table_tpl);
		$("table#cart tfoot tr.remaining").remove();
		$("table#cart tfoot tr.last").before(data.remaining_foot_tpl);
	} else{
		var updateCartMsg = new CartAddBox();
		updateCartMsg.show(true);
		updateCartMsg.getOverlay().unbind('click');
		updateCartMsg.getOverlay().click(function(){/* disabled t.close()*/});
		
		switch(data.error){
		case 'invalidEan':
			updateCartMsg.title = 'Impossibile aggiornare il carrello';
			updateCartMsg.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.'
			];
			updateCartMsg.buttons = [{
					text: 'Contattaci',
					callback: function(){window.location='mailto:informazioni@libreriadelgiurista.it';this.close();}
				},continua];
			updateCartMsg.showMessage();
			break;
		/* ci si riferisce al prezzo di listino ma si tratta del nuovo prezzo con lo sconto maggiore disponibile */
		case 'notEnough':
			if (typeof(pageTracker)!='undefined') {
				pageTracker._trackEvent(getCategory(), 'Split prodotto - proposta', data.ean);
			}
			
			updateCartMsg.title = 'Disponibilità limitata';
			updateCartMsg.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(){
					if (typeof(pageTracker)!='undefined') {
						pageTracker._trackEvent(getCategory(), 'Split prodotto - compra disponibili', data.ean);
					}
					this.loadingState();
					addRequest(data.ean,data.availability,data.specialprice,data.producttype, updateError, updateError, data.index);
				}
			};
			var qnt_fixed = data.curr_qnt + data.qnt - $("input[name='js_qnts[" + data.index + "]']").val();
			var compratutto = {
				text: 'Acquistare ' + data.availability + (data.availability > 1 ? ' pezzi' : ' pezzo') + ' a prezzo speciale e ' + (qnt_fixed-data.availability)+ ' a prezzo di listino',
				callback: function(){
					if (typeof(pageTracker)!='undefined') {
						pageTracker._trackEvent(getCategory(), 'Split prodotto - compra tutto', data.ean);
					}
					this.loadingState();
					addRequest(data.ean,qnt_fixed-data.availability, null, null, updateError, function(){}, data.index);
					addRequest(data.ean,data.availability,data.specialprice,data.producttype, updateError, updateError, data.index);
				}
			};
			var compraniente = {
					text: 'Annulla',
					callback: function(){
						if (typeof(pageTracker)!='undefined') {
							pageTracker._trackEvent(getCategory(), 'Split prodotto - compra niente', data.ean);
						}
						
						$("tr#cartentry" + data.index).find('td.quantity input').val($("input[name='js_qnts[" + data.index + "]']").val());
						this.close(); 
					}
			};
			updateCartMsg.buttons = [compradisponibili,compratutto,compraniente];
			updateCartMsg.showMessageWithList();
			break;
		case 'notPurchasable':
			updateCartMsg.title = 'Impossibile aggiornare il carrello';
			updateCartMsg.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."
			];
			updateCartMsg.buttons = [null,continua];
			updateCartMsg.showMessage();
			break;
			updateCartMsg.showMessage();
		}
	}
}
