var flagAnimazione = true;
//var marginLeft = 390;

var itemWidth;
var marginLeft = 0; 
//var itemBigWidth = 620;
var itemBigWidth = 590;
var offsetWidth = 41;
var time = 1500; //1500
var vContenutoBlockSmall = new Array();
var itemAttivo = null;
var numItems = 0;
var defaultEase = 'easeOutQuart'; // easeOutQuint easeOutExpo easeOutQuart
var numeroRipetizioniAccodamento = 0;

var maxWidth = 980;
var maxHeight = 500;

var checkScreenDimension;

var vBack = new Array();
vBack.push('/img/Back1.jpg');
vBack.push('/img/Back2.jpg');
vBack.push('/img/Back3.jpg');
vBack.push('/img/Back4.jpg');
vBack.push('/img/Back5.jpg');

$(document).ready(function () {
		   
	$('body').css('background-image', 'url(' + vBack[Math.floor(Math.random() * vBack.length)] + ')');
	
	$('#container2').css('left', marginLeft);
	itemWidth = $('#container2 div.channelPagesList ul').children('li.channelPagesListItem').outerWidth();

	$('#container2').css('width', 5000000);
	
	// RIEMPO UN ARRAY CON IL CONTENUTO DEGLI ITEM SMALL //
	$('#container2 div.channelPagesList ul').children('li.channelPagesListItem').each( function(){
		vContenutoBlockSmall[$(this).attr("id")] = $(this).html();
		numItems++;
	});
	
	// INTERCETTO PARAMETRO IN GET E SPOSTO LA LISTA //
	$.urlParam = function(name){
		var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
		return (results)?results[1]:0;
	}	
	
	if($.urlParam('anchor')) spostaListaDaAnchor($.urlParam('anchor'));
	
		
	$('#next').click(function(){ next() });
	
	$('#prev').click(function(){ prev()	});
	
    $('#container2 div.channelPagesList a.link-dett').click(function(){	
		clickOpenDett($(this));
	});
	
	



	if( !$('#container2 div').hasClass('contatti') && $('#people').length == 0 )
	{
		$(this).mousewheel(function(event, delta) {
			if (delta < 0) next();
			else if (delta > 0) prev();
		});
		
		$(this).keyup(function(event) { handleArrowKeys(event) });
	}
	else 
	{
		$('#navigazione').hide();
	}
		
	
	
	
	
	// CACHING BG IMAGE //
	jQuery.each(vBack, function(i) {
	  vBack[i] = new Image();
	  vBack[i].src = this;
	});
	
	
	checkScreenDimension = function() {	

		$('#global').css( 'overflow', 'auto' );
							  
		// WIDTH //
		if( $(window).width() <= maxWidth )
		{
			$('#global').width( maxWidth );
			//
			$('#main').width( maxWidth );
		}
		else 
		{
			$('#global').width( '100%' );
			//
			$('#main').width( '100%' );
		}
		
		// HEIGHT //
		if( $(window).height() <= maxHeight )
		{
			$('#global').height( maxHeight );
			//
			$('#main').css('top', ( maxHeight - $('#main').height() ) / 2 ).css('margin-top','0px');
		}
		else 
		{
			$('#global').height( '100%' );
			//
			$('#main').css('top','50%').css('margin-top','-240px');
		}
	}
	
	checkScreenDimension();
	$(window).resize( checkScreenDimension );
	
});	
	
function accodaItem(){
	
	numeroRipetizioniAccodamento++;
	
	suffissoIdBlockNew = '';
	for(i=0; i<numeroRipetizioniAccodamento; i++){ suffissoIdBlockNew += '__1' }
	
	for (var idBlock in vContenutoBlockSmall)
	{  
		newBlock = vContenutoBlockSmall[idBlock];
		$('#container2 div.channelPagesList ul').append('<li class="channelPagesListItem" id="' + idBlock + suffissoIdBlockNew + '">' + newBlock + '</li>');
		$('#container2 div.channelPagesList ul li').each( function(){
			if( $(this).attr("id") == idBlock + suffissoIdBlockNew )
			{
				$(this).children('div').attr("class", $(this).children('div').attr("class") + suffissoIdBlockNew);
			}
		});
	}
	
	//alert(numeroRipetizioniAccodamento);
}


function clickOpenDett(obj)
{
	nameAnchor = obj.parents("li.channelPagesListItem>div").attr("class");
	spostaListaDaAnchor(nameAnchor);
		
	idContainer = obj.parents("li.channelPagesListItem").attr("id");
	if(idContainer) openDett(idContainer);
}
	
	
function spostaListaDaAnchor(nameAnchor)
{
	/*$.urlParam = function(name){
		var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
		return results[1] || 0;
	}
	*/
	
	indiceItem = null;
	indice = 0;
	$("#container2 ul li").each( function(){
		if( $(this).children("div." + nameAnchor).html() != null )
		{
			indiceItem = indice;
		}
		indice++;
	});
	
	var target = - indiceItem * itemWidth;
	if(target < 0)
	{
		flagAnimazione = false;
		$('#container2').animate({left:target}, {duration: time, easing: defaultEase, complete:function() { flagAnimazione = true } } );
	}
}

function prev()
{
	if(flagAnimazione)
	{				  
	
		// CHIUDO DETTAGLIO E DO ALPHA A TUTTO //
		closeDett(itemAttivo);
		$('#container2 div.channelPagesList ul').children('li.channelPagesListItem').each( function(){
			$(this).ClearTypeFadeTo({ speed: 0, opacity: 1});
		});
		itemAttivo = null;
		//
			
		var cont = $('#container2');
		var position = cont.position();
		var target = position.left + itemWidth * 2;
		if(target <= marginLeft)
		{
			flagAnimazione = false;
			$('#container2').animate({left:target}, {duration: time, easing: defaultEase, complete:function() { flagAnimazione = true } } );
		} else {
			flagAnimazione = false;
			$('#container2').animate({left:0}, {duration: time, easing: defaultEase, complete:function() { flagAnimazione = true } } );
		}
	}	
}

function next()
{
	if(flagAnimazione)
	{
		
		// CHIUDO DETTAGLIO E DO ALPHA A TUTTO //
		closeDett(itemAttivo);
		$('#container2 div.channelPagesList ul').children('li.channelPagesListItem').each( function(){
			$(this).ClearTypeFadeTo({ speed: 0, opacity: 1});
		});
		itemAttivo = null;
		//		
		
		//openIndexFlag = (itemAttivo) ? 1 : 0;
		var cont = $('#container2');
		var position = cont.position();
		var target = position.left - itemWidth * 2;
		var targetAccodamento = position.left - itemWidth * 10;
		
		numItems = 0;
		$('#container2 div.channelPagesList ul').children('li.channelPagesListItem').each( function(){ numItems++ });				
		
		
		//var control = - (numItems + openIndexFlag) * itemWidth;
		var control = - numItems * itemWidth;
		
		
		if(targetAccodamento < control){ accodaItem() }
		flagAnimazione = false;
		$('#container2').animate({left:target}, {duration: time, easing: defaultEase, complete:function() { flagAnimazione = true } } );

		
		/*
		var control = - (numItems + openIndexFlag) * itemWidth;
		if(target > control)
		{
			flagAnimazione = false;
			//$('#container2').animate({ left: target }, time, function() { flagAnimazione = true });
			$('#container2').animate({left:target}, {duration: time, easing: defaultEase, complete:function() { flagAnimazione = true } } );
		} else {
			//goToFirst();
		}
		*/
		
	}
}


function goToFirst()
{
	if(flagAnimazione)
	{
		
		// CHIUDO DETTAGLIO E DO ALPHA A TUTTO //
		closeDett(itemAttivo);
		$('#container2 div.channelPagesList ul').children('li.channelPagesListItem').each( function(){
			$(this).ClearTypeFadeTo({ speed: 0, opacity: 1});
		});
		itemAttivo = null;
		//
		
		flagAnimazione = false;
		$('#container2').animate({left:0}, {duration: time, easing: defaultEase, complete:function() { flagAnimazione = true } } );
	}
}


	
function handleArrowKeys(evt) {
	evt = (evt) ? evt : ((window.event) ? event : null);
	if (evt) {
		switch (evt.keyCode) {
			case 37:
				prev();
				break;    
			case 39:
				next();
				break;    
		 }
	}
}

function openDett(block)
{
	$('#container2 div.channelPagesList ul').children('li.channelPagesListItem').each( function(){
		$(this).ClearTypeFadeTo({ speed: 0, opacity: 0.2});
	});
	
	if(itemAttivo != null) closeDett(itemAttivo);
	
	blockFormat = block.split("__");
	blockFormat = blockFormat[0];
	
	itemAttivo = block;
		
	id = '#' + block;
	idPagina = getId(blockFormat);
	
	$(id).ClearTypeFadeTo({ speed: 0, opacity: 1});
	
	$(id).html('<img src="/img/ajax-loader.gif" />');
	
	$(id).animate({ width: itemBigWidth }, {duration: time, easing: defaultEase, complete:function() { flagAnimazione = true } } );
	
	$(id).load('/index.php?id='+idPagina, function() {
		
		var actualNumber = 1;
		
		/////////////////////////////////////
		
		
		
		/*
		$.each($("#contImgs div").children("img"), function(key, value) { 
			$(this).wrap('<div class="item" style="height:'+ $(this).css('height') +'"></div>');
		});
		$.each($("#contImgs div").children("object"), function(key, value) { 
			$(this).wrap('<div class="item" style="height:'+ $(this).css('height') +'"></div>');
		});
		*/
		
		$.each( $("#contImgs img"), function(key, value) { 
			$(this).wrap('<div class="item" style="height:'+ $(this).css('height') +'" />');
		});
		$.each( $("#contImgs object"), function(key, value) { 
			$(this).wrap('<div class="item" style="height:'+ $(this).css('height') +'" />');
		});
		
		
		/////////////////////////////////////
		
		//var numImgs = $("#contImgs div").children("img").length;
		//var numImgs = $("#contImgs div").children("div.item").length;
		var numImgs = $("#contImgs div.item").length;
		
		$('div.dettaglio', id).hide();
		$('div.dettaglio', id).ClearTypeFadeIn({ speed: 1000, callback: function() {
				
				//$.each($("#contImgs div").children(".item"), function() {
				$.each($("#contImgs div.item"), function() {
					var id = $(this).children().attr("id");
					var obj = $(this).children();
					if( id.indexOf( "video" ) !== -1 )
					{
						if( document.getElementById( id ).playVideo )
						{
							document.getElementById( id ).playVideo();
						}
						else
						{
							document.getElementsByName( id )[0].playVideo();
						}
						return false;
					}
				});
				
			}
		});
		
		
		
		
		
		
		
		
		
		$('a.link-back', id).click(function(){
			itemAttivo = null;
			closeDett(block);
			
			$('#container2 div.channelPagesList ul').children('li.channelPagesListItem').each( function(){
				$(this).ClearTypeFadeTo({ speed: 0, opacity: 1});
			});
			
		});
		
		if( numImgs > 1)
		{
			$('#up', id).click(function(){
				
				if(flagAnimazioneDett == true)
				{	
					actualNumber = actualNumber-1;
					
					if(actualNumber > 0)
					{
						scrollImgs('up');
						$('.numImgs', id).html(actualNumber + '/' + numImgs);
					} else {
						actualNumber = 1;
					}
				}
			});
		
			$('#down', id).click(function(){
				
				if(flagAnimazioneDett == true)
				{
					actualNumber = actualNumber+1;
					
					if(actualNumber <= numImgs)
					{
						scrollImgs('down');
						$('.numImgs', id).html(actualNumber + '/' + numImgs);
					} else {
						actualNumber = numImgs;
					}
				}
			});
			
			$('.numImgs', id).html(actualNumber + '/' + numImgs);
			
			/* CLICK SULLE IMMAGINI 
			$("#contImgs div").children("img").css('cursor','pointer');
			$("#contImgs div").children("img").click(function(){
				scrollImgs('down');
			});
			*/
		} else {
			$('#up', id).css('display', 'none');
			$('#down', id).css('display', 'none');
			$('.numImgs', id).css('display', 'none');
		}		
	});
}

function closeDett(block)
{	
	id = '#'+block;
	blockFormat = block;
	if(block)
	{
		blockFormat = block.split("__");
		blockFormat = blockFormat[0];
	}
	
	newWidth = itemWidth - offsetWidth;
		
	//$(id).animate( { width: newWidth }, time);
	$(id).animate({ width: newWidth }, {duration: time, easing: defaultEase } );
		
		
	$(id).html(vContenutoBlockSmall[blockFormat]);
	
	$('div.inside', id).hide();
	$('div.inside', id).ClearTypeFadeIn({ speed: time });
	
	/*
	$('#container2 div.channelPagesList a.link-dett').click(function(){	
		idContainer = $(this).parents("li.channelPagesListItem").attr("id");
		if(idContainer) openDett(idContainer);
	});
	*/
	
	$('#container2 div.channelPagesList a.link-dett').click(function(){	
		clickOpenDett($(this));
	});
	
}

function getId(labelId)
{
	return labelId.replace("block","");
}

// DETTAGLIO //

var flagAnimazioneDett = true;
var timeDett = 1000; // millisecondi

function scrollImgs(type)
{
	if(flagAnimazioneDett == true)
	{	
		flagAnimazioneDett = false;
		
		//altezzaImg = parseInt($("#contImgs div").children("div.item").css('height').replace("px",""));
		altezzaImg = parseInt($("#contImgs div.item").css('height').replace("px",""));
		//altezzaImg = 330;
		
		//$.each($("#contImgs div").children("object"), function() {
		$.each($("#contImgs object"), function() {
			
			if( document.getElementById( $(this).attr('id') ).stopVideo )
			{
				document.getElementById( $(this).attr('id') ).stopVideo();
			}
			else
			{
				document.getElementsByName( $(this).attr('id') )[0].stopVideo();
			}	
			
		});
		
		switch(type)
		{
			case 'down':
				//numero = $("#contImgs div").children("div.item").length;
				numero = $("#contImgs div.item").length;
				targetY = parseInt($('#contImgs').css('top').replace("px","")) - altezzaImg;
				if(targetY >= - (numero-1) * altezzaImg)
				{
					//$('#contImgs').animate({ top: targetY }, timeDett, function() { flagAnimazioneDett = true });
					$('#contImgs').animate({ top: targetY }, {duration: timeDett, easing: defaultEase, complete:function() { flagAnimazioneDett = true } } );
				} else {
					//$('#contImgs').animate({ top: 0 }, timeDett, function() { flagAnimazioneDett = true });
					$('#contImgs').animate({ top: 0 }, {duration: timeDett, easing: defaultEase, complete:function() { flagAnimazioneDett = true } } );
				}
			break;
			
			case 'up':
				targetY = parseInt($('#contImgs').css('top').replace("px","")) + altezzaImg;
				if(targetY <= 0)
				{
					//$('#contImgs').animate({ top: targetY }, timeDett, function() { flagAnimazioneDett = true });
					$('#contImgs').animate({ top: targetY }, {duration: timeDett, easing: defaultEase, complete:function() { flagAnimazioneDett = true } } );
				} else {
					flagAnimazioneDett = true;
				}
			break;
		}
	}
}
