// JavaScript Document
/*--------------------------------------------------
iGuzzini 
http://www.iguzzini.com
website by websolute
http://www.websolute.it
--------------------------------------------------*/

/*--------------------------------------------------
COLOR MENU
--------------------------------------------------*/

function colorMenu() {
	$("#menu ul li a").hover( function() {
		var myColor = $(this).attr("rel");
		$(this).stop().animate({'color': '#'+ myColor +''}, 500);
	}, function(){
		$(this).stop().animate({'color': '#999999'}, 500);
	});
}
	
/*--------------------------------------------------
COLOR LAYER
--------------------------------------------------*/	
function colorLayer() {
	clcH = $("#heroWindow").css("border-top-color");
	$("#heroWindow .topColor").attr("rel",clcH);
	$(".previewImg").each( function() {
		clcP = $(this).css("border-top-color");
		$(this).children(".topColor").attr("rel",clcP);
	});
	$(".slideshow_Pr").each( function() {
		clcP = $(this).css("border-top-color");
		$(this).children(".topColor").attr("rel",clcP);
	});
	$(".topColor").hover( function() {
		var myColor = $(this).attr("rel");
//		console.log(myColor);
		$(this).find(".topLayer").stop().animate({'backgroundColor':'#'+ myColor +''}, 1800);
	}, function(){
		$(this).find(".topLayer").stop().animate({'backgroundColor':'#9C9D9D'}, 2000);
	});
}

/*--------------------------------------------------
HEIGHT SITE MAP
--------------------------------------------------*/	

function siteMapHeight() {
	$(".preFooterBox").each(function(){
		$(this).find('ul').eq(0).addClass('first');
	});
	//myH = $(".preFooterBox").outerHeight();
//	$(".preFooterBox").height(""+ myH +"")
	$(".preFooterBox").eq(2).css({'width':'113px','margin-left':'26px'});
}

/*--------------------------------------------------
MENU
--------------------------------------------------*/

function gMenu() {
	$('.menuService li a.open').click( function() {
		$('.menuService li a.open').addClass('on');
		var m = $('#menuMarketLang:visible').size();
		if(m == 0){
		$('#wrapMenu').show().animate({ height: "111px", 'margin-bottom':'20px' }, 800);	
		$('#menuMarketLang').delay(800).fadeIn(500);	
		}
	});
	$('#closeMenu').click( function() {
			gClose();
	});
}
function gClose() {
		$('#menuMarketLang').fadeOut(500);	
		$('#wrapMenu').delay(500).animate({ 'height': '0px', 'margin-bottom':'0px' }, 800);	
		$('.menuService li a.open').removeClass('on');
}

/*--------------------------------------------------
Select
--------------------------------------------------*/
function gSelect(sender)
{
    if ($(sender).next().is(":visible"))
    {
        $(sender).next().slideUp(200);
    } else
    {
        $(sender).next().slideDown(200);
    }
	$(sender).parent(".gSelect").hover(function(){},function(){
        $(sender).next().slideUp(200);
	});
    return false;
}

/*--------------------------------------------------
MENU SX
--------------------------------------------------*/
function menuSx(menu)
{	
    if ($(menu).next().is(":visible"))
    {
		$(menu).parent().removeClass("open")
		$(menu).parent().find("span").text(">");
        $(menu).next().slideUp(60);
    } else
    {	
		$("#menuSx li").has('ul:visible').find("a").next().slideUp(60);
		$("#menuSx li").has('ul:visible').find("a").parent().find("span").text(">");
		$("#menuSx li").has('ul:visible').find("a").parent().removeClass("open")
		$(menu).parent().find("span").text("v");
		$(menu).parent().addClass("open");
        $(menu).next().slideDown(60);
	}
    return false;
}


/*--------------------------------------------------
Slideshow
--------------------------------------------------*/
function moveOn(parametro){
		slideSizeA = $("#slideshow .slideshow_wrap").size();
		$(".balls .ball").removeClass("on");
		$(".balls .ball").eq(parametro).addClass("on");
		myLeft = $("#slideshow .slideshow_wrap").eq((parametro)).outerWidth();
		if (parametro != slideSizeA -1){
			$("#slideshow .slideshow_overflow").stop().animate({"left":-(myLeft*parametro) + "px"},1000);
		}else{
			if(slideSizeA > 1){
				$("#slideshow .slideshow_overflow").stop().animate({"left":-(myLeft+((parametro-1)*768)) + "px"},1000);
			}
		}
}
function noSlide(){
	imgSize = $("#slideshow .slideshow_wrap .slideshow").size();
	if(imgSize <= 1) {
		$("#contSlideshow").css("margin-top","0").hide();
	}
}
function slideshow(){
	increment = 0;
	slideSize = $("#slideshow .slideshow_wrap").size();
	if(slideSize <= 1) {
		$("#contSlideshow .arrows").hide();
		$(".balls").hide();
	}else{
		$("#contSlideshow .arrows").show();
		$(".balls").show();
	}
	// balls
	for (i=0; i<slideSize; i++){
		$(".balls").append('<div class="ball">' + i + '</div>');
	}	
	moveOn(increment);

	// frecce
	$("#contSlideshow .arrows #right").unbind('click').click(function(){
		increment = increment + 1;
		if (increment >= slideSize){
			increment = 0;
		}
		moveOn(increment);
		return false;
	});

	$("#contSlideshow .arrows #left").unbind('click').click(function(){
		increment = increment - 1;
		if (increment < 0){
			increment = slideSize-1;
		}
		moveOn(increment);
		return false;
	});

	$("#contSlideshow .balls .ball").unbind('click').click(function(){
		increment = parseInt($(this).text(), 10);
		moveOn(increment);
		return false;
	});
}

/*--------------------------------------------------
Slideshow
--------------------------------------------------*/
function slideshow_Pr(){
	incrementPr = 0;
	slideSizePr = $("#slideshow_Pr .slideshow_wrap_Pr").size();
	if(slideSizePr <= 1) {
		$("#contSlideshow_Pr .arrows_Pr").hide();
		$(".balls_Pr").hide();
	}
	var loop;

	// balls
	for (i=0; i<slideSizePr; i++){
		$(".balls_Pr").append('<div class="ball_Pr">' + i + '</div>');
	}

	function moveOn(parametro){
		$(".balls_Pr .ball_Pr").removeClass("on");
		$(".balls_Pr .ball_Pr").eq(parametro).addClass("on");
		myLeftPr = $("#slideshow_Pr .slideshow_wrap_Pr").eq((parametro)).outerWidth();
//		console.log(myLeft);
//		console.log(parametro);
		if (parametro != slideSizePr -1){
			$("#slideshow_Pr .slideshow_overflow_Pr").stop().animate({"left":-(myLeftPr*parametro) + "px"},1000);
		}else{
			if(slideSizePr > 1){
				$("#slideshow_Pr .slideshow_overflow_Pr").stop().animate({"left":-(myLeftPr+((parametro-1)*768)) + "px"},1000);
			}
		}
	}
	moveOn(incrementPr);

	// frecce
	$("#contSlideshow_Pr .arrows_Pr #right_Pr").click(function(){
		incrementPr = incrementPr + 1;
		if (incrementPr >= slideSizePr){
			incrementPr = 0;
		}
		moveOn(incrementPr);
		return false;
	});

	$("#contSlideshow_Pr .arrows_Pr #left_Pr").click(function(){
		incrementPr = incrementPr - 1;
		if (incrementPr < 0){
			incrementPr = slideSizePr-1;
		}
		moveOn(incrementPr);
		return false;
	});

	$("#contSlideshow_Pr .balls_Pr .ball_Pr").click(function(){
		incrementPr = parseInt($(this).text(), 10);
		moveOn(incrementPr);
		return false;
	});
}



/*--------------------------------------------------
AJAX
--------------------------------------------------*/
function ajaxG() {
/*	
    $("#contSlideshow_Pr #slideshow_Pr .slideshow_Pr:even a").click(function () {
		$(".slideshow_Pr .topLayer").removeClass("on");
		if($(this).hasClass("fwb")){
			$(this).parent().next().addClass("on");
		}else{
			$(this).prev().children(".topLayer").addClass("on");
		}
		var rel = $(this).attr("rel");
		scrollTopGallery();
		$("#heroWindow").append('<div class="loading"><img src="/img/loading.gif" /></div');
		$("#heroWindow").animate({'opacity':'0.1'}, 1000, function () {        
			$.ajax({
				url: "/WS/wsGetContent.asmx/getHeroWindow",
				type: "POST",
				async: false,
				cache: false,
				contentType: "application/json; charset=utf-8",
				data: JSON2.stringify({ 'co_id_caller': $("meta[name=doc_id]").attr("content"), 'co_id': rel }),
				dataType: "json",
				success: function (data) {
					$("#heroWindow").find(".loading").remove();
					$("#heroWindow").after(data.d.HTML).remove();
					$("#heroWindow").css({'opacity':'0.1'});
					noSlide();
					setTimeout(function(){
						gHero();
						$("#heroClose").show();
						$("#heroContent").show();
						$("#heroMore").show().css({"height":"auto","visibility":"visible"});
						$("#heroWindow").animate({'opacity':'1'}, 1000);
					},300);
				},
				error: function (data) {
					//alert(data.d.HTML)
				}
			})
		})
		return false;
	});
*/	

        // Bind to StateChange Event
    History.Adapter.bind(window, 'statechange', function () { // Note: We are using statechange instead of popstate
        var State = History.getState(); // Note: We are using History.getState() instead of event.state
        if (State.data.myRel) {
            scrollTopGallery();
            gHeroClose();
            $("#heroWindow").append('<div class="loading"><img src="/img/loading.gif" /></div');
            setTimeout(function () {
                $("#heroWindow").animate({ 'opacity': '0.1' }, 1000, function () {
                    //console.log(State.data.myRel);
                    $.ajax({
                        url: "/WS/wsGetContent.asmx/getHeroWindow",
                        type: "POST",
                        async: false,
                        cache: false,
                        contentType: "application/json; charset=utf-8",
                        data: JSON2.stringify({ 'co_id_caller': $("meta[name=doc_id]").attr("content"), 'co_id': State.data.myRel }),
                        dataType: "json",
                        success: function (data) {
                            // CLASSE ON SUL BOX ATTUALE
                            $(".slideshow_Pr .topLayer").removeClass("on");
                            if ($(".slideshow_Pr[rel=" + State.data.myRel + "] a").hasClass("fwb")) {
                                $(".slideshow_Pr[rel=" + State.data.myRel + "] a").parent().next().addClass("on");
                            } else {
                                $(".slideshow_Pr[myRel] a").prev().children(".topLayer").addClass("on");
                            }

                            $("#heroWindow").find(".loading").remove();
                            $("#heroWindow").fadeIn();
                            $("#heroWindow").after(data.d.HTML).remove();
							noSlide();
                            gaTrackPage(location.pathname);
                            gHero();
                            $("#heroImgFront a").trigger("click");
                            scrollTopGallery();
                            //$("#heroWindow").after(data.d.HTML).remove();
                            //gHero();
                            //$(window).scrollTop(0);
                        },
                        error: function (data) {
                            //alert(data.d.HTML)
                        }
                    })
                })
            }, 800);
        } else {
            window.location = State.url;
        }
    });    
		$("#contSlideshow_Pr #slideshow_Pr .slideshow_Pr a").click(function () {
			/*$(".slideshow_Pr .topLayer").removeClass("on");
			if($(this).hasClass("fwb")){
				$(this).parent().next().addClass("on");
			}else{
				$(this).prev().children(".topLayer").addClass("on");
			}*/
			var rel = $(this).attr("rel");
			var ajAddress = $(this).attr("href");
			ajTitle = ajAddress.replace(/_/g, " ");
			History.pushState( {myRel:rel}, ajTitle, ajAddress);			
            return false;
		});
}


/*--------------------------------------------------
CATALOGO COLORS
--------------------------------------------------*/
function changeCat(i){
	var my_loop;
	$("#catalogueFront").fadeOut(6000,function(){
		$("#catalogueFront").attr("src",'/img/catalogo/' + (i+1) +'.png');
		$("#catalogueFront").fadeIn(2000, function() {
			if(i==0){e= i+8;}else{e = i;}
			$("#catalogueBack").attr("src",'/img/catalogo/' + (e) +'.png');
		});
	});
	my_loop = setTimeout(function(){
		i = i + 1;
		if (i >= 8){
			i = 0;
		}
		changeCat(i);
	},8000);
}
function creaCatalogo() {
	var img = 1;
	$("#catalogueAnimation a").append('<img id="catalogueFront" src="/img/catalogo/' + img +'.png"/><img id="catalogueBack" src="/img/catalogo/' + (img + 1) +'.png"/>')
	changeCat(img)
}

/*--------------------------------------------------
CATALOGO PR
--------------------------------------------------*/

function myfade(){
	my_inc = 0;
	newsSize = $("#catalogueAnimation .imgPr").size();
	var my_loop;
	function fadeOn(my_par){
		$("#catalogueAnimation .imgPr:visible").hide()
		$("#catalogueAnimation .imgPr").eq(my_par).fadeIn(2000);
		//$("#catalogueAnimation .imgPr").eq(my_par-1).fadeOut(2000);
		my_loop = setTimeout(function(){
			my_inc = my_inc + 1;
			if (my_inc >= newsSize){
				my_inc = 0;
			}
			fadeOn(my_inc);
		},8000);
	}
	fadeOn(my_inc);
}


/*--------------------------------------------------
VIDEO
--------------------------------------------------*/
function setVideo(){
$(".slideshow_wrap .slideshow a").each( function() {
	var isV = $(this).attr("href");
	if (isV.indexOf('.')>-1) {} else {
		$(this).append('<span class="isVideo"></span>');
	}
});
}

/*--------------------------------------------------
Gallery
--------------------------------------------------*/
function scrollTopGallery() {
	var st = Math.max($("html").scrollTop(),$("body").scrollTop());
	if((st) > 145) {
		$('html, body').animate({ scrollTop: ($("#leftContent").offset().top -10) }, 800, "swing");
	}
}

function myGallery(){
    ytReadyInit();
    var firstVideo = $("#video .ytPlayer").children().attr("id");	
    $(".slideshow_wrap .slideshow a").eq(0).addClass("on");
	$(".slideshow_wrap .slideshow a").live("click",function(){
		if ($(this).hasClass("on")) {
			return false;
		}else{
		w = $(this).attr("href");
		$(".slideshow_wrap .slideshow a").removeClass("on");
		$(this).addClass("on");
		var dida = $(this).children("img").attr("alt");
		$("#labelImg").html(dida + "&nbsp;");
		scrollTopGallery();
		if (w.indexOf('.')>-1) {
			// IMMAGINE
			if (($("#video").css("z-index")) == "40"){
				$("#video").css("z-index","15");
			}else{
				$("#video").css("z-index","10");
			}
			function changeImg(i){
				$this = $("#heroImg");
				
				$this.find("#heroImgFront img").fadeOut(500,function(){
					$this.find(".loading").remove();
					$this.find("#heroImgFront img").attr("src",i);
					$this.find("#heroImgFront img").fadeIn(500);
				});
			}
			var img = $(this).attr("href");
			$this = $("#heroImg");
			$this.find(".loading").remove();
			$l = $('<div class="loading"><img src="/img/loading.gif" /></div');
			$this.append($l);
			$this.find("#heroImgBack img").attr("src",img);
			$.ajax({
				url:img,
				success:function(){
					changeImg(img);	
				},
				error:function(){
					changeImg(img);	
				}
			});
			if($(".ytPlayer").size() > 0){
				ytStopAllPlay();
			}
		} else {
			// VIDEO
			var ytkVideoAutoPlay = true;
			var video = $(this).attr("href");
			var imgVideo = $(this).children("img").attr("src");
			$("#heroImgFront img").attr("src","img/px.gif");
			$("#video").css("z-index","40");
			Swap(firstVideo,video);
//			console.log(firstVideo);
//			console.log(video);
		};
		return false;
		}
	});
}			
/*--------------------------------------------------
heroWindow
--------------------------------------------------*/
function gHeroInit() {
    gHero()
    $("#slideshow_Pr a[rel=" + $("#heroWindow").attr("rel") + "]").addClass("on")
    $(".slideshow_Pr[rel=" + $("#heroWindow").attr("rel") + "] .topColor .topLayer").addClass("on")
    if ($("#heroWindow").hasClass("open")) { gHeroOpenOnLoad() }
}

function gHero() {
	gMenu();
	setVideo();
	slideshow();
	myGallery();
	colorLayer();
	maxHeight($("#heroContent .bT"));
	topLayerHeight();
	var hContH = $('#heroContent').height();
	$('#heroMore').hide();
	$('#heroContent').hide();
	//$('#heroWindow .topColor .title span').append('<span id="titleGt"> &gt;</span>');
	$('#heroWindow .topColor .title , #heroImgFront a').click( function() {
		var s = $('#heroContent:visible').size();
		if(s == 0){
			gHeroOpen(hContH);
		}
		return false;
	});
	$('#heroClose').click( function() {gHeroClose();});
	
    if ($(".slideshow_Pr").size() < 2) {
	    $("#moreHeroNav").remove()
	} else {
	    //prev - next
	    var navSize = $(".slideshow_Pr").size()
	    //var navArr = []; $(".slideshow_Pr").each(function (i) { navArr[i] = $(this).attr("rel") })
	    //var navCurrIndex = navArr.indexOf($("#heroWindow").attr("rel"));
		var navCurrIndex = $(".slideshow_Pr[rel="+$("#heroWindow").attr("rel")+"]").index();
		//console.log(navCurrIndex);
	    $(".moreHeroPrev").click(function () {
	        if (navCurrIndex == 0) { navCurrIndex = navSize - 1 } else { navCurrIndex -= 1 }	        
	        $(".slideshow_Pr").eq(navCurrIndex).children("a").click()
	    })
	    $(".moreHeroNext").click(function () {
	        if (navCurrIndex == navSize - 1) { navCurrIndex = 0 } else { navCurrIndex += 1 }
	        $(".slideshow_Pr").eq(navCurrIndex).children("a").click()
	    })
    }

    //addThis
	var addThisJs = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
    if (window.addthis) {window.addthis = null;}
    $.getScript(addThisJs);

}

function gHeroOpen(e) {
	$('#heroWindow').removeClass("closed");
	$('#heroWindow').addClass("open");
	$('#heroClose').fadeIn(500);
	//$("#titleGt").fadeOut(100);
	$('#heroMore').show().animate({ height: ""+ e +"px" }, 1500).css("visibility","visible");
	scrollTopHero();
	$('#heroContent').delay(200).fadeIn(500);
}

function gHeroOpenOnLoad() {
    $('#heroWindow').removeClass("closed");
    $('#heroWindow').addClass("open");
    $('#heroClose').show();
    $('#heroMore').show().css("visibility", "visible");    
    $('#heroContent').show();
}

function scrollTopHero(){
	$('html, body').animate({ scrollTop: ($("#leftContent").offset().top -10) }, 2000, "swing").bind('mousewheel', function(){
		$('html, body').animate().stop();
    });
}


function gHeroClose() {
	// VIDEO VISIBLE > GOTO FIRST IMG
	$('#heroWindow').removeClass("open");
	$('#heroWindow').addClass("closed");
	if(($("#video").css("z-index")) == "40"){
		$(".slideshow_wrap .slideshow a").eq(0).trigger("click");
	}
	$("#titleGt").fadeIn(100);
	$('#heroClose').fadeOut(500);
	$('#heroContent').fadeOut(500);	
	//$('#heroMore').delay(200).animate({ height: "0px" }, 800, "swing");	
	$('#heroMore').animate({ height: "0px" }, 800, "swing");	
}

/*--------------------------------------------------
TOPLAYER HEIGHT
--------------------------------------------------*/
function topLayerHeight() {
	var tLh = $("#heroWindow .topColor .title").height();
	tLh = tLh + 26;
	$("#heroWindow .topColor .topLayer").height(""+ tLh +"px");
}

/*--------------------------------------------------
MAX HEIGHT
--------------------------------------------------*/

function maxHeight(group) {
	var tallest = 0;
	group.each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}

/*--------------------------------------------------
HOVER
--------------------------------------------------*/

function hoverType() {
	$("#types .box .imgBox").append("<span></span>");
	$("#types .box .imgBox span").css({'opacity':'0.7'})
	var hC = $("#types").attr("rel");
	$("#types .box .imgBox span").hover(function() {
		$(this).stop().animate({'backgroundColor':'#'+ hC +'','opacity':'0.2'}, 1000);
	}, function() {
		$(this).stop().animate({'backgroundColor':'transparent','opacity':'0'}, 2000);
	});
}

/*--------------------------------------------------
HEIGHT AWARDS
--------------------------------------------------*/

function maxHeightAwards() {
	mHa = ($(".boxAwardsDx").outerHeight()) + ($(".singleYear").outerHeight()) -17 ;
	$(".boxAwardsSx .boxAwards").height(""+ mHa +"");
}

/*--------------------------------------------------
LIST BOX WRAP AND ADD class LAST
--------------------------------------------------*/
function wrapAndLastBox() {
	if(($(".search").size()) != 1) {
		$(".contBox .box:nth-child(3n)").addClass("last");
		var $pArr = $('.pageB #contDx .box');
		var pArrLen = $pArr.length;
		for (var i = 0;i < pArrLen;i+=3){
			$pArr.filter(':eq('+i+'),:eq('+(i+1)+'),:eq('+(i+2)+')').wrapAll('<div class="wrapBox clearfix" />');
		};
	} else {
		$(".contBox .box:nth-child(4n)").addClass("last");
		var $pArr = $('.pageB #contDx .box');
		var pArrLen = $pArr.length;
		for (var i = 0;i < pArrLen;i+=4){
			$pArr.filter(':eq('+i+'),:eq('+(i+1)+'),:eq('+(i+2)+'),:eq('+(i+3)+')').wrapAll('<div class="wrapBox clearfix" />');
		};
	}
}

/*--------------------------------------------------
LIST BOX SET HEIGHT
--------------------------------------------------*/

function maxHeightWrapBox() {
	maxHeight($(".wrapBox .box .title"));
	$(".wrapBox").each( function() {
		var wrapH =	$(this).height();
		$(".box", this).height(wrapH -31);	
	});
	maxHeight($(".wrapBox .box .text"));
}


/*--------------------------------------------------
INIT
--------------------------------------------------*/

$(document).ready(function ()
{
	$(".gSelect").show();
	$('.scrollbar').jScrollPane().bind('mousewheel', function(e){
		e.preventDefault();
    });
	noSlide();
//	gMenu();
//	setVideo();
//	slideshow();
	slideshow_Pr();
//  myGallery();
	colorMenu();
//	colorLayer();
    creaCatalogo();
	myfade();
	siteMapHeight();
	//creaCatPr();
//	maxHeight($("#heroContent .bT"));
//	topLayerHeight();
	gHeroInit();
	maxHeight($("#types .box"));
	hoverType();
	wrapAndLastBox();
	setTimeout(function(){
		maxHeight($("#boxNews .box:odd"));
		maxHeight($("#boxNews .box:even"));
		maxHeight($(".preFooterBox"));
		maxHeightAwards();
		maxHeightWrapBox();
	},1000);
	ajaxG();
	$(".gSelected").not(".noOptions").click(function () { return gSelect(this); });
	$("#menuSx li").has('ul li').find("a:first").click(function () { return menuSx(this); });
	$(".generic .linkPr a").eq(0).addClass("first");
	$(".gOption").hide();
	$("#menuSx ul li ul").hide();	
	$('.fancybox').fancybox({
		  'overlayColor'  : '#fff',
		  'transitionIn'	: 'fade',
		  'transitionOut'	: 'fade',
		  'titleShow' : false
	});
   $('.pageB #contDx .box .read .gOption li a,.pageB #contDx .box .read .noOptions a').fancybox({
		  'overlayColor'  : '#EDEDED',
		  'transitionIn'	: 'fade',
		  'transitionOut'	: 'fade',
		  //'scrolling'	: 'no',
		  'width': '100%',
		  'height': '100%',
		  'titleShow' : false
	});
});





