var ytplayer;
var alertTimerId;
var updateTimerId;
var pointerTimerId;

var infoImg=0;

var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
// Handle all the FSCommand messages in a Flash movie.
function player_DoFSCommand(command, args) {
	var playerObj = isInternetExplorer ? document.all.player : document.player;
	$('#ses').hide();
	$("#main").show();
	$('#fade_background').fadeOut(2500, function(){});
}
// Hook for Internet Explorer.
if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1) {
	document.write('<script language=\"VBScript\"\>\n');
	document.write('On Error Resume Next\n');
	document.write('Sub player_FSCommand(ByVal command, ByVal args)\n');
	document.write('	Call player_DoFSCommand(command, args)\n');
	document.write('End Sub\n');
	document.write('</script\>\n');
}


function onYouTubePlayerReady(playerId) {
      ytplayer = document.getElementById("myytplayer");
	  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
	  //ytplayer.setPlaybackQuality("hd720");
	  video_id = "6fhy_ZCsHzA";
	  ytplayer.loadVideoById(video_id,0,'large');
	  updateTimerId=setInterval(updateytplayerInfo, 250);
	  
	  //ytplayer.cueVideoById(video_id,0);
}

function onytplayerStateChange(newState)
{
	//console.log(newState);
	switch (newState)
	{
		case 0: //ended
			clearInterval(updateTimerId);
			$('#main').fadeOut(500, function(){$('#myytplayer').remove();});
			$('#fade_background').fadeIn(500, function () {
				$('body').css("background","url(Images/welbg_l.jpg) top left no-repeat #000");
				$(this).animate({width:"0%", left:"50%"},1000,function(){
					$('#top_bar, #bottom_bar').animate({backgroundColor: '#000'},1000);
					if(infoImg==0){
						$('<img/>',{
							id:'lochd',
							src:'Images/locandina_gen.jpg'
						}).prependTo('#infoContainer');
						//caro vecchio flag.. così non aggiungo di nuovo l'immagine
						//al container se qualcuno rivede il video
						infoImg++;
					}
					$('#info').fadeIn(500);
					window.scrollTo(0,0);
					$('#fade_background').fadeOut(500,function(){
						$('#occhio').animate({'right': '-242px'},{queue:false , duration:1000});
					});
				});
				
				
			});
			
			/*
			$('#videoContainer').fadeOut(function(){
				$('<img/>',{
					id:'lochd',
					src:'Images/locandina_head.jpg'
				}).appendTo('#info');
			});*/
		break;
	}
}

//timers
function updateytplayerInfo(){
	width = Math.round((ytplayer.getCurrentTime()/ytplayer.getDuration())*100);
	$('#elBar').css("width", width+"%");
	width = Math.round((ytplayer.getVideoBytesLoaded()/ytplayer.getVideoBytesTotal())*100);
	$('#ldBar').css("width", width+"%");
}

function mytimer()
{
	if(ytplayer.getPlayerState()!=1)
		return;
	
	$('#prgBar').fadeOut(500);
	$('#Skip').fadeOut(500);
	$('#Stop').fadeOut(500);		
	$('#Control').fadeOut(500, function() {
		if(ytplayer.getPlayerState()!=1){
			$('#Control').show();
			$('#prgBar').show();
			$('#Skip').show();
			$('#Stop').show();
		}
	});
}

function animatePointer()
{
	$('#hand').animate({'left': '40px'}, 300, function(){
		$('#hand img').animate({'width': '35px', 'height' : '37px'}, 100 , function(){
			$('#hand img').animate({'width': '37px', 'height' : '41px'}, 100 , function(){
			});
			$('#hand').delay(2000).animate({'left': '-40px'}, 500, function(){
				pointerTimerId=setTimeout(animatePointer, 5000);
			});
		});
	});
}


function Flick()
{
	$('.flicker').animate({'opacity': '0'}, 300, function(){
		$('.flicker').animate({'opacity': '1'}, 300, function(){
		pointerTimerId=setTimeout(Flick, 1000);
		});
	});
}

function setupVideo()
{
	$('#videoContainer').css({
		"position" :"relative",
		'z-index' : "0"
	});
	
	$('<div/>',{
		id:'ytapiplayer',
		text: 'You need Flash player 8+ and JavaScript enabled to view this video.',
		css:{
			width	: 780,
		    height	: 463,
			'z-index' : "0"
		}
	}).appendTo('#videoContainer');
	
	var params = {}; 
	
	params.allowScriptAccess= "always";
	//params.play = "true";
	//params.menu = "false";
	//params.quality = "best";
	params.wmode ="transparent";
	
    var atts = { id: "myytplayer" };
   
	
	swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&version=3&playerapiid=ytplayer", 
                       "ytapiplayer", "780", "463", "8", null, null, params, atts);

	//$('#myytplayer').css('z-index' , "-30");
	
	$('<div/>',{
		id:'Control',
		css:{
			position: "absolute",
			display : "none",
			width	: "120px",
		    height	: "120px",
			top		: "50%",
			left	: "50%",
			cursor	: "pointer",
			margin	: "-60px 0 0 -60px",
			'z-index'	: "1000",
		}
	}).appendTo('#videoContainer');
	
	$('<div/>',{
		id:'Skip',
		css:{
			position: "absolute",
			display : "none",
			width	: "50px",
		    height	: "47px",
			top		: "20px",
			right	: "20px",
			cursor	: "pointer",
			"background": "url('Images/itskip_l.png') no-repeat center center",
			'z-index'	: "1000",
		}
	}).appendTo('#videoContainer');
	
	$('<div/>',{
		id:'Stop',
		css:{
			position: "absolute",
			display : "none",
			width	: "50px",
		    height	: "47px",
			top		: "20px",
			right	: "90px",
			cursor	: "pointer",
			"background": "url('Images/itstop_l.png') no-repeat center center",
			'z-index'	: "1000",
		}
	}).appendTo('#videoContainer');
	
	$('<div/>',{
		id:'prgBar',
		css:{
			position: "absolute",
			display : "none",
			width	: "100%",
		    height	: "5px",/*
			top		: "50%",
			left	: "50%",*/
			bottom	: "0",
			cursor	: "pointer",/*
			margin	: "-60px 0 0 -60px",*/
			'z-index'	: "1000",
			'background' : '#400',
			'border' :'#999 solid 1px'
		}
	}).appendTo('#videoContainer');
	
	$('<div/>',{
		id:'ldBar',
		css:{
			position: "absolute",
			//display : "none",
			width	: "0%",
		    height	: "5px",
			top		: "0",
			left	: "0",
			cursor	: "pointer",/*
			margin	: "-60px 0 0 -60px",*/
			'z-index'	: "1000",
			'background' : '#800'
		}
	}).appendTo('#prgBar');
	
	$('<div/>',{
		id:'elBar',
		css:{
			position: "absolute",
			//display : "none",
			width	: "0%",
		    height	: "5px",
			top		: "0",
			left	: "0",
			cursor	: "pointer",/*
			margin	: "-60px 0 0 -60px",*/
			'z-index'	: "1000",
			'background' : '#F00'
		}
	}).appendTo('#prgBar');
	
	$('#videoContainer').mousemove(function(){
		try{
			clearTimeout (alertTimerId);
		}
		catch(e)
		{}
		
		$('#Control').fadeIn(500);
		$('#prgBar').fadeIn(500);
		$('#Skip').fadeIn(500);
		$('#Stop').fadeIn(500);
		switch(ytplayer.getPlayerState())
			{
				case 1:
					$('#Control').css("background", "url('Images/itpause.png') no-repeat center center");
					alertTimerId = setTimeout ( "mytimer()", 1000);
					break;
				
				case 2:
					$('#Control').css("background", "url('Images/itplay.png') no-repeat center center");
					break;
			}

	});

	$('#prgBar').click(function(e){
		ratio = (e.pageX-$(this).offset().left)/$(this).outerWidth();
		$("#elBar").width(Math.round(ratio*100)+'%');
		ytplayer.seekTo(Math.round(ytplayer.getDuration()*ratio), true);
	});
	
	$('#Skip').click(function(e){
		try{
			clearTimeout (alertTimerId);
		}
		catch(e)
		{}
		onytplayerStateChange(0);
		//ytplayer.seekTo(ytplayer.getDuration(), true);
	});
	
	$('#Stop').click(function(e){
		ytplayer.seekTo(0, true);
		ytplayer.stopVideo();
		$('#Control').css("background", "url('Images/itplay.png') no-repeat center center");
	});
	
	$('#Control').click(function(){
			try{
				clearTimeout (alertTimerId);
			}
			catch(e)
			{}
			
			switch(ytplayer.getPlayerState())
			{
				case 1:
					ytplayer.pauseVideo();
					$('#Control').css("background", "url('Images/itplay.png') no-repeat center center");
					break;
				
				case 2:
				case -1:
					ytplayer.playVideo();
					$('#Control').css("background", "url('Images/itpause.png') no-repeat center center").hide();//.delay(200).fadeOut(500);
					break;
			}
	});
};

//così aspetto che il documento sia caricato (ma non le immagini)

$(function() {

	
	//setupVideo();
	pointerTimerId=setTimeout(animatePointer, 1000);
	pointerTimerId=setTimeout(Flick, 1000);
	
	$('#occhio').hover(function(){
		$('#occhio').animate({'right': '0px'},{queue:false , duration:500});
		}, function(){
		$('#occhio').animate({'right': '-242px'},{queue:false , duration:500});
	});
	$('#infoBtn').click(function() {
		
		
			/*
			ql = ytplayer.getAvailableQualityLevels();
			for(i = 0 ; i< (ql.length - 1); i++)
				alert(ql[i]);
			
			alert(ytplayer.getPlaybackQuality());
			ytplayer.setPlaybackQuality("hd1080");
			return false;*/
			$('#clmPresent').hide();
			$('#clmSpettacoli').show();
			//window.scrollBy(0,250); // horizontal and vertical scroll increments
			window.location="#top";
			return false;
		});
		
		$('#backBtn').click(function() {
		
		
			$('#clmPresent').show();
			$('#clmSpettacoli').hide();
			
			//return false;
		});
	

	$("#contactform").validate({
			messages: {
				email: {
					required: "il campo email è obbligatorio",
					email: "inserire un indirizzo email valido"
				}
			}
	});
		
	$("#contactform").submit(function() {

			if($("#contactform").valid())
			{
				$("#after_submit").css("text-align","center").html('<img src="Images/loader.gif" /><br /><br />').show();
				$.post("contact.php", $(this).serialize(), function(data){
					var msg;
					if(data=="ok")
						msg="Grazie per il tuo messaggio, controlla la tua mail adesso, troverai il link dal quale scaricare il coupon sconto.<br /><br />";
					else
						msg="Purtroppo si è verificato un errore durante l'invio del messaggio, ti preghiamo di riprovare. Grazie.<br /><br />";
					$("#after_submit").css("text-align","justify").html(msg).show();
				});
			}
			
			return false;
	});
							
	/*
	$('#content').click(function() {
		tb_show("ONE MAN SHOW", "oltremare.html?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=350&width=700&modal=true", false)
	});*/
	
	$('#invite').click(function() {
		
		$('#invite').fadeOut(function(){
			/*
			$('#content').fadeOut(200,function(){
				$('#bottom_bar').animate({height:'50px'}, 500); 
				$('#bottom_bar').animate({opacity:'0.4'}, 500); 
			});*/
			
			$('#fade_background').fadeIn(function () {
				$(this).animate({width:"100%", left:"0%"},1000,function(){
					
					$('body').css("background","top left no-repeat #000"); //url(Images/welbg_dl2.jpg) 
					$('#top_bar, #bottom_bar').animate({backgroundColor: '#FFF'},1000);//.css("opacity", "0.4");
					if(infoImg==0){
						$('<img/>',{
							id:'lochd',
							src:'Images/locandina_gen.jpg'
						}).prependTo('#infoContainer');
						//caro vecchio flag.. così non aggiungo di nuovo l'immagine
						//al container se qualcuno rivede il video
						infoImg++;
					}
					$('#info').fadeIn(500);
					window.scrollTo(0,0);
					$('#fade_background').fadeOut(500,function(){
						$('#occhio').animate({'right': '-242px'},{queue:false , duration:1000});
												
					});
					/*$('#ses').show();/*.delay(17200).hide(function(){
						$("#main").show();
						$('#fade_background').fadeOut(2500, function(){});
					});*/
					
				
				});
			});	
		});	
	});	
			
	$('#replayBtn').click(function() {
		
		$('#videoContainer').html("");
		setupVideo();
		
		
		$('#info').fadeOut(function(){

			$('#fade_background').fadeIn(function () {
				$(this).animate({width:"100%", left:"0%"},1000,function(){
					
					$('body').css("background","top left no-repeat #000"); //url(Images/welbg_dl2.jpg) 

					$('#top_bar, #bottom_bar').animate({backgroundColor: '#FFF'},1000);//.css("opacity", "0.4");
					$('#occhio').animate({'right': '-335px'},{queue:false , duration:1000});
					$('#ses').show();
					/*
					$("#main").show();
					$('#fade_background').fadeOut(2500, function(){});
					*/
				});
			});	
		});	
	});
	

});



//così aspetto che anche le immagini siano caricate

$(window).load(function() {

	$('#invite').delay(500).fadeIn(2500);
	//tb_show("Chiarimento sulla campagna elettorale", "nncampagna_elettorale.html?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=700&width=700&modal=true", false)
	//$('#clickme').delay(4000).css('visibility','visible');
	
});

$(window).scroll(function (){

});

$(window).resize(function (){
});
