var fb = false;
var flicrk = false;
var youtube = false;

function handleTab(tabA){
	tabA.click(function(){
		var _this = $(this),
			indice = tabA.index(_this),
			postWrapper = $(".post_wrapper > div");//sono i contenitori dei post
			titolo = _this.attr("title");
		postWrapper.hide();
		postWrapper.eq(indice).fadeIn('slow');
		tabA.parent("li").removeClass("on");
		_this.parent("li").addClass("on");
		
		//queste funzioni sono in dynamic.js. Gli if servono a non sovrapporre le esecuzioni
		if(fb==false && titolo=="facebook"){
			doFacebook.init();
			fb=true;
		}
		if(flicrk==false && titolo=="flickr"){
			getFlickr();
			flicrk=true;
		}
		if(youtube==false && titolo=="youtube"){
			getYoutube();
			youtube=true;
		}
				
		//getTwitter();//richiamata nel document ready perche il primo tab aperto e twitter
		//getLinkedin();
		
		return false;
	});
}

function hideLoading(){
	$(".loading").fadeOut(400);
}

function carousel(){
	if($(".carousel ul li").eq(0)){
		$(".btn_prev").addClass("disabled");
	}
	$(".carousel").jCarouselLite({
		btnNext: '.btn_next',
		btnPrev: '.btn_prev',
		visible: 3,
		circular:false,
		speed:700
	});
}

function carouselPost(div){
	div.jCarouselLite({
		auto: true,
		speed: 3000,
		vertical: true,
		visible: 1
	});
}

var scrollVerb={
	verbs:["inspire", "feed", "elevate", "boost", "cheer"],
	h2:null,
	current:0,
	init:function()
	{
		scrollVerb.h2 = $("#header h2 span.verb");
		setInterval('scrollVerb.rotate()',4000);
	},
	rotate:function()
	{
		scrollVerb.h2.fadeOut(500,
			function()
			{
				scrollVerb.current++;
				if (scrollVerb.current>scrollVerb.verbs.length) scrollVerb.current=0;
				scrollVerb.h2.html(scrollVerb.verbs[scrollVerb.current]);
				scrollVerb.h2.fadeIn(500);
			}
		)
	}
}

function imgFlip(){	
	$(".toFlip").each(function(){
		var _this = $(this);
		_this.click(function(){
			_this.flip({
				onBefore: function(){//imposto altezza e larghezza del div da flippare, cosi che siano identiche sia prima sia dopo la rotazione e permettano un miglior effetto carta da gioco
					var h = _this.height(),
						w = _this.width();
					_this.css({width:w,height:h});
				},
				direction: 'rl',
				color:'#e33b30',
				content: $(".toFlipBack"),
				speed: 400,
				onEnd: function(){
					flipBackContent();					
				}
			});
			_this.prev(".logo_case_history").fadeOut(2000);
			return false;
		});
	});
}

function flipBackContent(){
	$(".revert").each(function(){
		var _this = $(this);
		_this.click(function(){
			_this.parent(".toFlip").revertFlip();
			_this.parent(".toFlip").prev(".logo_case_history").fadeIn(2000);
			return false;
		});
	});
}

function filterNews(tabA){
	var contenitori = $(".wrapper");
	tabA.click(function(){
		var _this = $(this),
			filtro = _this.attr("title");
		tabA.parent("li").removeClass("on");
		_this.parent("li").addClass("on");
		contenitori.fadeOut();
		if(filtro!="tutto"){$(".wrapper."+filtro).fadeIn();}
		else{contenitori.show();}
		//doMasonry();
		return false;
	});
}

function handleYoutubeThumb(){
	var img,  
		url, 
		_this,	
		contenitore = $(".thumb_wrapper"), // contiene l img grande del box di sx
		btn_video = $(".blog_post_wrapper .wrapper .btn_video:first"); // si tratta del link del box di sx
	
	//ottengo le thumb piccole
	$(".video_list a").each(function(){		
		_this = $(this);
		img = $("<img>"); 
		url = "http://img.youtube.com/vi/";		
		img.attr({"src":url+_this.attr("href").split("v=")[1]+"/2.jpg"});
		_this.html(img);
	})
	.click(function(){
			$(".video_controls").removeClass("opacity");
			$(".video_controls a[title=play]").addClass("opacity");
			updateVideo($(this).attr("href").split("v=")[1]);// questo parametro imposta l id del video e lo aggiorna
			return false;
		}
	);
	
	//ottengo la thumb grande
	btn_video.each(function(){
		_this = $(this);
		img = $("<img>");
		url = "http://img.youtube.com/vi/";
		img.attr({"src":url+_this.attr("href").split("v=")[1]+"/0.jpg"});
		//contenitore.html(img);
	});	
}

function youtubePlayer(){
	function playVideo(){
		if (ytplayer){
		  ytplayer.playVideo();
		}
	}

	function pauseVideo(){
		if (ytplayer){
		  ytplayer.pauseVideo();
		}
	}

	function muteVideo(){
		if(ytplayer){
		  ytplayer.mute();
		}
	}

	function unMuteVideo(){
		if(ytplayer){
		  ytplayer.unMute();
		}
	}
	
	// The "main method" of this sample. Called when someone clicks "Run".
	function loadPlayer(){
		// Lets Flash from another domain call JavaScript
		var params = { allowScriptAccess: "always" };
		// The element id of the Flash embed
		var atts = { id: "ytPlayer" };
		// All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
		swfobject.embedSWF("http://www.youtube.com/apiplayer?"+"&enablejsapi=1&playerapiid=player1","videoDiv", "377", "284", "8", null, null, params, atts);
	}
	
	function _run(){
		loadPlayer();
	}
	google.setOnLoadCallback(_run);
}	  

function updateVideo(idVideo){
	ytplayer.cueVideoById(idVideo);//aggiorno l id del video da passare al lettore creato in events.js
	ytplayer.playVideo();
}

function handleControls(){
	var a = $(".video_controls a");
	var t = $(this);
	$("a[title=play]").click(function(){	
		a.removeClass("opacity");
		t.addClass("opacity");
		ytplayer.playVideo();
		return false;
	});
	$("a[title=pause]").click(function(){
		a.removeClass("opacity");
		t.addClass("opacity");
		ytplayer.pauseVideo();
		return false;
	});
	$("a[title=unmute]").click(function(){
		a.removeClass("opacity");
		t.addClass("opacity");
		ytplayer.unMute();
		return false;
	});
	$("a[title=mute]").click(function(){
		a.removeClass("opacity");
		t.addClass("opacity");
		ytplayer.mute();
		return false;
	});
	
	$("#volume_slider_wrapper").slider({
		value: 75, //applico un valore fittizio
		min: 0,
		max: 100,
		slide: function(e){
			var volume = e.pageX - $(this).offset().left;//calcolo la posizione di partenza dello slider, poi la sottraggo al valore massimo dello slider in modo da limitare il range tra 0 e 100
			ytplayer.setVolume(volume);
		}
	});
	$("#progress_bar").slider({
		slide: function(e){
			var skipTo = e.pageX - $(this).offset().left,//calcolo la posizione a cui e lo slider 
				statusWidth = $(this).width(),//la dimensione della progress bar
				seekPosition = (skipTo / statusWidth),
				seekToPosition = Math.round(ytplayer.getDuration() * seekPosition);
			ytplayer.seekTo(seekToPosition, false);
		}
	});
}

secondsToTime = function(secs){
	minVar = Math.floor(secs.toFixed()/60).toFixed();  // The minutes
	secVar = (secs.toFixed() % 60).toFixed();
	if (minVar < 0) minVar = 0;
	if (secVar < 0) secVar = 0;
	if (minVar < 10) minVar = '0'+minVar;
	if (secVar < 10) secVar = '0'+secVar;
	return minVar+':'+secVar;
}

function updateTime(){
	$("#time").html(secondsToTime(ytplayer.getCurrentTime())+'<span> // </span>'+secondsToTime(ytplayer.getDuration()));//questa funzione scrive sia il minutaggio corrente sia la durata totale
}

function updateProgbar(){
	if(ytplayer.getCurrentTime() > 0 ){
		var videoPosition = (ytplayer.getCurrentTime() / ytplayer.getDuration()) * 100;
		$("#progress_bar a").css({left:videoPosition + '%'});
	}
}

function checkTextareaLenght(){
	$('textarea[maxlength]').keyup(function(){
		var _this = $(this),
			paragrafo = _this.siblings('.hidden'), // e' il p che contiene il numero di caratteri rimanenti
			max = parseInt(_this.attr('maxlength')), // numero massimo di caratteri consentito
			caratteri = _this.val().length; // numero di caratteri inseriti
		if(caratteri > max){
			_this.val(_this.val().substr(0, _this.attr('maxlength')));
		}
		paragrafo.html(''+stampaMessaggi('form','hai')+'' + (max - caratteri) + ''+stampaMessaggi('form','caratteri')+'').fadeIn(); //scrivo quanti caratteri rimangono a disposizione
		
		// nascondo il paragrafo alla perdita del focus della textarea
		_this.blur(function(){
			paragrafo.fadeOut();
		});
	});
}

/* function doMasonry(){
	$(".case_history_top").masonry(
		{
			itemSelector: ".box",
			columnWidth: 45
		}
	);
} */
