$(function(){

	// CARTELLE ANNI nell'ARCHIVIO del CALENDARIO!!!
	var year = $('#year_none').html();
	if(year){
		$('#main_menu .level_2 a').each(function() {
			var year = $(this).html();
			$(this).attr("href","/eventi/archivio-eventi?Year="+year);
			$(this).addClass(year);
		});
		$('#main_menu .level_2 .'+year).css("color","#EF4034");
	}


	$('#news-homepage').fadeIn(500);


	// PER EVITARE DI VEDERE IL CALENDARIO CHE SI CARICA!
	$('.content').css('display','block');


	// FANCYBOX	| IMAGES
	if($("a.group-images").length > 0){
		$("a.group-images").fancybox({
			'showCloseButton'	:	true,
			'titlePosition'		:	'inside'
		});
	}

	// FANCYBOX | VIDEO
	$("#video").click(function(){
		$.fancybox({
			'padding'		: 0,
			'autoScale'		: false,
			'transitionIn'	: 'none',
			'transitionOut'	: 'none',
			'title'			: this.title,
			'width'			: 680,
			'height'		: 495,
			'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type'			: 'swf',
			'swf'			: {
				'wmode'		: 'transparent',
				'allowfullscreen'	: 'true'
			}
		});
		return false;
	});

	// FANCYBOX in DOVE SIAMO -> ROMA -> STORIA
	$("#list-items-image a").fancybox({
		'showCloseButton'	:	true,
		'titlePosition'		:	'inside'
	});

	// PHOTOGALLERY
	$('#photos').galleryView({
		panel_width		:	605,
		panel_height	:	400,
		frame_width		:	100,
		frame_height	:	60,
		theme_path		:	'/themes/dark'
	});


	// IN HOMEPAGE
	if ($('.content').hasClass("content-homepage")) {
		var h_hp_body = $('body').height();
		var h_hp_content = $('.content-homepage').height();
		
		if (h_hp_body<(h_hp_content-200)) {
			$('.slideshow-day').css('display','none');
			$('.link-txt-events').fadeIn(500);
		}
	}


	// CONTROLLO ALTEZZA BOX-DETAIL - ma solo se NON sono in Homepage
	if (!$('.content').hasClass("content-homepage")) {
		// controllo altezza per sticky footer
		var h_body = $('body').height(); 
		var h_content = $('.content').height();
		//alert(h_content+100);
		//alert(h_body);
		if ((h_content+100) > h_body) {
			$('.sticky-footer').css('display','none');
			$('.alternative-sticky-footer').css('display','block');
		} else {
			$('.sticky-footer').css('display','block');
			$('.alternative-sticky-footer').css('display','none');
		}	
	}

	var h_box_info_detail = $('.box-event-detail .box-content-info-detail').height();
	var h_box_docs_detail = $('.box-event-detail .box-content-docs-detail').height();
	if (h_box_docs_detail>h_box_info_detail) {
		$('.box-content-info-detail').css('height',h_box_docs_detail);
		$('#eventBody').css('height',(h_box_docs_detail-180));
	} else {
		$('.box-content-docs-detail').css('height',h_box_info_detail);
	}


	/* riadatta box eventi... */
	var h_body_load = $('body').height();
	var h_content_load = $('.content').height();	
	var sum = 165 + 70 + h_content_load;
	if (sum > h_body_load) {
		$('.HPBox .ABS').css('display','none');
		$('.HPBox img').css('margin-top','0');
	} else {
		$('.HPBox .ABS').css('display','block');
		$('.HPBox img').css('margin-top','20px');
	}

	$(window).resize(function() {
		var h_body = $('body').height();
		var h_content = $('.content').height();
		var sum = (165 + 70 + h_content);
		if (sum > h_body) {
			$('.HPBox .ABS').css('display','none');
			$('.HPBox img').css('margin-top','0');
		} else {
			$('.HPBox .ABS').css('display','block');
			$('.HPBox img').css('margin-top','20px');
		}

		// CONTROLLO ALTEZZA BOX-DETAIL
		var h_box_info_detail = $('.box-event-detail .box-content-info-detail').height();
		var h_box_docs_detail = $('.box-event-detail .box-content-docs-detail').height();
		if (h_box_docs_detail>h_box_info_detail) {
			$('.box-content-info-detail').css('height',h_box_docs_detail);
			$('#eventBody').css('height',(h_box_docs_detail-180));
		} else {
			$('.box-content-docs-detail').css('height',h_box_info_detail);
			//$('#eventBody').css('height',(h_box_info_detail));
		}
	}); // CLOSE DOCUMENT RESIZE


	/* SLIDESHOW HOMEPAGE */
	$('.slideshow').cycle({
		fx				:	'fade',
		speedIn		:	2500,
		speedOut	:	500
	});
	$('.banner-homepage').fadeIn('slow');

	$('.slideshow-day').cycle({
		fx				:	'fade',
		speedIn		:	1000, 
		speedOut	:	1000
	});

	if($('#ticker').length > 0){
		$("#ticker").jStockTicker({interval: 45});
	}

	var lang_translation = {
		it	:	"italiano", 
		en	:	"english",
		es	:	"español",
		fr	:	"français"
	};


	/* ------------------------------------------------ */
	/* REDIRECT LINKS	                                */
	/* ------------------------------------------------ */
	$("a.cat_51").attr("href","http://www.reteurbs.org/search~S9/").click(function(){ this.target = "_blank"; });
	$("#Rapporto").click(function(){ this.target = "_blank"; });	
	$("a[rel='external']").click(function(){ this.target = "_blank"; });

	/* Archivio -> Links to the old site... */
	$("a.cat_83").attr("href","http://archivio.istitutosvizzero.it/"+ lang_translation[maui_runtime.current_language] +"/roma/archivio/archivio_cultura/2005/program_01.html").click(function(){ this.target = "_blank"; }); // Archivio Arte
	$("a.cat_57").attr("href","http://archivio.istitutosvizzero.it/"+ lang_translation[maui_runtime.current_language] +"/roma/archivio/archivio_scienza/2005/programmi.html").click(function(){ this.target = "_blank"; }); // Archivio Scienze

	/* ------------------------------------------------ */
	/* CONTENT DIMENSIONS                               */
	/* ------------------------------------------------ */

	var HPBoxesNum		=	parseInt($('.content').children('.HPBox').size(),10);
	var CalendarsNum	=	parseInt($('.content').children(".calendar").size(),10);
	var ActivitiesNum	=	parseInt($('.content').children(".activities").children(".activities_stack").size(),10);

	var HistoryItemsNum	=	parseInt($('.content').children(".Hitem").size(),10);
	var ContentWidth,WinHeight,transition,myMonth;

	if(HPBoxesNum !== 0){
		ContentWidth = (230 * HPBoxesNum); // Single box width * n° boxes - paddingLeft first element
		WinHeight = $(window).height();
		$(".container").css("width",ContentWidth);
		$(".content").css("width",ContentWidth);
		$("#main_menu").css("height",WinHeight);
	} else {
		//=> Calendar Dimensions
		if(CalendarsNum !== 0){
			ContentWidth = (680 * CalendarsNum);
			WinHeight = $(window).height();
			$(".content").css("width",ContentWidth).addClass("calendars");
			$("#main_menu").css("height",WinHeight);
		}

		//=> Activities Dimensions
		if(ActivitiesNum !== 0){
			ContentWidth = (960 * ActivitiesNum);
			WinHeight = $(window).height();
			$(".content").css("width",ContentWidth);
			$("#main_menu").css("height",WinHeight);
		}

		//=> History
		if(HistoryItemsNum !== 0){
			ContentWidth = (314 * (HistoryItemsNum + 0.5));
			WinHeight = $(window).height();
			$(".content").css("width",ContentWidth);
			$("#main_menu").css("height",WinHeight);
		}
	}

	/* ------------------------------------------------ */
	/* HOMEPAGE                                         */
	/* ------------------------------------------------ */
	$(".HPBox").hover(function() {
		$(this).children("h4").children("a").css("color","#000000");
		$(this).children("div.ABS").children("p").css("color","#000000");
		$(this).children(":not(span)").css("color","#000000");
		$(this).children("img").hoverFlow('mouseenter', { opacity: 1 }, 'normal');
	}, function() {
		$(this).children(":not(span)").css("color","#C6C7C8");
		$(this).children("div.ABS").children("p").css("color","#C6C7C8");
		$(this).children("h4").children("a").css("color","#C6C7C8");
		$(this).children("img").hoverFlow('mouseleave', { opacity: 0 }, 'normal');
	});


	/* ------------------------------------------------ */
	/* ACTIVITIES CALENDAR                              */
	/* ------------------------------------------------ */
	myMonth = new Date();
	myMonth = myMonth.getMonth() + 1;
	if(myMonth === 13) {
		myMonth = 1; // If we're in December...
	}

	$(".activities").children(":not(.cal_" + myMonth + ")").children("div").addClass("activities_item_nonactive");
	$(".activities").children(".cal_" + myMonth).children("div").addClass("activities_item_active");

	// Activities slide
	if(ActivitiesNum !== 0){
		transition = (960 * (myMonth - 1)) - (109 * 2.76);
		$(".content").animate({ marginLeft: "-" + transition + "px"}, 500);
		$("div.months > a#" + myMonth).addClass("currMonth");
	}

	$("a.activities_month").click(function(){
		$(this).siblings().removeClass("currMonth");
		$(this).addClass("currMonth");
		var selMonth = $(this).attr("id");

		$(".activities").children(":not(.cal_" + selMonth + ")").children("div").removeClass("activities_item_active").addClass("activities_item_nonactive");
		$(".activities").children(".cal_" + selMonth).children("div").removeClass("activities_item_nonactive").addClass("activities_item_active");

		if(selMonth === "1"){
			$(".content").animate({ marginLeft: "310px"}, 500);
		} else if(selMonth === "2") {
			transition = (700 * (selMonth - 1)) - 1350;
			$(".content").animate({ marginLeft: transition + "px"}, 500);
			//console.log(261 * (selMonth - 1));
		} else {
			transition = (960 * (selMonth - 1)) - (109 * 2.76);
			/*transition = (920 * (selMonth - 1)) - (80 * 2.76);*/
			$(".content").animate({ marginLeft: "-" + transition + "px"}, 500);
			//console.log(261 * (selMonth - 1));
		}
	});


	/* ------------------------------------------------ */
	/* CALENDAR                                         */
	/* ------------------------------------------------ */

	$("a#BackToCalendar").click(function(){
		refer('&m=' + $.cookie("month"));
	});


	function refer(args) {
		var ref = document.referrer;
		var myStart = ref.indexOf("?");
		if ((ref) && (ref !== "")) {
			location.href = ref;
		}
	}

	myMonth = new Date();
	myMonth = myMonth.getMonth() + 1;
	myMonth = 1;

	if(myMonth === 13) {
		myMonth = 1; // If we're in December...
	}

	if(myMonth === 1){
		transition = 1;
	} else {
		transition = (680 * (myMonth - 1)) - (109 * 2.76);
		transition = "-" + transition;
	}

	//transition = (680 * (myMonth - 1)) - (109 * 2.76);
	if(myMonth !== 1) {
		$(".calendars").animate({ marginLeft: transition + "px"}, 500);
		$("div.months > a#" + myMonth).addClass("currMonth");
	} else {
		if ( (year!==2010) && (year!==null) ) {
			$("div.months > a#" + myMonth).addClass("currMonth");
		}
	}


	// ++++ Science event or Art event ++++ //
	$(".event").each(function() {
		if($(this).hasClass("cat_11")) {
			$(this).children(".event_det").addClass("Aicon");
		} else if($(this).hasClass("cat_12")) {
			$(this).children(".event_det").addClass("Sicon");
		}
	});

	// ++++ Single Event Hover Effect ++++ //
	$(".event").hover(function() {
		$(this).hoverFlow('mouseenter', { opacity: 1 }, 'normal');
	  }, function() {
		$(this).hoverFlow('mouseleave', { opacity: 0.5 }, 'normal');
	});

	$("a[id^='event_']").click(function(){
		$("div.Highlighted").stop().animate({ opacity: 0.5 }, 'normal');
		var CurrentClass = $(this).attr("id");
		CurrentClass = CurrentClass.replace("event_","");	
		$("div." + CurrentClass).stop().addClass('Highlighted').animate({ opacity: 1 }, 'normal');
		$(".cal_categories li a").each(function() {
			$(this).removeClass("selected-red");
		});
		$('#event_'+CurrentClass).addClass("selected-red");
	});

// ++++ Slide calendar when click on month ++++ //
	$("a.event_month").click(function(){
		$("div[id^='EventDetail']").hide();	
		$(this).siblings().removeClass("currMonth");
		$(this).addClass("currMonth");
		var selMonth = $(this).attr("id");
		$.cookie("month",selMonth);
		if(selMonth === "1"){
			$(".content").animate({ marginLeft: "310px"}, 500);
		} else {
			transition = (680 * (selMonth - 1)) - (109 * 2.76);
			$(".content").animate({ marginLeft: "-" + transition + "px"}, 500);
		}
	});

	function showDetail() {
		$("div[id^='EventDetail']").hide();	
		
		if($(this).hasClass("cat_11")) {
			//	$(this).children(".event_det").addClass("Aicon");
			//alert("Aicon");
			$('.icon-detail').addClass('Aicon');
			
		} else if($(this).hasClass("cat_12")) {
			//$(this).children(".event_det").addClass("Sicon");
			//alert("Sicon");
			$('.icon-detail').addClass('Sicon');
		}
		
		
		
		//=> Get the id and clean it...
		var currID = $(this).attr("id");
		currID = currID.replace("DetEvent_","");
		$("#EventDetail_" + currID).removeShadow();
		
		//get the position of the div element
		var pos = $(this).offset();  
		//var width = $(this).width();
		//show the menu directly over the placeholder
		if($(this).hasClass("last")) {
			$("#EventDetail_" + currID).css({ "left": (pos.left - 110) + "px", "top":pos.top + "px" } );
		} else if($(this).hasClass("row2")) { 
			$("#EventDetail_" + currID).css({ "left": (pos.left) + "px", "top":pos.top - 212 + "px" } );
		} else {
			$("#EventDetail_" + currID).css({ "left": (pos.left) + "px", "top":pos.top + "px" } );
		}
	
		if($(this).hasClass("row3") && $(this).hasClass("last")) { 
			$("#EventDetail_" + currID).css({ "left": (pos.left - 110) + "px", "top":pos.top - 212 + "px" } );
		}

		

		$("#EventDetail_" + currID).show();
		$("#EventDetail_" + currID).dropShadow({
			left    : 5,
			top     : 5,
			blur    : 5,
			opacity : 0.8
		});
	}

	$("div[id^='DetEvent_']").click(showDetail);

	$("a.closeDet").click(function(){
		$(this).parent().parent().css("display","none");
		$(this).parent().parent().removeShadow();
	});

	$("div.ShowDetail").click(function(){});
	
	// => Footer Banners
	$("#FootBanner1").click(function(){ 
		$(".DetBanner1").fadeIn('normal'); 
		$(".DetBanner2").fadeOut('normal');
		$(".DetBanner3").fadeOut('normal');
		$(".Banner1").css("margin-top","0px"); 
	});
	
	$("#Close1").click(function(){ 
		$(".DetBanner1").fadeOut('normal'); 
		$(".Banner1").css("margin-top","130px");	
	});

	$("#FootBanner3").click(function(){ 
		$(".DetBanner1").fadeOut('normal'); 
		$(".DetBanner2").fadeOut('normal');
		$(".DetBanner3").fadeIn('normal'); 
		$(".Banner3").css("margin-top","0px"); 
	});
	
	$("#Close3").click(function(){ 
		$(".DetBanner3").fadeOut('normal'); 
		$(".Banner3").css("margin-top","130px");	
	});


	$("a.cat_31").click(function(){
		$(this).attr("href","http://www.facebook.com/pages/Istituto-Svizzero-di-Roma-ISR/103465293052947");
		$(this).attr("target","_blank");
		
	});


	/* MAIN NAVIGATION */
	function show() {
		var menu = $(this).children("ul");
		menu.slideDown();
	}
	function hide() { 
		var menu = $(this).children("ul");
		if(!menu.hasClass('selected')){
			menu.slideUp();
		}
	}
	$("#main_menu li.level_0").hoverIntent({
		sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
		interval: 50,   // number = milliseconds for onMouseOver polling interval
		over: show,     // function = onMouseOver callback (required)
		timeout: 300,   // number = milliseconds delay before onMouseOut
		out: hide       // function = onMouseOut callback (required)
	});

	if($("#scroller").length > 0){
		$("#scroller").simplyScroll({
			speed: 12
		});
	}

	if($("#panorama_wrap").length > 0){
		// PRELOAD PANORAMA IMAGE
		var imgList = [];
		$.extend({
			preload: function(imgArr, option) {
				var setting = $.extend({
					init: function(loaded, total) {},
					loaded: function(img, loaded, total) {},
					loaded_all: function(loaded, total) {}
				}, option);
				var total = imgArr.length;
				var loaded = 0;
				
				setting.init(0, total);
				for(var i in imgArr) {
					imgList.push($("<img />")
						.attr({
									src: imgArr[i],
									width: 14746,
									height: 360
									})
						.load(function() {
							loaded++;
							setting.loaded(this, loaded, total);
							if(loaded == total) {
								setting.loaded_all(loaded, total);
							}
						})
					);
				}
				
			}
		});
		$.preload(panoramaImgSrc, {
			loaded: function(img, loaded, total) {
				$("#panorama_wrap").html(img).children('img').panorama();
			}
		});

	}


	// VIRTUAL TOUR
	if($("#virtualtourMap_wrap").length > 0){
		$("area.showFanImage").fancybox({
			'showCloseButton'	:	true,
			'titlePosition'		:	'inside'
		});

		$("area.showHLTitle").hover(
			function(){
				txtID = $(this).attr('href');
				$(txtID).css('color','#D62027');
			},
			function(){
				$(txtID).css('color','#000000');
			}
		);

	}




	$('a.homebanner-id865').click( function() {
		if(navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)){
			//alert('Download Streamer App from iTunes store');
			window.open( 'http://istitutosvizzero.it/themes/istituto_svizzero/isrstreaming.html' );
			return false;
		} else {
			window.open( $(this).attr('href'),'popup','scrollbars=no,width=420,height=340,top=50,left=23' );
			return false;
		}
	});


});
