"use strict";

var currentVideoId;
var tvWidth;
var tvHeight;
var tv;
var queueUpdateInterval;
var isLive;

function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name, "", -1);
}

function secToMinSec(seconds) {
	var minutes = Math.floor(seconds / 60);
	var remainingSeconds = Math.floor(seconds) - minutes * 60;
	if(remainingSeconds.toString().length<2){
		remainingSeconds = "0" + remainingSeconds.toString();
	}
	return minutes + ":" + remainingSeconds;
}

function goLive() {
	if(!isLive){
		$("#live").animate({"background-color": "#0B0"}, "slow", function(){
			$("#live").animate({"background-color": "#BBB"}, "slow", function(){
				$("#live").animate({"background-color": "#0B0"}, "slow");
			});
		});
		isLive = 1;
	}
}

function goUnlive() {
	if(isLive){
		$("#live").animate({"background-color": "#BBB"}, "slow", function(){
			$("#live").animate({"background-color": "#0B0"}, "slow", function(){
				$("#live").animate({"background-color": "#BBB"}, "slow");
			});
		});
		isLive = 0;
	}
}

function showArchiveLink(aid) {
	$("#archiveLink").attr("href", "http://tv.seriousinc.net/archive/video.php?id=" + aid);
	$("#archivedContainer").animate({width: 35}, "slow", function(){ 
		$("#archivedSpacer").animate({height: 0}, "slow");
	});

}

function hideArchiveLink() {
	$("#archiveLink").attr("href", "");
	$("#archivedSpacer").animate({height: 26}, "slow", function(){ 
		$("#archivedContainer").animate({width: 1});
	});
}

function onYouTubePlayerReady(playerId) {
	tv = document.getElementById("mytv");
	tv.setVolume(100);
	
	$.ajaxSetup({timeout : 3000}); //requests that complete after too long screw up the tv
	
	$.get("./nowplaying.php", function(data){
		if(data.charAt(0) == "{"){
			var videoData = eval("("+data+")");
			currentVideoId = videoData.id
			
			readCookie("big") ? titleLen=50 : titleLen=40;
			if(readCookie("hidechat") && videoData.title.length>titleLen){
				var shortTitle = videoData.title.substring(0, titleLen) + "...";
			} else {
				var shortTitle = videoData.title;
			}
			
			tv.loadVideoById(currentVideoId, videoData.position, tvQuality);
			$("#videoTitle").html("<a href=\"" + tv.getVideoUrl() + "\" target=\"_blank\" title=\"" + videoData.title.replace("\"", "&quot;") + "\">" + shortTitle + "</a>");
			
			if(videoData.aid!=0){
				showArchiveLink(videoData.aid);
			}
			
			if(videoData.live){
				$("#live").animate({"background-color": "#0B0"}, "slow");
				isLive = 1;
			} else {
				$("#live").animate({"background-color": "#BBB"}, "slow");
				isLive = 0;
			}
			
			$("#viewers").html(videoData.viewers);
		} else {
			update();
		}
	});
	ping();
	setInterval("update()", 1000);
	setInterval("progress()", 83);
	setInterval("ping()", 60000);
	window.onbeforeunload = function(){
		$.get("./closeConnection.php");
	}
}

function update() {
	$.get("./nowplaying.php?nocache=" + Math.floor(Math.random()*1000000), function(data){
		if(data.charAt(0) == "{"){
			var videoData = eval("("+data+")");
			var timeDifference = Math.abs(videoData.position - tv.getCurrentTime())
			
			readCookie("big") ? titleLen=50 : titleLen=40;
			if(readCookie("hidechat") && videoData.title.length>titleLen){
				var shortTitle = videoData.title.substring(0, titleLen) + "...";
			} else {
				var shortTitle = videoData.title;
			}
			
			if(videoData.id==currentVideoId){
				if(timeDifference>=5 && tv.getPlayerState()<=1 && videoData.position<tv.getDuration()){
					tv.seekTo(videoData.position, 1);
				}
			} else {
				currentVideoId = videoData.id;
				tv.loadVideoById(currentVideoId);
				
				$("#videoTitle").html("<a href=\"" + tv.getVideoUrl() + "\" target=\"_blank\" title=\"" + videoData.title.replace("\"", "&quot;") + "\">" + shortTitle + "</a>");
				
				if(videoData.live==1){
					goLive();
				} else {
					goUnlive();
				}
				
				updateQueue();
			}
			
			$("#viewers").html(videoData.viewers);
			
			if(videoData.aid!=0){
				showArchiveLink(videoData.aid);
			} else {
				hideArchiveLink();
			}
		}
	});
	
	$("#position").text(secToMinSec(tv.getCurrentTime()));
	$("#duration").text(secToMinSec(tv.getDuration()));
}

function updateQueue() {
	$.get("./queue.php?nocache=" + Math.floor(Math.random()*1000000), function(data){
		if(data.length>17){
			$("#queue").html(data);
		} else {
			$("#queue").html("Nothing cued.");
		}
	});
}

function progress() {
	$("#progressbar").width(tv.getCurrentTime()/tv.getDuration()*100+"%");
}

function ping() {
	$.get("./openConnection.php");
}

$(document).ready(function(){
	if(readCookie("big")){
		tvWidth = "600";
		tvHeight = "450";
		$("#big").attr("checked", true);
	} else {
		tvWidth = "490";
		tvHeight = "368";
	}

	if(readCookie("hidechat")){
		$("#hidechat").attr("checked", true);
	}
	
	if(readCookie("highquality")){
		$("#highquality").attr("checked", true);
		tvQuality = "medium";
	} else {
		$("#defaultquality").attr("checked", true);
		tvQuality = "small";
	}
	
	var params = { allowScriptAccess: "always", wmode: "opaque" };
	var atts = { id: "mytv" };
	swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=tv&loop=1", "ytapiplayer", tvWidth, tvHeight, "8", null, null, params, atts);
	
	$("#preferences").click(function(event){ //Toggles visibility of preferencesbox
		if($("#preferencesbox").is(":visible")){
			$("#preferencesbox").slideUp("normal");
		} else {
			$("#preferencesbox").slideDown("slow");
		}
		event.preventDefault();
	});
	
	$("#mute").click(function(event){ //Muuuuute
		if(tv.isMuted()){
			tv.unMute();
			$("#mute a").html("Mute");
		} else {
			tv.mute();
			$("#mute a").html("Unmute");
		}
		event.preventDefault();
	});
	
	$("#queuebutton").click(function(event){ //show queue
		if($("#queue").is(":visible")){
			$("#queue").slideUp("normal");
			clearInterval(queueUpdateInterval);
		} else {
			$("#queue").slideDown("normal");
			updateQueue();
			queueUpdateInterval = setInterval("updateQueue()", 10000);
		}
		event.preventDefault();
	});
	
	$("#bookmarklets").click(function(event){ //Visible bookmarkletsbox
		if($("#bookmarkletsbox").is(":visible")){
			$("#bookmarkletsbox").slideUp("normal");
		} else {
			$("#bookmarkletsbox").slideDown("slow");
		}
		event.preventDefault();
	});
	
	$("#saveprefs").click(function(event){ //Saaaaave
		if($('#big').is(':checked')){
			createCookie("big", "1", 365);
		} else {
			eraseCookie("big");
		}
		if($('#hidechat').is(':checked')){
			createCookie("hidechat", "1", 365);
		} else {
			eraseCookie("hidechat");
		}
		if($('#highquality').is(':checked')){
			createCookie("highquality", "1", 365);
		} else {
			eraseCookie("highquality");
		}
		window.location.reload()
		event.preventDefault();
	});
});