/*--------------------------------------------------
    currency formatting
--------------------------------------------------*/
function formatCurrency(amount)
{
	var mf = new jsworld.MonetaryFormatter(new jsworld.Locale(POSIX_LC.de_DE));
	return mf.format(amount);
}



/*--------------------------------------------------
	hidden focus
--------------------------------------------------*/
function hiddenFocus(){
	$(".hiddenFocus").each(function(){
		$(this).focus(function(){
			if ($(this).val() == $(this).attr("title")){
				$(this).val("");	
			}
		}).blur(function(){
			if ($.trim($(this).val()) == ""){
				$(this).val($(this).attr("title"));	
			}
		});
	});
}

/*--------------------------------------------------
	banner top
--------------------------------------------------*/
function showBannerTop(){
	$(".banner_top_small").mouseover(function(){
		$(".banner_top_small").hide();
		$(".banner_top_big").show();
	});
	$(".banner_top_big").mouseout(function(){
		$(".banner_top_small").show();
		$(".banner_top_big").hide();
	});
}


/*--------------------------------------------------
	scrolla marchi
--------------------------------------------------*/
function scrollMarchi(){
	$(".scrollable").scrollable();
	var url;
	var myrel;
	$(".scroll_prodotto .items a").click(function(){
		url = $(this).attr("href");
		myrel = $(this).attr("rel");
		$(".items img").removeClass("active");
		$(this).find("img").addClass("active");
		/*$("#image_wrap img").animate({opacity:0},300,function(){
			$.ajax({
				href:url,
				rel:myrel,
				success:changeImg,
				error:changeImg
			});
		});*/
		return false;
	});
	/*function changeImg(){
		$("#image_wrap img").attr("src",url).delay(500).animate({opacity:1},300);
		$("#zoom1").attr("href",myrel);
	}*/
}

/*--------------------------------------------------
	show sub menu
--------------------------------------------------*/
function showSubMenu () {
    openMenu = setTimeout(function(){
        return true;
    },1);
	$(".sub_menu dl img").parents("dl").addClass("banner");
	$("#menu .menu a").not($("#menu ul li.tutti_reparti a, .sub_menu a")).hover(function(){
        clearTimeout(openMenu);
        $("#menu ul li.tutti_reparti .sub_menu_reparti").hide();
        var e = $(this);
        openMenu = setTimeout(function() {
            if ($("#menu ul li.tutti_reparti .sub_menu_reparti:visible").size() == 0) {
                e.parent().next().show();
				$('.container').each( function() {
					$(this).masonry({
					// options
					itemSelector : '.item',
					columnWidth : 234
					});
				});
            }
        },500);
    },function(){
        clearTimeout(openMenu);
        $(this).parent().next().hide();
    });
	/*$("#menu .menu a").not($("#menu ul li.tutti_reparti a, .sub_menu a")).hover(function(){
		$("#menu ul li.tutti_reparti .sub_menu_reparti").hide();
		$(this).parent().next().show();
	},function(){
		$(this).parent().next().hide();
	});*/
	$(".sub_menu").hover(function(){
		$(this).show();
		$(this).prev().find("a").addClass('on');
	},function(){
		$(this).hide();
		$(this).prev().find("a").removeClass('on');
	});
	
	$("#menu ul li.tutti_reparti a").not($(".sub_wrap a")).click(function(){
		$(this).parent().next().toggle();
		return false;
	});
}

/*--------------------------------------------------
	scroll evidenza
--------------------------------------------------*/
function scrollEvidenza(){
	var i = 0;
	var loop;
	goTo(i);
	
	function goTo(i){
			if (i >= $("#blocco_evidenza_menu ul li a").size()){
				i = 0;
			}
			$("#blocco_evidenza_menu ul li a").removeClass("on").eq(i).addClass("on");
			$("#blocco_evidenza_wrap .banner_evidenza").hide().eq(i).show();
			//$("#blocco_evidenza_wrap").stop().animate({"top":"-" + (i*338) + "px"},500);
	}
	
	$("#blocco_evidenza_menu ul li a").mouseover(function(){
		i =  $("#blocco_evidenza_menu ul li a").index($(this));
		goTo(i);
		clearInterval(loop);
	}).mouseout(function(){
		loop = setInterval(function(){
			goTo(++i);
		},5000);
	});
	
	loop = setInterval(function(){
		goTo(++i);
	},5000);
}


/*--------------------------------------------------
	scroll vetrina
--------------------------------------------------*/
function scrollVetrina(){
	var i = 0;
	var loop;
	goTo(i);
	
	function goTo(i){
			if (i >= $("#tutti_reparti ul.reparti li a").size()){
				i = 0;
			}
			$("#tutti_reparti ul.reparti li a").removeClass("on").eq(i).addClass("on");
			$(".vetrina_wrap .vetrina").hide().eq(i).show();
			//$(".vetrina_wrap").stop().animate({"top":"-" + (i*311) + "px"},500);
	}
	
	$("#tutti_reparti ul.reparti li a").mouseover(function(){
		i =  $("#tutti_reparti ul.reparti li a").index($(this));
		goTo(i);
		clearInterval(loop);
	}).mouseout(function(){
		loop = setInterval(function(){
			goTo(++i);
		},5000);
	});
	
	loop = setInterval(function(){
		goTo(++i);
	},5000);
}


/*--------------------------------------------------
	Show Copertina SubMenu
--------------------------------------------------*/
function showSubmenuCopertina(){
	$("#copertina_sezione ul li h2").hover(function(){
		$("#copertina_sezione ul li h2 a.on").removeClass("on");
		$(this).find("a:first").addClass("on");
		$(this).next().show();
	},function(){
		$(this).next().hide();
		$("#copertina_sezione ul li h2 a.on").removeClass("on");
	});
	
	$("#copertina_sezione .sottomenu").hover(function(){
		$(this).show();
		$(this).prev().find("a").addClass('on');
	},function(){
		$("#copertina_sezione ul li h2 a.on").removeClass("on");
		$(this).hide();
		$(this).prev().removeClass('on');
	});
}


/*--------------------------------------------------
	ALtezza li elenco prodotti
--------------------------------------------------*/
function elencoProdotti (){
//	$("#elenco_prodotti ul.clearfix li").css({height:"auto"});
//	$("#elenco_prodotti ul.clearfix li:nth-child(4n+1)").addClass("clear");
	
	var i=0;
	var c=0;
	var maxHeight = 0;

	$("#elenco_prodotti .descrizione_prodotto").each(function(){

		if ( $(this).height() > maxHeight )
			maxHeight = $(this).height();

		//alert(maxHeight);

		if (i == 3)
		{
			//alert("SETTO MAX H = " + maxHeight);
			//alert(c)
			$(this).height(maxHeight);
			$("#elenco_prodotti .descrizione_prodotto:eq("+ (c-1) +")").height(maxHeight);
			$("#elenco_prodotti .descrizione_prodotto:eq("+ (c-2) +")").height(maxHeight);
			$("#elenco_prodotti .descrizione_prodotto:eq("+ (c-3) +")").height(maxHeight);
				
			maxHeight  = 0;
			i = -1;
		}
		i++;
		c++;
	});

	i=0;
	c=0;
	maxHeight = 0;

	$("#elenco_prodotti .marca").each(function(){

		if ( $(this).height() > maxHeight )
			maxHeight = $(this).height();

		//alert(maxHeight);

		if (i == 3)
		{
			//alert("SETTO MAX H = " + maxHeight);
			//alert(c)
			$(this).height(maxHeight);
			$("#elenco_prodotti .marca:eq("+ (c-1) +")").height(maxHeight);
			$("#elenco_prodotti .marca:eq("+ (c-2) +")").height(maxHeight);
			$("#elenco_prodotti .marca:eq("+ (c-3) +")").height(maxHeight);
				
			maxHeight  = 0;
			i = -1;
		}
		i++;
		c++;
	});
	
	i=0;
	maxHeight = 0;
	
	$("#elenco_prodotti ul.clearfix li").not(".caratteristica li").each(function(){

		if ( $(this).height() > maxHeight )
			maxHeight = $(this).height();

		//alert(maxHeight);
		$(this).attr("rel", "davide");
		if (i == 3)
		{
			//alert("SETTO MAX H = " + maxHeight);
			$(this).height(maxHeight);
			$(this).prev().height(maxHeight);
			$(this).prev().prev().height(maxHeight);
			$(this).prev().prev().prev().height(maxHeight);
				
			maxHeight  = 0;
			i = -1;
		}
		i++;
	});
}


/*--------------------------------------------------
	Raffina la ricerca
--------------------------------------------------*/
function raffinaRicerca (){
	$(".elementi_ricerca li a").click(function(){
		$(this).toggleClass("on").next().toggle();
		return false;
	});
}


/*--------------------------------------------------
	togli padding elenco prodotti
--------------------------------------------------*/
function togliPaddingProdotti (){
	$(".descrizione_prodotto_dx ul li:nth-child(3n)").css("padding-right","0");
	$(".descrizione_prodotto_dx ul li:nth-child(3n+1)").addClass("clearfix clear");
}

function tabsProdotto (){
	$("ul.tabs").tabs("div.panes > div")
}


/*--------------------------------------------------
	select trasform
--------------------------------------------------*/
function beautifySelect() {
    $(".opzioni ul li").each(function() {
        $(this).append('<span class="select close"><span style="width: 154px; overflow: hidden">' + $(this).find("option:selected").html() + '</span></span>').find("select").css({opacity:0}).live("change",function() {			
					$(this).parent().find("span.select span").html($(this).find(':selected').html());
				});
    })
};


/*--------------------------------------------------
	cambia cli spedizione
--------------------------------------------------*/
function cambiaCliSpedizione(){
	if ($("[name=cli_spedizionediversa]:checked").val() == 0){
		$("#cli_spedizione_div #indirizzospe").hide();
	} else {
		$("#cli_spedizione_div #indirizzospe").show();
	}
}


/*--------------------------------------------------
	cambia cli fattura
--------------------------------------------------*/
function cambiaCliFattura(){
	if ($("[name=cli_fatturarichiesta]:checked").val() == 0){
		$("#cli_fattura_div").hide();
	} else {
		$("#cli_fattura_div").show();
	}
}

/*--------------------------------------------------
	cambia cli iscrizione
--------------------------------------------------*/
function cambiaCliIscrizione(){
	if ($("[name=cli_iscrizione]:checked").val() == 0){
		$("#iscrizionesito").hide();
	} else {
		$("#iscrizionesito").show();
	}
}


/*--------------------------------------------------
	configurazione prodotto
--------------------------------------------------*/
function configProd(){
	
	prezzo = parseFloat($(".cifra_grande").html().split(" ")[1].replace(".","").replace(",",".")).toFixed(2);
	$sel = $(".opzioni form select");

	if ($sel.size()>0)
	{
	 // disabilito il pulsante acquista		
	 disabled = true;
	 $(".aggiungi_carrello").addClass("aggiungi_carrello_disabled");
	 $(".aggiungi_carrello a").unbind("click");
		$(".aggiungi_carrello a").click(function(){
			return false;
		});	 
	}
	else
	{	
	 disabled = false;
	 $(".aggiungi_carrello").addClass("visibleCarrello");
	}
		
	
	// disattivo select
	$sel.attr("disabled","disabled");
	
	// creo select
	function 	createSelect(n){
		$sel.eq(n).html("").removeAttr("disabled");
		$('<option title="0" value="0" rel="0">[seleziona]</option>').appendTo($sel.eq(n));
		$(".opzioni form select:gt(" + n + ")").html('<option title="0" value="0" rel="0">[seleziona]</option>').attr("disabled","disabled");
		var ar;
		switch (n){
			case 0:
				ar = m;
			break;
			case 1:
				ar = m[$sel.eq(0).find("option:selected").attr("title")].risposte;
			break;
			case 2:
				ar = m[$sel.eq(0).find("option:selected").attr("title")].risposte[$sel.eq(1).find("option:selected").attr("title")].risposte;
			break;
			case 3:
				ar = m[$sel.eq(0).find("option:selected").attr("title")].risposte[$sel.eq(1).find("option:selected").attr("title")].risposte[$sel.eq(2).find("option:selected").attr("title")].risposte;
			break;
			case 4:
				ar = m[$sel.eq(0).find("option:selected").attr("title")].risposte[$sel.eq(1).find("option:selected").attr("title")].risposte[$sel.eq(2).find("option:selected").attr("title")].risposte[$sel.eq(3).find("option:selected").attr("title")].risposte;
			break;
			case 5:
				ar = m[$sel.eq(0).find("option:selected").attr("title")].risposte[$sel.eq(1).find("option:selected").attr("title")].risposte[$sel.eq(2).find("option:selected").attr("title")].risposte[$sel.eq(3).find("option:selected").attr("title")].risposte[$sel.eq(4).find("option:selected").attr("title")].risposte;
			break;
		}
		$.each(ar,function(i,val){
			$('<option title="' + i + '" value="' + ar[i].id + '" rel="' + ar[i].prezzo + '">' +  ar[i].value + '</option>').appendTo($sel.eq(n));
		});
	}
	
	
	// bind delle select
	$sel.bind("change",function(){
		
		ind = $sel.index($(this));
		if ($(this).find("option:selected").attr("title") == 0) {
			$(".opzioni form select:gt(" + ind + ")").html('<option value="0" rel="0">[seleziona]</option>').attr("disabled","disabled");
		} else {
			if ($sel.eq(ind+1).size()){
				createSelect(ind+1);
			}
		}
		

		// check pulsante
		for (j=0; j<$sel.size(); j++){
			if (parseInt($sel.eq(j).val()) == 0) {
				disabled = true;
				break;
			}
			else {
				disabled = false;
				$(".aggiungi_carrello").addClass("visibleCarrello");
			}
		}		
		if (!disabled) {
			$(".aggiungi_carrello").removeClass("aggiungi_carrello_disabled");
			$(".aggiungi_carrello a").click(function(){
				$("form[name='addProdotto']").submit();
			});
		} else {
			$(".aggiungi_carrello").addClass("aggiungi_carrello_disabled");
			$(".aggiungi_carrello a").unbind("click");			
			$(".aggiungi_carrello a").click(function(){
				return false;
			});
		}
		
		
		rel = parseFloat($(this).find(":selected").attr("rel")).toFixed(2);
		var cifraFormattataInEuro = formatCurrency((rel*1+prezzo*1).toFixed(2).replace(".00",""));
		$(".cifra_grande").html($(".cifra_grande").html().split(" ")[0] + " " + cifraFormattataInEuro);
	});
	
	createSelect(0);
}


/*--------------------------------------------------
	cambia cli newsletter
--------------------------------------------------*/
function cambiaCliNewsletter(){
	if ($("[name=cli_newsletter]:checked").val() == 0){
		$("#subnewsletter").hide();
	} else {
		$("#subnewsletter").show();
	}
}

/*--------------------------------------------------
	pulsantiera
--------------------------------------------------*/
function centraDivPulsantiera(){
	//alert (PaddingDaSottrarre)
	$(".pulsantiera li div").each(function(){
		var lunghezzaDiv = $(this).width();
		var lunghezzaLink = $(this).children().outerWidth();
		//alert (lunghezzaLink)
		var PaddingDaSottrarre = ((lunghezzaDiv-lunghezzaLink)/2)	
		$(this).css({"margin-left":PaddingDaSottrarre,"width":lunghezzaDiv-PaddingDaSottrarre});
		});
}

/*--------------------------------------------------
	Aggiungi al carrello Padding_Left
--------------------------------------------------*/
function addLeftPulsCarrello(){
	$("#wishlist .prezzo").each(function(){
		var lunghezzaPrezzo = $(this).width();
		var varLeft = ((260-lunghezzaPrezzo)/2)
		$(this).css({"left":varLeft})
		});
}

/*--------------------------------------------------
	Recupera Password
--------------------------------------------------*/
function recuperaPassword(){
	$(".login_effettua a").click(function(){
		$(".login_effettua").hide();
		$(".login_recupera").show();
		});

}

/*--------------------------------------------------
	My Account
--------------------------------------------------*/
function myAccount(){
	$(".apri").click(function(){
		$(".apri").not($(this)).removeClass("on").next().not($(this).next()).hide();
		$(this).toggleClass("on").next().toggle();
		return false;
	});
	maxW = 0;
	$(".riepilogo_dati span").each(function(){
	  if ($(this).width() > maxW) {
		maxW = $(this).width();
	  }
	});
	$(".riepilogo_dati span").width(maxW);
	$(".apri_next").css({"display":"none"});

}

/*--------------------------------------------------
	Lancia Fancy
--------------------------------------------------*/
function lanciaFancy(){
	$("a.fancy").fancybox();
}

/*--------------------------------------------------
	Switch Griglia Lista
--------------------------------------------------*/
function switchGrigliaLista(){
	$(".griglia").css({"background-position":"0 -30px"});
	$(".lista a").click(function(){
		$("#elenco_prodotti ul").not($(".visualizzazione ul")).not($(".caratteristica ul")).addClass("vis_lista");
		$(".lista").css({"background-position":"0 -90px"});
		$(".griglia").css({"background-position":"0 0"});
		return false
	});
	$(".griglia a").click(function(){
		$("#elenco_prodotti ul").removeClass("vis_lista");
		$(".lista").css({"background-position":"0 -60px"});
		$(".griglia").css({"background-position":"0 -30px"});
		return false
	});
}

/*--------------------------------------------------
	Altezza Titolo
--------------------------------------------------*/
function altezzaTitolo(){
	altezza = $(".titolo_prodotto h1").outerHeight();
	if ($(".titolo_prodotto h1").height() <= 30){
		//$(".titolo_prodotto").css({"background":"url(../images/bg_titolo_prodotto.png) left top no-repeat"});
		$(".titolo_prodotto h1").css({"height":30});
	} else {
		$(".titolo_prodotto").attr('id', 'titolo_prodotto_big');
	}
}


/*--------------------------------------------------
	Check Selection
--------------------------------------------------*/
function checkSelection(){
	sel = location.pathname.split("/")[1].toLowerCase();
	$("body").addClass(sel);
}

/*--------------------------------------------------
	BG DT
--------------------------------------------------*/
function bgDt(){
	$(".sub_wrap dt a").each(function(){
		$(this).prepend('<div class="freccia"></div>');
	});
}

/*--------------------------------------------------
	PREZZO Criteo
--------------------------------------------------*/
function wrapPrezzo(){
	$(".cto_ch_3955_dvpr").wrap("<div class='prezzo' />")
}
/*--------------------------------------------------
	DESCRIZIONE Criteo
--------------------------------------------------*/
function riduciDescr() {
	$(".cto_ch_3955_rec").each(function(i,e) {
			var descr = $("div:eq(0)",e).text();
			if (descr.length > 200)
			{
				descr = descr.substr(0, 199) + " [...]";
				$("div:eq(0)",e).text(descr);
			}
			else {}
		});
}

function myOver() {
	if ($(".pulsantiera li.puls_01.on").size() != 0) {
			$(".pulsantiera").addClass("puls1");
		}
	if ($(".pulsantiera li.puls_02.on").size() != 0) {
			$(".pulsantiera").addClass("puls2");
		}
	if ($(".pulsantiera li.puls_03.on").size() != 0) {
			$(".pulsantiera").addClass("puls3");
		}
	if ($(".pulsantiera li.puls_04.on").size() != 0) {
			$(".pulsantiera").addClass("puls4");
		}
}

/*--------------------------------------------------
	NO SCONTO
--------------------------------------------------*/
function noSconto() {
	$("#elenco_prodotti ul li").each( function() {
		if(($(".sconto", this).text()) == "") {
			$(".prezzo", this).css("margin-top","27px");
		}
	});
}
/*--------------------------------------------------
	LOADING CARRELLO
--------------------------------------------------*/
function loadingCarrello()
{
	// custom per paypal
	if ( $('input:radio[name=SelectedGateway]:checked').val() == "ezpaypal" )
	{
		content = $('#loadingCarrelloPaypal').clone(); 
	}
	else
	{
		content = $('#loadingCarrello').clone();
	}
	$.fancybox({
		'content': content,
		'width': 400,
		'height': 270,
		'autoDimensions': false,
		'showCloseButton': false,
		'enableEscapeButton':false,
		'hideOnOverlayClick':false
	});
	closeLoading();
}
function closeLoading(){
		setTimeout(function(){
			$.fancybox.close();
		},60000); // max 1 minuto di attesa
}
/*
 * per vat_userregister.tpl
 */
function langForm() {
   var myLangForm = $("#cli_naz").attr("value");
                   $("div").removeClass("en");
   if (myLangForm != "IT") {
                   $("div#cont_carrello").addClass("en");
   }
}
function langFormBind() {
    $("#cli_naz").bind("change",function(){
    	langForm();
    }); 
}


function image3dSpin() {
    var images = $.makeArray($('#image3dLoad a').map(function(i, e){return e.href}));
    $(".spritespin").mouseup(function(){
    		$(this).removeClass("dragging");
    	}).mousedown(function(){
    			$(this).addClass("dragging");
    	});

    //var images = [];
    //$('#image3dLoad a').each(function(i,e){images.push(e.href);});

    $(".spritespin").spritespin({
                   frames    : images.length,
                   width     : 600,
                   height    : 600,
                   touchable : undefined,
                   frame     : 11,
                   image     : images
    });
}


/*--------------------------------------------------
NASCONDE RIMBORSO SE SELEZIONO RAEE
--------------------------------------------------*/
function checkTipologiaRichiesta(){
	if (document.getElementById('tipo_richiesta3').checked) {
		hidedivRimborso();
	} else {
		showdivRimborso()
	}
	
} 

function hidedivRimborso() { 
	if (document.getElementById) { // DOM3 = IE5, NS6 
		document.getElementById('modalita_rimborso').style.visibility = 'hidden'; 
	} else { 
		if (document.layers) { // Netscape 4 
		document.modalita_rimborso.visibility = 'hidden'; 
		} else { // IE 4 
			document.all.modalita_rimborso.style.visibility = 'hidden'; 
		}
	} 
} 


function showdivRimborso() { 
	if (document.getElementById) { // DOM3 = IE5, NS6 
		document.getElementById('modalita_rimborso').style.visibility = 'visible'; 
	} 
	else { 
		if (document.layers) { // Netscape 4 
			document.modalita_rimborso.visibility = 'visible'; 
		} 
		else { // IE 4 
		document.all.modalita_rimborso.style.visibility = 'visible'; 
		} 
	} 
} 

/*--------------------------------------------------
	INIT
--------------------------------------------------*/
$(function(){
	showBannerTop();
	scrollMarchi();
	showSubMenu();
	//bgDt();
	scrollEvidenza();
	scrollVetrina();
	elencoProdotti();
	raffinaRicerca();
	togliPaddingProdotti();
	//beautifySelect();
	centraDivPulsantiera();
	addLeftPulsCarrello();
	recuperaPassword();
	myAccount();
	switchGrigliaLista();
	altezzaTitolo();
	//lanciaFancy();
	tabsProdotto ();
	hiddenFocus();
	showSubmenuCopertina();
	checkSelection();	
	myOver();
	noSconto();
	langForm();
	langFormBind();
	
	$(".open_fancybox").bind("click",function()
	{
		loadingCarrello();
	});
	// visualizza il terzo tab dei commenti
	if(location.search.match(/commentadded=1/)){
	    $('.tabs li:eq(2) a').click();
	}
	//configProd();
	//wrapPrezzo();
	//riduciDescr();
	
	// tab

	$(".fancy3d").fancybox({
        onStart : image3dSpin
	});	
		
});
