(function(A){A.fn.extend({euro:function(B){var C={s:",",d:".",c:2};C=A.extend({},C,B);return this.each(function(){var D=(C.n||A(this).text());D=(typeof D==="number")?D:((/\./.test(D))?parseFloat(D):parseInt(D)),s=D<0?"-":"",i=parseInt(D=Math.abs(+D||0).toFixed(C.c))+"",j=(j=i.length)>3?j%3:0;A(this).text(s+(j?i.substr(0,j)+C.s:"")+i.substr(j).replace(/(\d{3})(?=\d)/g,"$1"+C.s)+(C.c?C.d+Math.abs(D-i).toFixed(C.c).slice(2):""));return this})}})})(jQuery);jQuery.euro=function(){var A=jQuery("<span>").text(arguments[0]).euro(arguments[1]);return A.text()};

function is_email(value) 
{
	return /^[\w\-]+(\.[\w\-]+)*@[\w\-]+\.([\w\-]+\.)*[a-z]{2,}$/i.test(value);
}

function aggiorna_carrello(op,cod)
{
	$.post("ajax.php", { action: op, cod: cod }, function(data) {
		$('#sx_carrello').fadeOut(200,function(){$(this).html(data).fadeIn();})
	});	
}

// filtro numerico negli input
function in_array (needle, haystack, argStrict) {
	var key = '',
		strict = !! argStrict;
	if (strict) {
		for (key in haystack) {
			if (haystack[key] === needle) {
				return true;
			}
		}
	} else {
		for (key in haystack) {
			if (haystack[key] == needle) {
				return true;
			}
		}
	}
	return false;
}

function aggiorna_recap_pagamento()
{
	var myId = false;
	$.each($('.pagamento'), function(i, item) {
		if($(item).is(':checked')) { myId = $(item).val(); return false; }
	});
	if(myId)
	{
		$.post("ajax.php", { azione: "recap_pagamento", id: myId }, function(data) {
			var dati = data.split('|');
			$('#pagamento_recap').text(dati[0]);
			$('#modalita_pagamento_label').text(dati[0]);
			$('#costo_pagamento_label').html('');
			if(parseFloat(dati[1]) > 0)
			{
				$('#costo_pagamento_label').html('&euro; ' + $.euro(dati[1],{s:".",d:",",c:2}));
			}
			$('#var_carrello_pagamento').val(dati[1]);
			var totale_complessivo = parseFloat($('#var_carrello_totale').val()) + parseFloat($('#var_carrello_spedizione').val()) + parseFloat($('#var_carrello_pagamento').val());
			$('#checkout_carrello_totale').html('&euro; ' + $.euro(totale_complessivo,{s:".",d:",",c:2}));
		});
	}
}

function aggiorna_recap_spedizione()
{
	var myId = false;
	$.each($('.spedizione'), function(i, item) {
		if($(item).is(':checked')) { myId = $(item).val(); return false; }
	});
	if(myId)
	{
		$.post("ajax.php", { azione: "recap_spedizione", id: myId }, function(data) {
			var dati = data.split('|');
			$('#spedizione_recap').text(dati[0]);
			$('#modalita_spedizione_label').text(dati[0]);
			$('#costo_spedizione_label').html('');
			if(parseFloat(dati[1]) > 0)
			{
				$('#costo_spedizione_label').html('&euro; ' + $.euro(dati[1],{s:".",d:",",c:2}));
			}
			$('#var_carrello_spedizione').val(dati[1]);
			var totale_complessivo = parseFloat($('#var_carrello_totale').val()) + parseFloat($('#var_carrello_spedizione').val()) + parseFloat($('#var_carrello_pagamento').val());
			$('#checkout_carrello_totale').html('&euro; ' + $.euro(totale_complessivo,{s:".",d:",",c:2}));
		});
	}
}

$(function(){
	
    // fancybox
	$("a.fancybox").fancybox();
	
	// box newsletter
	$('#sx_newsletter_scroller').click(function(){
		$('#sx_newsletter_iscriviti').animate({top:'-210px', opacity:0});
		$('#sx_newsletter_cancellati').animate({top:'-210px', opacity:1});
	});
	
	$('#sx_newslettercanc_scroller').click(function(){
		$('#sx_newsletter_iscriviti').animate({top:'0px', opacity:1});
		$('#sx_newsletter_cancellati').animate({top:'0px', opacity:0});
	});

	
	// iscrizione alla newsletter
	$("#sx_newsletter_btn").click(function (event) {
		event.preventDefault();
		if(is_email($('#newsletter_email').val()) && $("#newsletter_nome").val())
		{
			$.post('ajax.php', { azione: "iscrivi", nome: $('#newsletter_nome').val(), email: $('#newsletter_email').val() }, function(data) {
				if(data == 1)
				{
					alert("Adesso sei iscritto alla nostra newsletter!");
					$("#newsletter_nome").val("");
					$("#newsletter_email").val("");
				}
				else
				{
					alert("Il tuo indirizzo e' gia' presente nel nostro archivio!");
				}
			});
		}
		else
		{
			alert('Per favore, riempi i campi richiesti con dati validi.')
		}
    });
	
	// cancellazione
	$("#sx_newslettercanc_btn").click(function (event) {
		event.preventDefault();
		if(is_email($('#newsletter_emailcanc').val()))
		{
			$.post('ajax.php', { azione: "cancella", email: $('#newsletter_emailcanc').val() }, function(data) {
				if(data == 1)
				{
					alert("Il tuo indirizzo e-mail e' stato cancellato dal nostro archivio.");
					init_reverse_flip();
				}
				else
				{
					alert("Questo indirizzo non risulta presente nel nostro archivio!");
				}
			});	
		}
		else
		{
			alert('Per favore, inserisci un indirizzo e-mail valido.')
		}
    });
	
	$(".solonumeri").keypress(function(event) {
		var allowed = [0,8,48,49,50,51,52,53,54,55,56,57];
		if(in_array(event.which,allowed)) { return true; }
		return false;
	});
	
	$(".soloalfanumerici").keypress(function(event) {
		var allowed = [0,8,46,48,49,50,51,52,53,54,55,56,57,113,119,101,114,116,121,117,105,111,112,97,115,100,102,103,104,106,107,108,122,120,99,118,98,110,109,95,8,0];
		if(in_array(event.which,allowed))
		{
			if(event.which == 46 || event.which == 95)
			{
				ultimo_carattere = $(this).val().substr($(this).val().length - 1);
				console.log(ultimo_carattere);
				if(ultimo_carattere != "." && ultimo_carattere != "_" && ultimo_carattere)
				{
					return true;
				}
			}
			else
			{
				return true;
			}
		}
		//console.log(event.which);
		return false;
	});
	
	$('.placeholder').focus(function(){
		if($(this).hasClass('placeholder'))
		{
			$(this).animate({color:'#ffffff'},function(){
				if($(this).attr('id') == "fake_password")
				{
					$(this).css('display','none');
					$('#password').css('display','block').focus();
				}
				else
				{
					$(this).removeClass('placeholder');
					$(this).addClass('|' + $(this).val().replace(/ /g,'|'));
					$(this).val('');
					$(this).css('color','#333333');
				}
			});
		}
	});
	
	$('.placeholder').blur(function(){
		if($(this).val() == '')
		{
			$(this).addClass('placeholder').css('color','#ffffff');
			var classi = $(this).attr('class').split(' ');
			for(i=0;i<classi.length;i++)
			{
				if(classi[i].substring(0,1) == '|')
				{
					$(this).removeClass(classi[i]);
					$(this).val(classi[i].replace(/\|/g,' ').substring(1));
				}
			}
			$(this).animate({color:'#595959'});
		}
	});
	
	$('#dx_collane_lista li').hover(function(){
		$(this).animate({'backgroundColor':'#eee'},200);
	},function(){
		$(this).animate({'backgroundColor':'#fff'},200);
	});
	
	$.widget("custom.catcomplete", $.ui.autocomplete, {
		_renderMenu: function( ul, items ) {
			var self = this,
				currentCategory = "";
			$.each( items, function( index, item ) {
				if ( item.category != currentCategory ) {
					ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
					currentCategory = item.category;
				}
				self._renderItem( ul, item );
			});
		}
	});
		
	$("#autocomplete").catcomplete({
		delay: 300,
		source: 'ajax.php',
		minLength: 3,
		zIndex: 1000,
		select: function( event, ui ) {
			$("#autocomplete").val(ui.item.label);
			document.location.href = ui.item.value;
			return false;
		},
		open: function(event,ui){ $('ul.ui-autocomplete').css('z-index',1000);}
	});
	
	// recap
	if($('.spedizione').length > 0) { aggiorna_recap_spedizione(); }
	if($('.pagamento').length > 0) { aggiorna_recap_pagamento(); }
	$('.pagamento').click(function(){ aggiorna_recap_pagamento(); });
	$('.spedizione').click(function(){ aggiorna_recap_spedizione(); });
	
	// fancybox condizioni
	$("a#condizioni").fancybox({
		'width':650,
		'height':500
	});
		
});
