var ytplayer;
// Chromeless player has no controls.

// Update a particular HTML element with a new value
function updateHTML(elmId, value) {
	document.getElementById(elmId).innerHTML = value;
}

// This function is called when an error is thrown by the player
function onPlayerError(errorCode) {
	//alert("An error occured of type:" + errorCode);
}


// Load playlist if mature user
function callStandardPlaylist(data) {
	standardPlaylist = data;
	if (typeof(userMature)=="undefined") { showMyVideos(data) }
	else if (typeof(maturePlaylist)=="undefined") {showMyVideos(data) };
}


// Load playlist if not mature user
function callMatureplaylist(data) {
	maturePlaylist = data;
	document.getElementById("matureCheckboxContainer").style.visibility = "visible";
	document.getElementById("matureCheckboxContainer").style.display = "block";
	if (typeof(userMature)!="undefined") { 
		showMyVideos(data);
		document.getElementById("matureCheckbox").checked = "checked";
		}
}

// Load mature playlist if the check is checked

function loadMature (checkBox) {
	if (checkBox.checked == true ) {showMyVideos(maturePlaylist)}
	else { showMyVideos(standardPlaylist) };
	loadNewVideoUrl(videoUrlArray[0], 0, 0);
	
	// Re-set slider buttons
	// Hide right arrow if videolist don't overflow
	if (document.getElementById("videoList").actualPage >= document.getElementById("videoList").startPage) 
	{ document.getElementById("slidePrev").className = "darkSlider"; }
	else { document.getElementById("slidePrev").className = ""; }

	// Hide left arrow if videolist is at its start
	if (document.getElementById("videoList").pageMax <= document.getElementById("videoList").actualPage) 
	{ document.getElementById("slideProx").className = "darkSlider"; } 
	else { document.getElementById("slideProx").className = ""; } 
}


// This function is called when the player changes state, if it arrived at the end of the video, it load the next one in the playlist, if is the last, it restart from the beginning of the playlist
function onPlayerStateChange(newState) {
	//updateHTML("playerState", newState);
	if (newState == 0)
	{
		if ( ytplayer.videoNumber == ( videoUrlArray.length -1)) {nextVideo = 0}
		else {nextVideo = ytplayer.videoNumber +1 };
		loadNewVideoUrl(videoUrlArray[nextVideo], 0, nextVideo);
	}
	if (newState == 1)
	{
		getVideoQual();
	}
}

/* Refresh data function
----------------------------------------------------------*/

// Display information about the current state of the player and refresh the bars
function updatePlayerInfo() {
	// Also check that at least one function exists since when IE unloads the
	// page, it will destroy the SWF before clearing the interval.
	if(ytplayer && ytplayer.getDuration) {
		updateHTML("videoDuration", transformDuration(ytplayer.getDuration()));
		updateHTML("videoCurrentTime", transformDuration(ytplayer.getCurrentTime()));
		//updateHTML("volume", ytplayer.getVolume());
		if (document.getElementById("videoQuality").className != "quality" + ytplayer.getPlaybackQuality() ) 
		{	document.getElementById("videoQuality").className = "quality" + ytplayer.getPlaybackQuality(); 
		document.getElementById("videoQuality").innerHTML =   getVideoQualName (ytplayer.getPlaybackQuality()) ;
		
		} 
		//updateHTML("videoQuality", ytplayer.getPlaybackQuality());
		loadingBar();
		playedBar();
		volumeBar();
		// Change play/pause button
		if (ytplayer.getPlayerState() == 1 && document.getElementById("playButton").className != "pauseButton" ) 
		  { document.getElementById("playButton").className = "pauseButton" }
		else if(ytplayer.getPlayerState() != 1 && document.getElementById("playButton").className != "playButton")	
		  { document.getElementById("playButton").className = "playButton"}
			
		// Pause if another tab is selected
		if (document.getElementById("tabMenu")){
			
			var tabMenu = document.getElementById("tabMenu");
			var tabLabels = tabMenu.getElementsByTagName("span");
			if(tabLabels[3].className != "selected") ytplayer.pauseVideo();
			
			}
	  }
}

// Transform duration format into mm:ss

function transformDuration (time){
	if (time < 0) {return "0:00"}
	durationInSeconds = Math.floor(time);
	durationSeconds = Math.floor(durationInSeconds % 60);
	if (durationSeconds < 10) {durationSeconds= "0"+durationSeconds}
	durationMinutes = Math.floor((durationInSeconds/60) % 60);
	durationFormatted = durationMinutes  + ":" + durationSeconds;
	return (durationFormatted);
}





/* Command buttons
----------------------------------------------------------*/

// Play and pause the video
function playPauseVideo (){
		if (ytplayer.getPlayerState() == 1) {
			ytplayer.pauseVideo();
		}
		else {
			ytplayer.playVideo();	
		}
}

// Allow the user to set the volume from 0-100
function setVideoVolume(volume) {
  if(ytplayer){
		ytplayer.unMute();
		document.getElementById("muteVideoButton").className = "muteVideoButton";
		ytplayer.setVolume(volume);
	}
}

// Set the video player at the chosen time and start buffering from it 
function setVideo(time) {
	if (ytplayer) {
		ytplayer.seekTo(time, true);
		var startloadbyte = ytplayer.getVideoStartBytes();
		var loadingBarWidth = document.getElementById("loadingBar").offsetWidth;
		var totalDimension = ytplayer.getVideoBytesTotal();
		var startByteLoaded = (startloadbyte * 100 ) / totalDimension;
		var startingLoadedBar = startByteLoaded * ( loadingBarWidth / 100) ;
		document.getElementById("loadedBar").style.marginLeft = startingLoadedBar +"px";
	}
}

// Mute unmute video
function muteVideo(text) {
	if(ytplayer.isMuted()) {
		ytplayer.unMute();
		document.getElementById("muteVideoButton").className = "muteVideoButton";
	}
	else {
		ytplayer.mute();
		document.getElementById("muteVideoButton").className = "unMuteVideoButton";
	}
}

// this function load a video before or after the actual video in the player, using the value passed
function anotherVideo(distance) {
	wantedVideo = ytplayer.videoNumber + distance;
	if ( wantedVideo < 0 ) { wantedVideo = videoUrlArray.length - 1 }
	else if ( wantedVideo > videoUrlArray.length -1) { wantedVideo = 0 }
	loadNewVideoUrl(videoUrlArray[wantedVideo], 0, wantedVideo);
}

// Open a new window with a maximized video
function playVideoFull() {
	var linkFullVideo = videoUrlArray[ytplayer.videoNumber]+"&hd=1&autoplay=1&egm=0&rel=0&iv_load_policy=3" ;
	var width = screen.width;
	var height = screen.height;
	var attrib = 'width='+width+',height='+height+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no,resizable=no';
	ytplayer.pauseVideo();
	window.open(linkFullVideo,'FullScreen',attrib);
}

// Get the video quality list and put them in an ul
function getVideoQual () {
		var videoQualitiesArray = ytplayer.getAvailableQualityLevels();
		if ( videoQualitiesArray.length > 1) {
			var qualityHtml = [];
			for (var i = 0; i < videoQualitiesArray.length; i++)
			{
				var videoQualityName = getVideoQualName (videoQualitiesArray[i]);
				qualityHtml.push( '<li class=\"quality',videoQualitiesArray[i],'\" onclick=\'setVideoQual(\"',videoQualitiesArray[i],'\")\'>',videoQualityName,'</li>');
			}
			document.getElementById("videoQualityList").innerHTML = qualityHtml.join('');
		}
}

function getVideoQualName (qualValue) {
	var videoQualityName;
	if (qualValue == "medium") videoQualityName = "320p"
	else if (qualValue == "large") videoQualityName = "480p"
	else if (qualValue == "hd720") videoQualityName = "720p"
	else if (qualValue == "hd1080") videoQualityName = "1080p"
	return (videoQualityName);
}

function setVideoQual(quality) {
	  // set the selected quality if it is different from the actual quality
		if (ytplayer && quality != ytplayer.getPlaybackQuality()) {
		ytplayer.setPlaybackQuality(quality);
	}
}


/* This function is automatically called by the player once it loads 
----------------------------------------------------------*/

function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("ytPlayer");
	// This causes the updatePlayerInfo function to be called every 250ms to get fresh data from the player
	setInterval(updatePlayerInfo, 250);
	updatePlayerInfo();
	ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
	ytplayer.addEventListener("onError", "onPlayerError");
	//Load an initial video into the player
	loadNewVideoUrl(videoUrlArray[0], 0, 0);
	if (startingVolume != null) { 
	    if (startingVolume == 0) {muteVideo()}
	  else setVideoVolume(startingVolume); 
	}	
}

// The "main method".
function loadPlayer() {
	// Lets Flash from another domain call JavaScript
	var params = { allowScriptAccess: "always", wmode: "opaque" };
	// 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=ytPlayer","videoDiv", "540", "304", "8", null, null, params, atts);
}

// needed cunctions
function _run() {
	loadPlayer();
}

google.setOnLoadCallback(_run);


// load a new video and set the current video number
function loadNewVideoUrl(url, startSeconds,number) {
	if (ytplayer) {
		ytplayer.loadVideoByUrl(url, startSeconds);
		ytplayer.videoNumber = number;

		// Set the video name in the h2 of the video zone 
		document.getElementById("videoName").innerHTML = videoNamesArray[number].substr(0, 70);
		showHideCommands('show','videoName');
		setTimeout(function(){showHideCommands('hide','videoName')},5000);
		//setTimeout = (showHideCommands('hide','videoName'),500);	
		// Reset the loaded bar margin left
		 
			document.getElementById("loadedBar").style.marginLeft = 0 +"px";
			
			
			
			// Part for auto scrolling the playlist
			actualvid=number+1;
		//	alert(actualvid);
			//alert(document.getElementById('videoList').actualPage);
			//alert(videoUrlArray.length)
			if (actualvid == videoUrlArray.length) {
			
			var a=1;	
	
				
			}

			if (actualvid != document.getElementById('videoList').actualPage ) 
			{
				
				distance = document.getElementById('videoList').actualPage - actualvid;
			//	alert(distance)
				if (distance > 0)
				{
				  for (var i = 0 ; i < distance; i++) {
					setTimeout(function(){prev(126,12,'videoList')}, i*550);
					}
			  }
				if (distance < 0)
				{
				
				  for (var i = 0 ; i < -distance; i++) {
						setTimeout(function(){prox(126,12,'videoList');}, i*550);
					}
			  } 
			}
			var videoArr = document.getElementById('videoList');
			var videoLiTitle= videoArr.getElementsByTagName("li");
			for (loop = 0; loop<videoLiTitle.length; loop++) {
				videoLiTitle[loop].style.color ="";
				videoLiTitle[loop].childNodes[0].style.background ="";
			}
			videoLiTitle[number].style.color="#900";
			videoLiTitle[number].childNodes[0].style.background ="#CCC";
			
	}
}


/* This function creates an array of id of the videos of the playlist and an ul of the video thumbnails 
----------------------------------------------------------*/

function showMyVideos(data) {
  var feed = data.feed;
  var entries = feed.entry || [];
	
	// set the video container width
	var listwidth = 126 * (entries.length);
	
	// array degli url e dei titoli dei video, aperto all'esterno
	videoUrlArray = [];
	videoNamesArray	= [];
	videoDescriptionArray	= [];
	
  var html = ['<ul id="videoList" style="margin-left:0; width:', listwidth, 'px">'];
  for (var i = 0; i < entries.length; i++) {
    var entry = entries[i];
		if (entry.title.$t.length > 40){
      var title = entry.title.$t.substr(0, 37) +"...";
		}
		else {var title = entry.title.$t;}
    var thumbnailUrl = entry.media$group.media$thumbnail[0].url;
    var playerUrl = entry.media$group.media$content[0].url;
		
		// adds the video url to the video array
	  videoUrlArray.push(playerUrl);
		videoNamesArray.push(entry.title.$t);
		videoDescriptionArray.push(entry.media$group.media$description.$t);
		// Questo crea l'elenco dei li con le immagini della playlist 
    html.push('<li onclick="loadNewVideoUrl(\'', playerUrl, '\', 0, ', i, ' );"><span class="titlec">', title, '</span><img title=" ', entry.title.$t , '\ " src="',thumbnailUrl, '"/>', '</span></li>');
  }
  html.push('<br /></ul>');
  document.getElementById('videoPlaylist').innerHTML = html.join('');
	document.getElementById('videoList').pageMax = (entries.length -3);
  document.getElementById('videoList').startPage = 1;
  document.getElementById('videoList').actualPage = 1;
	document.getElementById('videoList').steps = calculateSteps(126) ;
	
}

/* Get site search link 
----------------------------------------------------------*/

function getProductDescription() {
	var desc = videoDescriptionArray[ytplayer.videoNumber];
	alert(desc);	
}

function productLink() {
	var desc = videoDescriptionArray[ytplayer.videoNumber];
	var geturl =  desc.split("\n");
	var productUrl = geturl[0]
	window.location = productUrl;
}

/* Bars settings 
----------------------------------------------------------*/

/* Set loading bar dimension */
function loadingBar() {
	var loadingBarWidth = document.getElementById("loadingBar").offsetWidth;
	var totalDimension = ytplayer.getVideoBytesTotal();
	var actualDownloaded = ytplayer.getVideoBytesLoaded();
	var percentualLoaded = (actualDownloaded * 100 ) / totalDimension;
	var dimensionLoadedBar = percentualLoaded * ( loadingBarWidth / 100) ;
	document.getElementById("loadedBar").style.width = dimensionLoadedBar + "px";
}

/* Set played bar dimension e cursor position*/
function playedBar() {
	var timeBarWidth = document.getElementById("timeBar").offsetWidth;
	var duration = ytplayer.getDuration();
	var currentTime = ytplayer.getCurrentTime();
	var percentualPlayed = (currentTime * 100 ) / duration;
	var dimensionPlayedBar = percentualPlayed * (timeBarWidth / 100) ;
	document.getElementById("playedBar").style.width = dimensionPlayedBar + "px";
	
	if (document.getElementById("playerCursor").setted != 1) {document.getElementById("playerCursor").style.marginLeft = dimensionPlayedBar + "px"; }
}

/* Set volume cursor position */
function volumeBar() {
	var volumeBarHeight = document.getElementById("volumeBar").offsetHeight;
	var volume = ytplayer.getVolume();
	volumeCursorPos = volumeBarHeight - ((volume * volumeBarHeight) / 100);
	if (document.getElementById("volumeCursor").setted != 1) {document.getElementById("volumeCursor").style.marginTop = volumeCursorPos + "px" }
}

// Sliders functions
/* Start video when the cursor is dropped */
function setVideoAtCursor(event,obj) {
	var cursorPos = MsePos(event,obj);
	var sliderBarWidth = document.getElementById("cursorBar").offsetWidth;
	var duration = ytplayer.getDuration();
	var chosenTime = (cursorPos * duration) / sliderBarWidth;
	setVideo(chosenTime);
	document.getElementById("playerCursor").setted = 0;	
}

/* Set volume when cursor is dropped */
function setVolumeAtCursor(event,obj) {
	var cursorPos = MseYPos(event,obj);
	var volumeBarHeight = document.getElementById("volumeBar").offsetHeight;
	var chosenVolume = parseInt((cursorPos *100) / volumeBarHeight );
	setVideoVolume(100 - chosenVolume);
	document.getElementById("volumeCursor").setted = 0;
	document.getElementById("volumeCursor").movedOut = 0;
}

/* Set cursor X position  */
function setCursorPosition (event,obj,cursorID){
	/* set the cursor as clicked */
	document.getElementById(cursorID).setted = 1;
	
	/* calculate the position of the cursor */
	var cursorPos = MsePos(event,obj) ;
	
	/* set the cursor position */
	document.getElementById(cursorID).style.marginLeft = cursorPos + "px";	
}

/* Move cursor X */
function moveCursor (event,obj,cursorID){
	/* if the cursor is clicked */
  if ( document.getElementById(cursorID).setted == 1 )
	   {
			 /* Set the cursor position */
	     var cursorPos = MsePos(event,obj) ;
			 document.getElementById(cursorID).style.marginLeft = cursorPos + "px";	
		 }
}

/* Set cursor Y position  */
function setCursorYPosition (event,obj,cursorID){
	/* set the cursor as clicked */
	document.getElementById(cursorID).setted = 1;
	
	/* calculate the position of the cursor */
	var cursorPos = MseYPos(event,obj) ;
	
	/* set the cursor position */
	document.getElementById(cursorID).style.marginTop = cursorPos + "px";	
}

/* Move cursor Y */
function moveYCursor (event,obj,cursorID){
	/* if the cursor is clicked */
  if ( document.getElementById(cursorID).setted == 1 )
	   {
			 /* Set the cursor position */
	     var cursorPos = MseYPos(event,obj) ;
			 document.getElementById(cursorID).style.marginTop = cursorPos + "px";	
		 }
}

function moveCursorOut (event,obj,cursorID) {
if ( document.getElementById(cursorID).setted == 1 ) 
	{
		document.getElementById(cursorID).movedOut = 1;	
	}
}


function moveCursorIn (event,obj,cursorID){
	/* if the cursor is clicked */
  if ( document.getElementById(cursorID).movedOut == 1 )
	   {
			 document.getElementById(cursorID).movedOut == 0;
		 }
}


function showHideVolume(wanted,idToShow) {
	if (wanted == "show") {document.getElementById(idToShow).style.visibility = "visible";}
	else if ( document.getElementById("volumeCursor").movedOut != 1){document.getElementById(idToShow).style.visibility = "hidden";}
}


/* Functions to get mouse position */
function zxcMse(event){
if(!event) var event=window.event;
if (document.all){ return [event.clientX+zxcDocS()[0],event.clientY+zxcDocS()[1]]; }
return [event.pageX,event.pageY];
}

function zxcDocS(){
if (!document.body.scrollTop){ return [document.documentElement.scrollLeft,document.documentElement.scrollTop]; }
return [document.body.scrollLeft,document.body.scrollTop];
}

function zxcPos(zxcobj){
zxclft=zxcobj.offsetLeft;
zxctop=zxcobj.offsetTop;
while(zxcobj.offsetParent!=null){
zxcpar=zxcobj.offsetParent;
zxclft+=zxcpar.offsetLeft;
zxctop+=zxcpar.offsetTop;
zxcobj=zxcpar;
}
return [zxclft,zxctop];
}

// Return the relative x position
function MsePos(event,obj){
xPosition=zxcMse(event)[0]-zxcPos(obj)[0]
return (xPosition)
}

// Return the relative y position
function MseYPos(event,obj){
yPosition=zxcMse(event)[1]-zxcPos(obj)[1]
return (yPosition)
}





// Slides the gallery left and right
//------------------------------------------------------------------------

function calculateSteps(displacement) {
		 var actualPosition =  0;
		 var finalPosition = actualPosition + displacement;
		 var tempPosition = actualPosition;
		 var intermediatePositions = [];
		 var jumps = 0;
	 
		 	while (tempPosition < finalPosition) {
				var difference = Math.ceil((finalPosition-tempPosition)/8);	
				intermediatePositions[jumps] = difference;
				tempPosition = tempPosition + intermediatePositions[jumps];
				jumps++;
			}
			return intermediatePositions;	
}

// Slide to left the gallery
function prox(howmuch,time,slidabile) {
	 var playlist = document.getElementById(slidabile);

	 // If the actual page is less than the max page
	 if (playlist.actualPage < playlist.pageMax)
	 {
		 //deactivate button functionality while sliding
		 document.getElementById("slideProx").oldCl = document.getElementById("slideProx").onclick;
	   document.getElementById("slideProx").onclick = null;
		 
		 // Show the slide to prev arrow
		 document.getElementById("slidePrev").className = "";
		 
		 // Set the new page value
		 playlist.actualPage = playlist.actualPage +1;
		 
		 // Call the slide function
		 jumps = playlist.steps.length;
		 var frame = 0;
		 steps=0;
		 for( jumps ; jumps > 0; jumps--)
		 {
			 	timer = setTimeout(slideLeft,time*frame);
				frame++;
		 }
 
	   // If the actual page is the last disable the slideProx button
	   if (playlist.actualPage == playlist.pageMax) { document.getElementById("slideProx").className = "darkSlider"; } 
	 }
} 


function slideLeft() {
	var playlistToSlide = document.getElementById("videoList");
	var nextPosition = Math.abs(parseInt(playlistToSlide.style.marginLeft)) + Math.abs(parseInt(playlistToSlide.steps[steps]));
	playlistToSlide.style.marginLeft = -nextPosition + "px"; 
	
	// If i am at the end of the animation i reactivate the button
	if ( steps == playlistToSlide.steps.length -1)
	{
		document.getElementById("slideProx").onclick = document.getElementById("slideProx").oldCl;
	}
	steps++;
} 


// Slida to right the gallery
function prev(howmuch,time,slidabile) {
	 var playlist = document.getElementById(slidabile);

	 // If the actual page is less than the max page
	 if (playlist.actualPage > playlist.startPage)
	 {
		 //deactivate button functionality while sliding
	   document.getElementById("slidePrev").oldCl = document.getElementById("slidePrev").onclick;
	   document.getElementById("slidePrev").onclick = null;
		 
		 // Show the slide to prev arrow
		 document.getElementById("slideProx").className = "";

		 // Set the new page value
		 playlist.actualPage = playlist.actualPage -1;
		  
		 // Call the slide function
		 jumps = playlist.steps.length;
		 var frame = 0;
		 steps=0;
		 for( jumps ; jumps > 0; jumps--)
		 {
			 	timer = setTimeout(slideRight,time*frame);
				frame++;
		 }
 
	   // If the actual page is the last disable the slideProx button
	   if (playlist.actualPage == playlist.startPage) {  document.getElementById("slidePrev").className = "darkSlider"; } 
	 }
} 

// Slide to left function
function slideRight() {
	var playlistToSlide = document.getElementById("videoList");
	var nextPosition = Math.abs(parseInt(playlistToSlide.style.marginLeft)) - Math.abs(parseInt(playlistToSlide.steps[steps]));
	playlistToSlide.style.marginLeft = -nextPosition + "px";  
	
	  // If i am at the end of the animation i reactivate the button
		if ( steps == playlistToSlide.steps.length -1)
	{
		document.getElementById("slidePrev").onclick = document.getElementById("slidePrev").oldCl;
	}
	steps++;
}

// Hide and Show player commands

function showHideCommands(wanted,idToShow) {
	if (wanted == "show") {document.getElementById(idToShow).style.visibility = "visible";}
	else {document.getElementById(idToShow).style.visibility = "hidden";}
}