var songData = [];
var nextSongIndex = 0;
var currentPlayer = null;
var currentSong;
var players = [];
var busyUpdatingDB = false;
$(window).ready(init);


function browserIsSafari() {
	//alert(navigator.userAgent );
	if (navigator.userAgent.indexOf("Safari")!=-1 && navigator.userAgent.indexOf("Chrome")==-1) {
		return true;
	} else {
		return false;
	}
//	return true;
}


function init() {	 
	setInterval(updateSourcesDB,30*60*1000); // ieder half uur
	if (!browserIsSafari()) {
		alert("Unfortunately Firefox, Chrome and IE do not (properly) support the playback of (all) MP3 files (yet).\nFor best results use Safari instead :(");
	} else {
		initPrototypes();
		setInterval(update,100);
		$("#nextButton").click(onClickNextButton);
		
		
		$.ajax({
			type:		"POST",
			url:		"/data.xml?rnd=" +Math.round(Math.random()*1000000),
			dataType:	"xml",
			success:	onLoadXML
		}); 
	}
}


function updateSourcesDB() {
	if (busyUpdatingDB) return;
	busyUpdatingDB = true;
	$.ajax({
			type:		"POST",
			url:		"/updateradio.php",
			dataType:	"json",
			success:	function() {
				busyUpdatingDB = false;
				//alert("test");
			}
		}); 
}

function onClickNextButton() {
	if (currentPlayer != null) {
		
		currentPlayer.fadeOutAndKill();		
	}
	playNextSong();
}

function formatPlayTime(t) {
	var hours = Math.floor(t / 60 / 60);
	var minutes = Math.floor(t / 60) % 60;
	var seconds = Math.floor(t) % 60;


	if (seconds < 10) seconds = "0" + seconds;
	if (hours == 0) {
		return minutes + ":" + seconds; 
	} else {
		if (hours < 10) {
			hours = "0" + hours;
		}
		if (minutes < 10) {
			minutes = "0" + minutes;
		}
		return hours + ":" + minutes + ":" + seconds; 	
	}
}

function update() {
	var status = $("#statusContainer");
	statusText = "test";
	
	if ( currentPlayer != null) {
		if (currentPlayer.player.networkState == 3) { // not found
			onClickNextButton();
		}
		if (isNaN(currentPlayer.player.currentTime) || isNaN(currentPlayer.player.duration) ) {
			statusText =  currentSong.sourceTitle + " &mdash; <a href='"+currentSong.songLink +"' target='_blank'>" + currentSong.songTitle + "</a>  [...]";
		} else {
			statusText = 
				 currentSong.sourceTitle + " &mdash; <a href='" +currentSong.songLink + "' target='_blank'>" + currentSong.songTitle + "</a>" + 
				" [" + formatPlayTime(currentPlayer.player.currentTime) + " / " + 
				formatPlayTime(currentPlayer.player.duration) + "] "
				;
		}
		/*statusText += " - ";
		statusText += Math.round(currentPlayer.currentTime);*/
		if (currentPlayer.player.currentTime + 18 > currentPlayer.player.duration) {
			currentPlayer.fadeOutAndKill();		
			playNextSong();
		}
	
	} else {
		statusText = "Not (yet) playing...";
	}

	
	status.html(statusText);
}

function onLoadXML(xml) {
	processXML(xml);
	playNextSong();	
}

function processXML(xml) {
	var xmlItems = $(xml).find("item");
	for (var i=0;i < xmlItems.length;i++) { 
		var xmlItem = xmlItems[i];
		
		var songTitle   = $(xmlItem).find("title"	).text();
		var songLink   	= $(xmlItem).find("link" 	).text();
		var sourceTitle = $(xmlItem).find("source" 	).text();
		var sourceLink 	= $(xmlItem).find("source" 	)[0].attributes.getNamedItem("url").value;
		
		songData.push({
			'songTitle':	songTitle,
			'songLink':		songLink,
			'sourceTitle':	sourceTitle,
			'sourceLink':	sourceLink
		});
	}
	songData.randomize();
	nextSongIndex = 0;
}

function playNextSong() {
	currentSong = songData[nextSongIndex];
	var url = currentSong.songLink;
	var newPlayer = new SongPlayer(url);
	players.push(newPlayer);
	if(currentPlayer != null) currentPlayer.hidePlayer();
	currentPlayer = newPlayer;
	nextSongIndex++;
	nextSongIndex %= songData.length;
}

function SongPlayer(url) {
	this.player = new Audio();
	
	$("#playerContainer").append(this.player);

	
	this.player.setAttribute('src', url);
	this.player.load();
	this.player.setAttribute('controls', 'true');
	this.player.play();
	
	
	this.fadeOutAndKill = function () {
		var context = this;
		
		this.fadeOutIntervalId = setInterval(function(){
			context.player.volume *= 0.975;
			if (context.player.volume <= 0.004) {
				context.player.volume = 0;
				clearInterval(context.fadeOutIntervalId);
				$(context.player).remove();
			}
		},100)
	}
	
		
	this.destroy = function() {
		$(this.player).remove();
	}
	
	this.hidePlayer = function() {
		$(this.player).hide()

	}
	
}

function initPrototypes() {
	Array.prototype.randomize = function() {
		var s = [];
		while (this.length) s.push(this.splice(Math.random() * this.length, 1)[0]);
		while (s.length) this.push(s.pop());
		return this;
	}
}
