//à	
function makeScrollable(wrapper, scrollable){
				// Get jQuery elements
				var wrapper = $(wrapper), scrollable = $(scrollable);
				
				// Hide images until they are not loaded
				scrollable.hide();
				var loading = $('<div class="loading">Loading...</div>').appendTo(wrapper);
				
				// Set function that will check if all images are loaded
				var interval = setInterval(function(){
					var images = scrollable.find('img');
					var completed = 0;
					
					// Counts number of images that are succesfully loaded
					images.each(function(){
						if (this.complete) completed++;	
					});
					
					if (completed == images.length){
						clearInterval(interval);
						// Timeout added to fix problem with Chrome
						setTimeout(function(){
							
							loading.hide();
							// Remove scrollbars	
							wrapper.css({overflow: 'hidden'});						
							
							scrollable.slideDown('slow', function(){
								enable();	
							});					
						}, 1000);	
					}
				}, 100);
				
				function enable(){
					// height of area at the top at bottom, that don't respond to mousemove
					var inactiveMargin = 99;					
					// Cache for performance
					var wrapperWidth = wrapper.width();
					var wrapperHeight = wrapper.height();
					// Using outer height to include padding too
					var scrollableHeight = scrollable.outerHeight() + 2*inactiveMargin;
					// Do not cache wrapperOffset, because it can change when user resizes window
					// We could use onresize event, but it's just not worth doing that 
					// var wrapperOffset = wrapper.offset();
					
					// Create a invisible tooltip
					/*var tooltip = $('<div class="sc_menu_tooltip"></div>')
						.css('opacity', 0)
						.appendTo(wrapper);
				
					// Save menu titles
					scrollable.find('a').each(function(){				
						$(this).data('tooltipText', this.title);				
					});
					*/
					// Remove default tooltip
					scrollable.find('a').removeAttr('title');		
					// Remove default tooltip in IE
					scrollable.find('img').removeAttr('alt');	
					
					var lastTarget;
					//When user move mouse over menu			
					wrapper.mousemove(function(e){
						// Save target
						lastTarget = e.target;
						
						var wrapperOffset = wrapper.offset();
						/*
						var tooltipLeft = e.pageX - wrapperOffset.left;
						// Do not let tooltip to move out of menu.
						// Because overflow is set to hidden, we will not be able too see it 
						tooltipLeft = Math.min(tooltipLeft, wrapperWidth - 75); //tooltip.outerWidth());
						
						var tooltipTop = e.pageY - wrapperOffset.top + wrapper.scrollTop() - 40;
						// Move tooltip under the mouse when we are in the higher part of the menu
						if (e.pageY - wrapperOffset.top < wrapperHeight/2){
							tooltipTop += 80;
						}				
						tooltip.css({top: tooltipTop, left: tooltipLeft});				
						*/
						// Scroll menu
						var top = (e.pageY -  wrapperOffset.top) * (scrollableHeight - wrapperHeight) / wrapperHeight - inactiveMargin;
						if (top < 0){
							top = 0;
						}			
						wrapper.scrollTop(top);
					});
					/*
					// Setting interval helps solving perfomance problems in IE
					var interval = setInterval(function(){
						if (!lastTarget) return;	
													
						var currentText = tooltip.text();
						
						if (lastTarget.nodeName == 'IMG'){					
							// We've attached data to a link, not image
							var newText = $(lastTarget).parent().data('tooltipText');

							// Show tooltip with the new text
							if (currentText != newText) {
								tooltip
									.stop(true)
									.css('opacity', 0)	
									.text(newText)
									.animate({opacity: 1}, 1000);
							}					
						}
					}, 200);
					
					// Hide tooltip when leaving menu
					wrapper.mouseleave(function(){
						lastTarget = false;
						tooltip.stop(true).css('opacity', 0).text('');
					});			
					*/
					/*
					//Usage of hover event resulted in performance problems
					scrollable.find('a').hover(function(){
						tooltip
							.stop()
							.css('opacity', 0)
							.text($(this).data('tooltipText'))
							.animate({opacity: 1}, 1000);
				
					}, function(){
						tooltip
							.stop()
							.animate({opacity: 0}, 300);
					});
					*/			
				}
			}
			
//à

$(document).ready(function(){

	//nav top\
	$("ul.subnav").parent().append("<span></span>");
	$("ul.topnav li span").click(function() {
		$(this).parent().find("ul.subnav").slideDown('fast').show();
		$(this).parent().hover(function() {
		}, function(){
			$(this).parent().find("ul.subnav").slideUp('slow'); 
		});
		}).hover(function() {
			$(this).addClass("subhover"); 
		}, function(){	
			$(this).removeClass("subhover");
	});
	//fast search
	if($("#search_nome").length > 0) 
	{
		$('#search_nome').bind("keyup",function() {  fastShlookup();});
		$('#search_nome').bind("blur",function() { fastShfill();});	
		if($('#fastSh').length > 0)
		{
			$('#fastSh').css("top",$('#search_nome').offset()["top"]+25);
			$('#fastSh').css("left",$('#search_nome').offset()["left"]+5);
		}
	}

		
	
		
	if($(".hprivacy").length > 0)
	{
		$(".hprivacy").attr("href",$(".hprivacy").attr("href")+"?embed");
		$(".hprivacy").colorbox({width:"800px", height:"80%"});
	}
	if($(".dologin").length > 0)
	{
		$(".dologin").attr("href",$(".dologin").attr("href")+"?embed");
		$(".dologin").colorbox({width:"300px", height:"190px"});
	}
	if($(".goDetOrd").length > 0)
	{
		$(".goDetOrd").colorbox({width:"600px", height:"80%"});
	}
	if($(".goIndSped").length > 0)
	{
		$(".goIndSped").colorbox({width:"600px", height:"80%", overlayClose : false});
	}
	if($(".goDetCupon").length > 0)
	{
		$(".goDetCupon").colorbox({width:"650px", height:"80%"});
	}	
	$("#frmLogin").live("submit", function() {  dofrmLogin(); return false; });
	$("#frmReg").live("submit", function() {  dofrmReg(); return false; });
	$("#frmLp").live("submit", function() {  dofrmLp(); return false; });
	$("#frmNewsLetter").live("submit", function() {  dofrmNewsLetterIN(); return false; });
	//$("#goDetOrd").live("click", function() {  goDetOrd(); return false; });
	if($("#boxMarchi").length > 0) 
		makeScrollable("#boxMarchi  .sc_menu_wrapper", "#boxMarchi  .sc_menu");
	if($("#viewAllMarche").length > 0)
	{
		$("#viewAllMarche").bind("click",function() {  $("#viewAllMarche").hide(); $("#selectAllMarchi").show();});
	 
	}		

	
});
function cambioTipoPersonaReg()
{ 
	if ($("input[@name='r_giuridico']:checked").val() == 'f')
	{
		$("#riga_piva").hide();
		$("#r_nome").attr("placeholder","Nome");
		$("#lnome").html("Nome*:");
		$("#lcognome").html("Cognome*:");
	}
	else
	{
		$("#riga_piva").show();
		$("#r_nome").attr("placeholder","Ragione Sociale");
		$("#lnome").html("Ragione Sociale*:");
		$("#lcognome").html("Cognome:");		
	}
}
function goReg()
{	 
	$(".doreg").colorbox({width:"630px", height:"80%", overlayClose : false});	
}
function goLogin()
{	 
	$(".dologin").colorbox({width:"300px", height:"190px"});	
}
 function goLp()
{	 
	$(".doLp").colorbox({width:"300px", height:"180px"});	
}
var cacheFastS = Array();
function fastShlookup() {
	var inputString = jQuery.trim($('#search_nome').val());
	if(inputString.length == 0) {
		// Hide the suggestion box.
		$('#fastSh').hide();
	} else {
		if(cacheFastS[inputString] == undefined){
			$.get("fast_search.php", {input: ""+inputString+"",async: false}, function(data){
				if(data.length >0) {
					$('#fastSh').show();					
					cacheFastS[inputString] = data;
					$('#fastShContent').html(data);
				}
			});
		}
		else
		{			
			$('#fastShContent').html(cacheFastS[inputString]);
			$('#fastSh').show();
		}
	}
} // lookup

function fastShfill() {
	$('#fastSh').hide('slow');
}

$(document).ready(function(){
	//$(".MiniItemsWrap li:first").hide();
	 
	
	
	$(".MiniItemsWrap li img").live("click", function(event) { 
		var productIDValSplitter 	= (this.id).split("_");
		var basketType 			= productIDValSplitter[0];	
		var productIDVal 			= productIDValSplitter[2];	
		$("#"+basketType+"notificationsLoader").html('<img src="images/art/loader.gif">');
		//?XDEBUG_SESSION_START
		$.ajax({  
			type: "POST",  
			url: "aj.php", 
			async: false, 			
			data: { productID: productIDVal, action: "deleteFrom"+basketType},  
			success: function(theResponse) {		
				$("#"+basketType+"productID_" + productIDVal).hide("slow",  function() {$(this).remove();});
				$("#"+basketType+"notificationsLoader").empty();
				
				if(basketType == "MB" && window.location.pathname.search("carrello.php") > 0)
					document.location = "carrello.php";
			}  
		});  
		
	});
	
	$(".wrapAddBasket").click(function() {
	
			var productIDValSplitter 	= (this.id).split("_");
			var basketType 			= productIDValSplitter[0];	
			var productIDVal 			= productIDValSplitter[2];	
			if(!islogged && basketType == "WB")
			{
				$(".dologin").first().click();
				return;				
			}
			var productX 		= $("#productImageWrapID_" + productIDVal).offset().left;
			var productY 		= $("#productImageWrapID_" + productIDVal).offset().top;
			
			var basketX 		= $("#"+basketType+"notificationsLoader").offset().left;
			var basketY 		= $("#"+basketType+"notificationsLoader").offset().top;

			
			var gotoX 			= basketX - productX - 100;
			var gotoY 			= basketY - productY;
			
			
			var newImageWidth 	= $("#productImageWrapID_" + productIDVal).width() / 2;
			var newImageHeight	= $("#productImageWrapID_" + productIDVal).height() / 2;
			
			$("#productImageWrapID_" + productIDVal + " img")
			.clone()
			.prependTo("#productImageWrapID_" + productIDVal)
			.css({'position' : 'absolute','z-index': '9999'})
			.animate({opacity: 0.8}, 100 )
			.animate({opacity: 0.2, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1200, function() {
				
				$(this).remove();	
				$("#"+basketType+"notificationsLoader").html('<img src="images/art/loader.gif">');		
				$.ajax({  
					type: "POST",  
					url: "aj.php", 
					async: false, 
					data: { productID: productIDVal, action: "addToBasket"+basketType},  
					success: function(theResponse) {
						if(theResponse.substring(0, 3) == 'ER:')
						{
							displayMessageTimed(theResponse.substring(3),4, true);
							$("#"+basketType+"notificationsLoader").empty();
							return;
						}
						else if(theResponse.substring(0, 3) == 'OK:')
						{
							theResponse = theResponse.substring(3);
						}
						else
						{
							displayMessageTimed("Application error",4, true);
							//document.write(theResponse);
							$("#"+basketType+"notificationsLoader").empty();
							return;
						}
						
						if( $("#"+basketType+"productID_" + productIDVal).length > 0){
							$("#"+basketType+"productID_" + productIDVal).animate({ opacity: 0 }, 500, function(){
								$("#"+basketType+"productID_" + productIDVal).before(theResponse).remove();
								$("#"+basketType+"productID_" + productIDVal).animate({ opacity: 1 }, 500);
								$("#"+basketType+"notificationsLoader").empty();
							});
							
						} else {
							$("#"+basketType+"ItemsWrap li:last").after(theResponse);
							$("#"+basketType+"ItemsWrap li:last").css("display","block").hide();
							$("#"+basketType+"ItemsWrap li:last").show("slow"); 
							$("#"+basketType+"notificationsLoader").empty();	
			
						}
						if(basketType == "MB")//TODO LANG
							displayMessageTimed("Carrello aggiornato",2);
						if(basketType == "WB")	
							displayMessageTimed("Lista desideri aggiornata",2);
					}  
				});  
			
			});
			
	});
});
function dofrmRegProfilo()
{
	var valido = checkRequired(new Array("r_nome","r_cognome","r_email", "r_codice_fiscale","r_nazioni_ID", "r_indirizzo", "r_citta",
			"r_pr", "r_cap"));
	if(!valido)
		return;
	if(!isMail($("#r_email").val()) == "")
	{
		displayMessageTimed("E-mail non valida",2	, true);
		return;
	}		
	if($("#r_telefono").val().trim() == "" && $("#r_cellulare").val().trim() == "")
	{
		displayMessageTimed("Inserire almeno un numero di teleono",2	, true);
		$("#r_cellulare").focus();
		return;
	}	
	$("#frmReg").submit();

}
function dofrmRegIndSped()
{
	var valido = checkRequired(new Array("s_nome", "s_cognome", "s_nazioni_ID", "s_indirizzo", "s_citta", "s_pr", "s_cap" ));
	if(!valido)
		return;
	$.ajax({  
					type: "POST",  
					url: "aj.php", 
					async: false, 
					data: "action=indSped&"+$("#frmReg").serialize(),  
					success: function(theResponse) {
						if(theResponse.substring(0, 3) == 'ER:')
						{
							 
							displayMessageTimed(theResponse.substring(3),2, true);
							 
							return;
						}
						else if(theResponse.substring(0, 3) == 'OK:')
						{
							$('#doreg').colorbox.close();
							document.location = document.location;
						}
						else
						{
							displayMessageTimed("Application error",4, true);
							//document.write(theResponse);
							 
							return;
						}
						
						
					}  
				});		
}
function logOut()
{
	$.ajax({  
					type: "POST",  
					url: "aj.php", 
					async: false, 
					data: "action=logout",  
					success: function(theResponse) {
						if(theResponse.substring(0, 3) == 'ER:')
						{
							 
							displayMessageTimed(theResponse.substring(3),2, true);							 
							return;
						}
						else if(theResponse.substring(0, 3) == 'OK:')
						{
							document.location = document.location;
						}
						else
						{
							displayMessageTimed("Application error",4, true);					 
							return;
						}
						
						
					}  
				});	
}
function cambioNaz(chi)
{
	if($('#'+chi+'_nazioni_ID').val() != "22")
		$('#'+chi+'_pr').val("EE");
}
function copyDatiSpedizione()
{
	/*if($('#s_nome').val() == "")
	{
		$('#s_nome').val($('#r_nome').val());
		$('#s_cognome').val($('#r_cognome').val());
		$('#s_nazioni_ID').val($('#r_nazioni_ID').val());
		$('#s_indirizzo').val($('#r_indirizzo').val());
		$('#s_citta').val($('#r_citta').val());
		$('#s_pr').val($('#r_pr').val());
		$('#s_cap').val($('#r_cap').val());
	}*/

}
function dofrmReg()
{
	if($("#pageIndSped").length> 0)
	{
		dofrmRegIndSped();
		return;
	}
	if($("#pageProfilo").length> 0)
	{
		dofrmRegProfilo();
		return;
	}
	if($("#pageContatti").length> 0)
	{
		dofrmContatti();
		return;
	}

	var valido = checkRequired(new Array("r_nome","r_email","r_password", "r_codice_fiscale","r_nazioni_ID", "r_indirizzo", "r_citta",
			"r_pr", "r_cap" ));
	if(valido == false)
		return;
 		
	if($("#r_telefono").val() == "" && $("#r_cellulare").val() == "")
	{
		displayMessageTimed("Inserire almeno un numero di teleono",2	, true);
		$("#r_cellulare").focus();
		return;
	}	
 
	/*copyDatiSpedizione();
	valido = checkRequired(new Array( "s_nome", "s_nazioni_ID", "s_indirizzo", "s_citta", "s_pr", "s_cap"));
	if(!valido)
		return;*/
	if($('input[name=r_giuridico]:checked').val() == "g")
	{	
		if($('#r_codice_fiscale').val().length == 16)
		{
			if(!ControllaCF($('#r_codice_fiscale').val()))
			{
				displayMessageTimed("Inserire un codice fiscale valido",2, true);
				$('#r_codice_fiscale').focus();
				return;
			}
		}
		else if($('#r_codice_fiscale').val().length == 11)
		{
			if(!ControllaPIVA($('#r_pi').val()))
			{
				displayMessageTimed("Inserire un codice fiscale valido",2, true);
				$('#r_codice_fiscale').focus();
				return;
			}	
		}
		else
		{
				displayMessageTimed("Inserire un codice fiscale valido",2, true);
				$('#r_codice_fiscale').focus();
				return;	
		}		

		if(!ControllaPIVA($('#r_pi').val()))
		{
			displayMessageTimed("Inserire una partita IVA valida",2, true);
			$('#r_pi').focus();
			return;
		}
		
	}
	else
	{	
		if(!checkRequired(new Array("r_cognome")))
			return;	
		if(!ControllaCF($('#r_codice_fiscale').val()))
		{
			displayMessageTimed("Inserire un codice fiscale valido",2, true);
			$('#r_codice_fiscale').focus();
			return;
		}			
	}
	if(!isMail($("#r_email").val()) == "")
	{
		displayMessageTimed("E-mail non valida",2	, true);
		return;
	}		
	if($('input[name=r_giuridico]:checked').val() == "g")
	{

		if($('#r_pi').val().length != 11)
		{
			displayMessageTimed("Inserire una partita IVA valida",2, true);
			$('#r_pi').focus();
			return;
		}
	}
	if($('#r_codice_fiscale').val().length != 16 && $('#r_codice_fiscale').val().length != 11)
	{
		displayMessageTimed("Inserire un codice fiscale valido",2, true);
		$('#r_codice_fiscale').focus();
		return;
	}
	if($("#r_privacy").prop("checked") == false)
	{
		displayMessageTimed("Accettare trattamento privacy",2, true);
		return
	}	 
	$.ajax({  
					type: "POST",  
					url: "aj.php", 
					async: false, 
					data: "action=reg&"+$("#frmReg").serialize(),  
					success: function(theResponse) {
						if(theResponse.substring(0, 3) == 'ER:')
						{
							 
							displayMessageTimed(theResponse.substring(3),2, true);
							 
							return;
						}
						else if(theResponse.substring(0, 3) == 'OK:')
						{
							$('#doreg').colorbox.close();
							if($("#frmCarrello").length > 0)
								$("#frmCarrello").submit();
							else
								document.location = document.location;
						}
						else
						{
							displayMessageTimed("Application error",4, true);
							//document.write(theResponse);
							 
							return;
						}
						
						
					}  
				});	
	
}
function dofrmContatti()
{
	var valido = checkRequired(new Array("c_nome","c_mail","c_msg"));
	if(!valido)
		return;
	if(!isMail($("#c_mail").val()) == "")
	{
		displayMessageTimed("E-mail non valida",2	, true);
		return;
	}
$.ajax({  
					type: "POST",  
					url: "aj.php", 
					async: false, 
					data: "action=contatti&"+$("#frmReg").serialize(),  
					success: function(theResponse) {
						if(theResponse.substring(0, 3) == 'ER:')
						{
							 
							displayMessageTimed(theResponse.substring(3),2, true);							 
							return;
						}
						else if(theResponse.substring(0, 3) == 'OK:')
						{
							$("#divContatti").slideUp('slow');
							displayMessageTimed("Grazie per averci contattato",4, false);
						}
						else
						{
							displayMessageTimed("Application error",4, true);
							//document.write(theResponse);
							 
							return;
						}
						
						
					}  
				});		
}
function checkRequired(ids)
{
	for (var i = 0; i < ids.length; i++){ 
		if($("#"+ids[i]).val() == "")
		{
			var label = $("label[for="+ids[i]+"]");
			var msg = label.attr("title");			
			if(!label.attr("title"))
				msg = label.text();
			if(msg.substring(msg.length - 2, msg.left) == "*:" )
				msg = msg.substring(0,msg.length - 2);
			displayMessageTimed("Inserire "+msg,2, true);
			$("#"+ids[i]).focus();
			return false;
		}
	}
	return true;
	
}
function dofrmNewsLetterIN()
{
	if($("#newsletter_utenti_nome").val() == "" || $("#newsletter_utenti_email").val() == "")
	{
		displayMessageTimed("Inserire nome e e-mail",2	, true);
		return;
	}
	if(!isMail($("#newsletter_utenti_email").val()) == "")
	{
		displayMessageTimed("E-mail non valida",2	, true);
		return;
	}		
	$.ajax({  
					type: "POST",  
					url: "aj.php", 
					async: false, 
					data: { action: "newsIN", utenti_nome: $("#newsletter_utenti_nome").val() ,utenti_email: $("#newsletter_utenti_email").val()},  
					success: function(theResponse) {
						if(theResponse.substring(0, 3) == 'ER:')
						{
							 
							displayMessageTimed(theResponse.substring(3),2, true);
							 
							return;
						}
						else if(theResponse.substring(0, 4) == 'OK:')
						{
							displayMessageTimed("Iscrizione registrata",2	, false);
							$("#newsletter_utenti_nome").val("");
							$("#newsletter_utenti_email").val("");
						}
						else
						{
							displayMessageTimed("Application error",4, true);
							//document.write(theResponse);
							return;
						}
						
						
					}  
				});	 

}
function dofrmNewsLetterOUT()
{
	if($("#newsletter_utenti_email").val() == "")
	{
		displayMessageTimed("Inserire e-mail",2	, true);
		return;
	}
	if(!isMail($("#newsletter_utenti_email").val()) == "")
	{
		displayMessageTimed("E-mail non valida",2	, true);
		return;
	}	
	
	$.ajax({  
					type: "POST",  
					url: "aj.php", 
					async: false, 
					data: { action: "newsOUT", utenti_email: $("#newsletter_utenti_email").val()},  
					success: function(theResponse) {
						if(theResponse.substring(0, 3) == 'ER:')
						{
							 
							displayMessageTimed(theResponse.substring(3),2, true);
							 
							return;
						}
						else if(theResponse.substring(0, 4) == 'OK:')
						{
							displayMessageTimed("Iscrizione cancellata",2	, false);
							$("#newsletter_utenti_nome").val("");
							$("#newsletter_utenti_email").val("");							
						}
						else
						{
							displayMessageTimed("Application error",4, true);
							//document.write(theResponse);
							return;
						}
						
						
					}  
				});	 

}
function isMail(str)
{
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	return !emailReg.test(str)
}
function dofrmLogin()
{
	if($("#username").val() == "" || $("#password").val() == "")
	{
		displayMessageTimed("Inserire utente e password",2	, true);
		return;
	}
	$.ajax({  
					type: "POST",  
					url: "aj.php", 
					async: false, 
					data: { action: "login", username: $("#username").val() ,password: $("#password").val()},  
					success: function(theResponse) {
						if(theResponse.substring(0, 3) == 'ER:')
						{
							 
							displayMessageTimed(theResponse.substring(3),2, true);
							 
							return;
						}
						else if(theResponse.substring(0, 3) == 'OK:')
						{
							$('#dologin').colorbox.close();
							if($("#frmCarrello").length > 0)
								$("#frmCarrello").submit();
							else
								document.location = document.location;
						}
						else
						{
							displayMessageTimed("Application error",4, true);
							//document.write(theResponse);
							return;
						}
						
						
					}  
				});


}
function dofrmLp()
{
	if($("#username").val() == "")
	{
		displayMessageTimed("Inserire la propria email",2	, true);
		return;
	}
	$.ajax({  
					type: "POST",  
					url: "aj.php", 
					async: false, 
					data: { action: "lp", username: $("#username").val()},  
					success: function(theResponse) {
						if(theResponse.substring(0, 3) == 'ER:')
						{
							 
							displayMessageTimed(theResponse.substring(3),2, true);
							 
							return;
						}
						else if(theResponse.substring(0, 3) == 'OK:')
						{
							$(".dologin").first().click();
							displayMessageTimed("Password spedita",3	, false);
						}
						else
						{
							displayMessageTimed("Application error",4, true);
							//document.write(theResponse);
							return;
						}
						
						
					}  
				});


}
    
function displayMessageTimed(message, timeOut, errore) {
	$('#MessageTimed').remove();
	if ( errore === undefined )	
		errore = false;
	var msg = $("<div/>").attr("id","MessageTimed").text(message).center();
	if(errore)
		msg.css("background-color","red");
	msg.appendTo("body");

	setTimeout(function() {
		$('#MessageTimed').fadeOut(function() {$(this).remove()});
	}, timeOut * 1000);
}
jQuery.fn.center = function (absolute) {
    return this.each(function () {
        var t = jQuery(this);
		var left = '50%';
		if($.browser.msie)
			left = '40%';
		if($.browser.msie && $.browser.version < 8)
		{
			//alert($.browser.version );
			absolute = true;
		}
        t.css({
            position:    absolute ? 'absolute' : 'fixed', 
            left:        left, 
            top:        '50%', 
            zIndex:        '99'
        }).css({
            marginLeft:    '-' + (t.outerWidth() / 2) + 'px', 
            marginTop:    '-' + (t.outerHeight() / 2) + 'px'
        });

        if (absolute) {
            t.css({
                marginTop:    parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(), 
                marginLeft:    parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
            });
        }
    });
};

function goToPage(p)
{
	if(jQuery.trim(p) == "")
		return;
	else
		document.location = p;
}

function confermaCarrello()
{

	if($("#carrelloNotLoggedIn").length > 0)
	{
		$(".dologin").first().click();
		return;
	
	}
	$("#btnAcq").attr('disabled', 'disabled');
	$("#frmCarrello").append("<input name='conferma' id='carreloConferma'/>").submit();
}
function removeCodiceSconto(c)
{
		$.ajax({  
					type: "POST",  
					url: "aj.php", 
					async: false, 
					data: { action: "rmSconto", codice: c},  
					success: function(theResponse) {
						if(theResponse.substring(0, 3) == 'ER:')
						{
							 
							displayMessageTimed(theResponse.substring(3),2, true);
							 
							return;
						}
						else if(theResponse.substring(0, 4) == 'OK:')
						{
							displayMessageTimed("Codice cancellato",2	, false);
							document.location = "carrello.php";
						}
						else
						{
							displayMessageTimed("Application error",4, true);
							//document.write(theResponse);
							return;
						}
						
						
					}  
				});	
}
function selCupon()
{

		$val = $("#frmSelCupon :input[value]").serialize();
		if($val == "")
			return;
		$val += "&action=addSconto";
		$.ajax({  
					type: "POST",  
					url: "aj.php", 
					async: false, 
					data: $val,  
					success: function(theResponse) {
						if(theResponse.substring(0, 3) == 'ER:')
						{
							 
							displayMessageTimed(theResponse.substring(3),2, true);
							 
							return;
						}
						else if(theResponse.substring(0, 4) == 'OK:')
						{
							displayMessageTimed("Aggiornamento Carrello",2	, false);
							document.location = "carrello.php";
						}
						else
						{
							displayMessageTimed("Application error",4, true);
							//document.write(theResponse);
							return;
						}
						
						
					}  
				});	

}
function deleteCarrelloItem(idx)
{
	if(confirm('Sei sicuro di voler rimuovere l\'articolo dal carrello ?'))
	{
		$("#qta_r_"+idx).val(0);
		$("#frmCarrello").submit();
	}
}
function ControllaCF(cf)
{
	var validi, i, s, set1, set2, setpari, setdisp;
	if( cf == '' )  return false;
	cf = cf.toUpperCase();
	if( cf.length != 16 )
		return false;
	validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	for( i = 0; i < 16; i++ ){
		if( validi.indexOf( cf.charAt(i) ) == -1 )
			return false;
	}
	set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
	s = 0;
	for( i = 1; i <= 13; i += 2 )
		s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	for( i = 0; i <= 14; i += 2 )
		s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
		return false;
	return true;
}
function ControllaPIVA(pi)
{
	if( pi == '' )  return false;
	if( pi.length != 11 )
		return false;
	validi = "0123456789";
	for( i = 0; i < 11; i++ ){
		if( validi.indexOf( pi.charAt(i) ) == -1 )
			return false;
	}
	s = 0;
	for( i = 0; i <= 9; i += 2 )
		s += pi.charCodeAt(i) - '0'.charCodeAt(0);
	for( i = 1; i <= 9; i += 2 ){
		c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
		if( c > 9 )  c = c - 9;
		s += c;
	}
	if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )
		return false;
	return true;
}	

(function($) {
    var opt;

    $.fn.jqprint = function (options) {
        opt = $.extend({}, $.fn.jqprint.defaults, options);

        var $element = (this instanceof jQuery) ? this : $(this);

        if (opt.operaSupport && $.browser.opera) 
        { 
            var tab = window.open("","jqPrint-preview");
            tab.document.open();

            var doc = tab.document;
        }
        else 
        {
            var $iframe = $("<iframe  />");

            if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-600px", top: "-600px" }); }

            $iframe.appendTo("body");
            var doc = $iframe[0].contentWindow.document;
        }

        if (opt.importCSS)
        {
            if ($("link[media=print]").length > 0) 
            {
                $("link[media=print]").each( function() {
                    doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' media='print' />");
                });
            }
            else 
            {
                $("link").each( function() {
                    doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' />");
                });
            }
        }

        if (opt.printContainer) { doc.write($element.outer()); }
        else { $element.each( function() { doc.write($(this).html()); }); }

        doc.close();

        (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).focus();
        setTimeout( function() { (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000);
    }

    $.fn.jqprint.defaults = {
        debug: false,
        importCSS: true, 
        printContainer: true,
        operaSupport: true
    };

    // Thanks to 9__, found at http://users.livejournal.com/9__/380664.html
    jQuery.fn.outer = function() {
      return $($('<div></div>').html(this.clone())).html();
    } 
})(jQuery);

