// Get Video-ID
function getVariables() {
	nowPlaying = $('.videoPlaceholder').attr('name');
	placeholdPosition = $('.videoPlaceholder').offset();
	nowRel = $('.videoPlaceholder').attr('rel');
	$('<div class="videoContainer" />')
	     .appendTo('body')
	     .attr({'name':nowPlaying,'rel':nowRel})
	     .css('position','absolute')
	     .offset(placeholdPosition);
  if ($.browser.msie && $.browser.version < 9.0){
    var playerWidth = $('.videoPlaceholder').width();
    var playerHeight = $('.videoPlaceholder').height();
    $('<object width="' + playerWidth + '" height="' + playerHeight + '"><param name="movie" value="http://www.youtube.com/v/' + nowPlaying + '?fs=1&amp;hl=nl_NL&amp;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + nowPlaying + '?fs=1&amp;hl=nl_NL&amp;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + playerWidth + '" height="' + playerHeight + '"></embed></object>').appendTo('.videoPlaceholder');
    $('a.playYtVideo').click(function(){
      var nextVideoId = $(this).attr('href');
      $('.videoPlaceholder').empty().append('<object width="' + playerWidth + '" height="' + playerHeight + '"><param name="movie" value="http://www.youtube.com/v/' + nextVideoId + '?fs=1&amp;hl=nl_NL&amp;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + nextVideoId + '?fs=1&amp;hl=nl_NL&amp;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + playerWidth + '" height="' + playerHeight + '"></embed></object>');
      return false;
    });
    return false;
  }
	object = $('.videoContainer');
	playerVolume = 100;
	relatedVideosTimer = 'empty';
	$(document).bind('mousemove', function (e) {
		var mouseX = e.pageX;
		mouseXpos = mouseX;
	});
}

// This function is called when the player changes state
function onPlayerStateChange(newState) {
	if (newState == 1) { // play
		$('.controlPlay').addClass('controlPaused').attr('title', 'Pauze');
		toggleVideoInfo('up');
		videoQuality();
	}
	else if (newState == 2) { // pauze
		$('.controlPlay').removeClass('controlPaused').attr('title', 'Play');
		toggleVideoInfo('down');
	}
	else if (newState === 0) { // end
		$('.controlPlay').removeClass('controlPaused').attr('title', 'Play');
		videoEnd();
	}
}

function updateLoaded() {
	if (ytplayer.getVideoBytesLoaded() > -1) {
		var loadedAmount = (ytplayer.getVideoBytesLoaded() / ytplayer.getVideoBytesTotal()) * 100;
		var startAmount = (ytplayer.getVideoStartBytes() / ytplayer.getVideoBytesTotal()) * 100;
		$('.playerLoaded').css({
			'width': loadedAmount + '%',
			'left': startAmount + '%'
		});
	}
}

function updatePosition() {
	if (ytplayer.getCurrentTime() > 0) {
		var videoPosition = (ytplayer.getCurrentTime() / ytplayer.getDuration()) * 100;
		$('.playerBar').css('left', videoPosition + '%');
	}
}

function updateVideoInfo(val, title) {
	var youtubeId = object.attr('name');
	$.getJSON("http://gdata.youtube.com/feeds/api/videos/" + youtubeId + "?v=2&alt=json-in-script&callback=?", function (data) {
		var videoTitle = data.entry.title.$t;
		var videoUploader = data.entry.author[0].name.$t;
		var videoViews = data.entry.yt$statistics.viewCount;
		var content = '<span class="videoTitle">Video: <b>' + videoTitle + '</b></span>';
		var content = content + '<span class="videoUploader">By: <a href="http://www.youtube.com/' + videoUploader + '" target="_blank">' + videoUploader + '</a></span>';
		var content = content + '<span class="videoViews"><b>' + videoViews + '</b><br />views</span>';
		$('.videoInfoInner').html('' + content + '');
		nowPlaying = youtubeId;
		$('a.controlWoy').attr('href', ytplayer.getVideoUrl());
	});
}

function playTime(val) {
	ytplayer.seekTo(val, true);
	if (ytplayer.getPlayerState() != 1) {
		ytplayer.playVideo();
	}
}

function switchTimeDisplay() {
	$('#playerTime').toggleClass('remaining');
}

function togglePlay() {
	if (ytplayer.getPlayerState() != 1) {
		ytplayer.playVideo();
	}
	else {
		ytplayer.pauseVideo();
	}
}

function toggleMute() {
	if (ytplayer.isMuted()) {
		ytplayer.unMute();
		$('.controlMute').removeClass('controlMuted').attr('title', 'Mute');
		$("#volumeSlider").slider("option", "value", playerVolume);
	}
	else {
		playerVolume = ytplayer.getVolume();
		ytplayer.mute();
		$('.controlMute').addClass('controlMuted').attr('title', 'Unmute');
		$("#volumeSlider").slider("option", "value", 0);
	}
}

function setVideoVolume(val) {
	if (ytplayer.isMuted()) {
		toggleMute();
	}
	if (val != null) {
		var volume = val;
		$("#volumeSlider").slider("option", "value", val);
	} else {
		var volume = $("#volumeSlider").slider("option", "value");
	}
	ytplayer.setVolume(volume);
}

function seekTime() {
	var offset = $('.playerProgress').offset();
	var clickX = mouseXpos - offset.left;
	var progressBarWidth = $('.playerProgress').width();
	var clickRatio = progressBarWidth / clickX;
	var newTime = (ytplayer.getDuration() / clickRatio) - 2; //Displayfix
	playTime(newTime);
}

function roundTime(val) {
	if (ytplayer.getCurrentTime() < 0) {
		return ('0:00');
	}
	else {
		var secVar0 = Math.floor(val);
		var minVar = Math.floor(secVar0 / 60);
		var secVar1 = secVar0 % 60;
		if (secVar1 < '10') {
			var secVar = '0' + secVar1;
		}
		else if (secVar1 >= '10') {
			var secVar = secVar1;
		}

		return (minVar + ':' + secVar);
	}
}

function displayTime() {
	var currentTime = roundTime(ytplayer.getCurrentTime());
	var totalTime = roundTime(ytplayer.getDuration());
	var remainingTime1 = ytplayer.getDuration() - ytplayer.getCurrentTime();
	var remainingTime = roundTime(remainingTime1);
	if ($('#playerTime').hasClass('remaining')) {
		return ('-' + remainingTime + ' / ' + totalTime);
	}
	else {
		return (currentTime + ' / ' + totalTime);
	}
}

function videoQuality(val) {
	if (val == null) {
		$('ul#playerQuality').empty().append('<li onclick="videoQuality(\'click\')">' + ytplayer.getPlaybackQuality() + '</li>');
	}
	else if (val == 'click') {
		var availableQualities = ytplayer.getAvailableQualityLevels();
		var qualityList = '';
		for (i in availableQualities) {
			if (availableQualities[i] != 'undefined') {
				if (availableQualities[i] == ytplayer.getPlaybackQuality()) {
					var qualityList = qualityList + '<li class="currentQuality">' + availableQualities[i] + '</li>';
				}
				else {
					var qualityList = qualityList + '<li onclick="ytplayer.setPlaybackQuality(\'' + availableQualities[i] + '\');">' + availableQualities[i] + '</li>';
				}
			}
		}
		$('ul#playerQuality').fadeOut('normal', function () {
			$(this).empty().append(qualityList).fadeIn().addClass('showQuality');
		});
	}
}

function updatePlayerInfo() {
	if(ytplayer && ytplayer.getDuration){
		$('#playerTime').html(displayTime());
		updateLoaded();
		updatePosition();
	}
}

function toggleVideoInfo(val) {
	var videoInfo = $('.videoInfo');
	var topValue = videoInfo.css('top');
	var heightValue = videoInfo.css('height');
	if (topValue == '0px' || val == 'up') {
		videoInfo.animate({
			'top': '-' + heightValue
		}, 500);
	}
	else if (topValue == '-' + heightValue || val == 'down') {
		videoInfo.animate({
			'top': '0'
		}, 500);
	}
}

function toggleVideoControls(val, delay) {
	var controlsHeight = $('.videoControls').height() - 5; // Show a little progressbar
	if (delay == null) {
		var delay = 0;
	}
	if (val == 'show') {
		$('.videoControls').show().stop(true, true).delay(delay).animate({
			'bottom': '0px'
		}, 500);
	}
	else if (val == 'up') {
		$('.videoControls').stop(true, true).delay(delay).animate({
			'bottom': '0px'
		}, 500);
	}
	else if (val == 'down' || val == 'hide') {
		$('.videoControls').stop(true, true).delay(delay).animate({
			'bottom': '-' + controlsHeight
		}, 500);
		if (val == 'hide') {
			$('.videoControls').hide();
		}
	}
}

function toggleSize() {
  if ($('.videoOverlay').length) {
    var originals = object.attr('originals');
    var originalsSplit = originals.split(",");
    var playerWidth = object.width();
    if ($.browser.msie) {
      $('.videoOverlay').remove();
    }
    else {
      $('.videoOverlay').fadeOut(function () {
        $(this).remove();
      });
    }
    if($('.videoEnd').is(':visible') && playerWidth > 1150){
      $('.videoEnd').addClass('transition').fadeOut();
    }
    $('.videoPlayer,object').css({
      width: originalsSplit[0],
      height: originalsSplit[1]
    });
    $('.videoContainer').css({
      top: originalsSplit[3] + 'px',
      left: originalsSplit[2] + 'px',
      margin: 0
    });
    object.removeClass('ytplayerFullscreen');
    if(playerWidth > 1150 && $('.videoEnd').hasClass('transition')){
        videoEnd();
        $('.videoEnd').removeClass('transition');
    }
  } else {
      var offset = object.offset();
      var windowHeight = $(window).height();
      var windowWidth = $(window).width();
      var image_width = object.width();
      var image_height = object.height();
      var heightRatio = image_height / windowHeight;
      var widthRatio = image_width / windowWidth;
      var newHeight = image_height / widthRatio;
      var newWidth = image_width / heightRatio;
      object.attr('originals',image_width + ',' + image_height + ',' + offset.left + ',' + offset.top);
      object.addClass('ytplayerFullscreen');
      if ($.browser.msie) {
        $('<div class="videoOverlay" />').appendTo('body').css({opacity: '1'});
      }
      else {
        $('<div class="videoOverlay" />').appendTo('body').animate({opacity: '1'}, 800);
      }
      if (heightRatio > widthRatio) {
        $('.videoPlayer,object').css({
          width: newWidth,
          height: windowHeight
        });
        $('.videoContainer').css({
          top:'0px',
          left: (windowWidth-newWidth)/2,
          margin: 0
        });
      } else {
        $('.videoPlayer,object').css({
          width: windowWidth,
          height: newHeight
        });
        $('.videoContainer').css({
          top: (windowHeight-newHeight)/2,
          left: '0px',
          margin: 0
        });
      }
    }
}

function convers8Share() {
	videoEnd();
}

function socialShare(val){
	var videolink = ytplayer.getVideoUrl();
	var videotitle = $('.videoTitle b').text();
	var sharetext = 'deze video zag ik net';
	if(val=="load"){
		var shareContent = '<span class="shareTitle">Deel deze video op:</span>';
		var shareContent = shareContent + '<a href="javascript:void(0);" onclick="socialShare(\'facebook\');" class="share_Facebook" title="Facebook"></a>';
		var shareContent = shareContent + '<a href="javascript:void(0);" onclick="socialShare(\'twitter\');" class="share_Twitter" title="Twitter"></a>';
		var shareContent = shareContent + '<a href="javascript:void(0);" onclick="socialShare(\'hyves\');" class="share_Hyves" title="Hyves"></a>';
		var shareContent = shareContent + '<a href="javascript:void(0);" onclick="socialShare(\'buzz\');" class="share_Buzz" title="Google Buzz"></a>';
		var shareContent = shareContent + '<br style="clear:both"/><a href="javascript:void(0);" onclick="socialShare(\'close\');" class="share_close">&times; Sluiten</a>';
		$('.videoShare').html('' + shareContent + '').fadeIn();
	} else if(val=='close'){
		$('.videoShare').fadeOut();
	} else {
		if(val == 'facebook' || val == 'Facebook') {
	        var url = 'http://www.facebook.com/sharer.php?u=' + videolink;
	    } else if(val == 'twitter' || val == 'Twitter') {
	        var url = 'http://twitter.com/share?url=' + videolink + '&text=' + sharetext + ' ' + videotitle;
	    } else if(val == 'hyves' || val == 'Hyves') {
	        var url = 'http://www.hyves-share.nl/button/tip/?tipcategoryid=3&rating=5&title=' + videotitle + '&body=' + sharetext + ' ' + videolink;
	    } else if(val == 'buzz' || val == 'Buzz') {
	        var url = 'http://www.google.com/buzz/post?message=' + sharetext + ' ' + videolink;
	    }
	    popUp(url);
	    socialShare('close');
    }
}

function popUp(url) {
    	window.open(url,'','toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=400,left=400,top=150');
}
	
function relatedVideos() {
	var related = object.attr('rel');
	var relatedSplit = related.split(",");
	var playerWidth = object.width();
  if(playerWidth < 1150){
  	var relatedVideos = '<div class="relatedVideos small">';
  	for(i in relatedSplit){
      if(i<3){
  		  var relatedVideos = relatedVideos + '<div onclick="playRelated(\'' + relatedSplit[i] + '\',' + i + ');" rel="' + relatedSplit[i] + '" class="relatedVideo img' + (i*1+2) + '"><img src="http://img.youtube.com/vi/' + relatedSplit[i] + '/hqdefault.jpg" /><span class="info"><span class="title" /><span class="views" /></span><span class="reflection" /></div>';
      }
    }
  } else {
    var relatedVideos = '<div class="relatedVideos">';
    for(i in relatedSplit){
      if(i<5){
        var relatedVideos = relatedVideos + '<div onclick="playRelated(\'' + relatedSplit[i] + '\',' + i + ');" rel="' + relatedSplit[i] + '" class="relatedVideo img' + (i*1+1) + '"><img src="http://img.youtube.com/vi/' + relatedSplit[i] + '/hqdefault.jpg" /><span class="info"><span class="title" /><span class="views" /></span><span class="reflection" /></div>';
      }
    }
  }
  
  var appendEndButtons = '<div class="buttons"><a href="javascript:void(0);" onclick="playAgain();" class="button" title="Bekijk opnieuw">Bekijk opnieuw</a>';
  var appendEndButtons = appendEndButtons + '<a href="javascript:void(0);" onclick="convers8Share();" class="button" title="Deel deze video">Deel deze video</a>';
  if(object.hasClass('ytplayerFullscreen')){
    var appendEndButtons = appendEndButtons + '<a onclick="toggleSize();" class="button" title="Exit Fullscreen">Exit Fullscreen</a>';
  }
  var relatedVideos = relatedVideos + appendEndButtons + '</div>';
	$('.videoEnd').html('' + relatedVideos + '');
	if(playerWidth < 1150){
  	$.getJSON("http://gdata.youtube.com/feeds/api/videos/" + relatedSplit[0] + "?v=2&alt=json&callback=?", function(data) {
          $('.img2 .title').text(data.entry.title.$t);
          $('.img2 .views').text(data.entry.yt$statistics.viewCount + ' views');
    });
    $.getJSON("http://gdata.youtube.com/feeds/api/videos/" + relatedSplit[1] + "?v=2&alt=json&callback=?", function(data) {
          $('.img3 .title').text(data.entry.title.$t);
          $('.img3 .views').text(data.entry.yt$statistics.viewCount + ' views');
    });
    $.getJSON("http://gdata.youtube.com/feeds/api/videos/" + relatedSplit[2] + "?v=2&alt=json&callback=?", function(data) {
          $('.img4 .title').text(data.entry.title.$t);
          $('.img4 .views').text(data.entry.yt$statistics.viewCount + ' views');
    });
  } else {
    $.getJSON("http://gdata.youtube.com/feeds/api/videos/" + relatedSplit[0] + "?v=2&alt=json&callback=?", function(data) {
          $('.img1 .title').text(data.entry.title.$t);
          $('.img1 .views').text(data.entry.yt$statistics.viewCount + ' views');
    });
    $.getJSON("http://gdata.youtube.com/feeds/api/videos/" + relatedSplit[1] + "?v=2&alt=json&callback=?", function(data) {
          $('.img2 .title').text(data.entry.title.$t);
          $('.img2 .views').text(data.entry.yt$statistics.viewCount + ' views');
    });
    $.getJSON("http://gdata.youtube.com/feeds/api/videos/" + relatedSplit[2] + "?v=2&alt=json&callback=?", function(data) {
          $('.img3 .title').text(data.entry.title.$t);
          $('.img3 .views').text(data.entry.yt$statistics.viewCount + ' views');
    });
    $.getJSON("http://gdata.youtube.com/feeds/api/videos/" + relatedSplit[3] + "?v=2&alt=json&callback=?", function(data) {
          $('.img4 .title').text(data.entry.title.$t);
          $('.img4 .views').text(data.entry.yt$statistics.viewCount + ' views');
    });
    $.getJSON("http://gdata.youtube.com/feeds/api/videos/" + relatedSplit[4] + "?v=2&alt=json&callback=?", function(data) {
          $('.img5 .title').text(data.entry.title.$t);
          $('.img5 .views').text(data.entry.yt$statistics.viewCount + ' views');
    }); 
  }
}

function videoEnd() {
	toggleVideoControls('hide');
	toggleVideoInfo('up');
	ytplayer.stopVideo();
	relatedVideos();
	$('.videoEnd').fadeIn();
}

function playAgain() {
	$('.videoEnd').fadeOut();
	toggleVideoControls('show', 1000);
	playTime(0);
}

function playRelated(val, number) {
	var update = object.attr('rel');
	var updateSplit = update.split(",");
	updateSplit[number] = nowPlaying;
	for (i in updateSplit) {
		if (i == 0) {
			var newRel = updateSplit[i];
		} else {
			var newRel = newRel + ',' + updateSplit[i];
		}
	}
	$('.videoEnd').fadeOut();
	toggleVideoControls('show', 1000);
	ytplayer.loadVideoById(val); // load next video
	object.attr({
		name: val,
		rel: newRel
	}); // set new name & rel
	updateVideoInfo();
}

// Keyboard shortcuts
document.onkeydown = function (e) {
	if (e == null) {
		keycode = event.keyCode;
	}
	else {
		keycode = e.which;
	}
	if (keycode == 27 && $('.videoOverlay').length) { // close fullscreen by pressing ESC
		toggleSize();
	}
	else if (keycode == 32) { // togglePlay with spacebar
		togglePlay();
	}
	else if (keycode == 179) { // togglePlay with Global Media Keys
		togglePlay();
	}
};

function loadPlayer(val) {
	getVariables();
  if ($.browser.msie && $.browser.version < 9.0){
     return false;
  }
	addElementsToDom();
	var playerWidth = $('.videoPlaceholder').width();
	var playerHeight = $('.videoPlaceholder').height();
	var params = {
		allowScriptAccess: "always",
		wmode: "transparent"
	};
	var atts = {
		id: "youtubeplayer"
	};
	// All of the magic handled by SWFObject
	swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&version=3&playerapiid=youtubeplayer","videoDiv", playerWidth, playerHeight, "8", null, null, params, atts);
}

function _run() {
	loadPlayer();
}

google.setOnLoadCallback(_run);

// This function is automatically called by the player once it loads
function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("youtubeplayer");
	// This causes the updatePlayerInfo function to be called every 300ms
	setInterval(updatePlayerInfo, 300);
	ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
	// Load an initial video into the player
	ytplayer.cueVideoById(nowPlaying);
	ytplayer.setVolume(100);
	updateVideoInfo();
}

// Insert Elements into DOM
function addElementsToDom() {
	$('<div class="videoPlayer"><div id="videoDiv" /></div>').appendTo('.videoContainer');
	var appendPlayer = '<div class="videoControls"><div class="videoControlsInner" /></div>';
	var appendPlayer = appendPlayer + '<div class="videoInfo"><div class="videoInfoInner" /><span class="videoInfoLabel" onclick="toggleVideoInfo();">info</span></div>';
	var appendPlayer = appendPlayer + '<div class="videoEnd" />';
	var appendPlayer = appendPlayer + '<div class="videoShare" />';
	$('.videoPlayer').append('' + appendPlayer + '');

	var appendControls = '<span class="playerProgress" onclick="seekTime();"><span class="playerLoaded" /><span class="playerBar" /></span>';
	var appendControls = appendControls + '<a href="javascript:void(0);" onclick="togglePlay();" class="controlPlay" title="Afspelen" />';
	var appendControls = appendControls + '<span class="volumeControls"><a href="javascript:void(0);" onclick="toggleMute();" class="controlMute" title="Mute" /><div id="volumeSlider" /></span>';
	var appendControls = appendControls + '<span id="playerTime" onclick="switchTimeDisplay();">0:00 / 0:00</span>';
	var appendControls = appendControls + '<ul id="playerQuality" title="Change Quality" />';
	// var appendControls = appendControls + '<a href="javascript:void(0);" onclick="convers8Share();" class="controlConvers8" title="Deel deze video"/>';
	var appendControls = appendControls + '<a href="javascript:void(0);" onclick="socialShare(\'load\');" class="controlDeel" title="Deel deze video"/>';
	var appendControls = appendControls + '<a href="javascript:void(0);" onclick="toggleSize();" class="controlFullscreen" title="Wissel Playergrootte"/>';
	var appendControls = appendControls + '<a href="javascript:void(0);" class="controlWoy" title="Watch on Youtube" target="_blank"/>';
	$('.videoControlsInner').append('' + appendControls + '');

	$('a.controlMute').mouseover(function () {
		$('.volumeControls').stop(true, true).animate({
			width: '120px'
		}, 400);
	});
	$('.videoControls').mouseleave(function () {
		$('.volumeControls').stop(true, true).delay(1000).animate({
			width: '25px'
		}, 400);
	});
	$('.playerBar').draggable({
		axis: "x",
		stop: function (event, ui) {
			seekTime();
		}
	});

	$("#volumeSlider").slider({
		range: "min",
		min: 0,
		max: 100,
		value: 100,
		slide: function (event, ui) {
			setVideoVolume();
		}
	});

	$('.videoPlayer').hover(
		function () {
			toggleVideoControls('up');
		}, function () {
			toggleVideoControls('down', 1000);
		});
		
		$('a.playYtVideo').click(function(){
		  var nextVideoId = $(this).attr('href');
		  ytplayer.loadVideoById(nextVideoId);
		  if($('.videoEnd').is(':visible')){
        $('.videoEnd').fadeOut();
        toggleVideoControls('show', 1000);
      }
		  object.attr({
        name: nextVideoId
      }); // set new name & rel
      updateVideoInfo();
		  return false;
		});
}

