var playlistURL = "/playlist.xml";
var refreshPlaylist;
var playlistTimer;
var text_width = $('#playlist').width();
var needConstruction = true;
var timer = [];
var playlistTimeBeforeRefresh; // en millisecondes

function scroll(id, direction) {
	var marginleft = $("#playlist #"+id).css('margin-left').match('-?[0-9]{1,}');
	var max_width = 290;
	var span_width = $("#playlist #"+id).width();
	if(direction=="left" && Math.abs(marginleft)+max_width >= span_width) {
		timer[id] = window.setTimeout("scroll('"+id+"', 'right')", 4000);
		return true;
	} else if(direction=="right" && marginleft>=0) {
		timer[id] = window.setTimeout("scroll('"+id+"', 'left')", 4000);
		return true;
	}
	$("#playlist #"+id).css('margin-left', marginleft-(direction=="left"?1:-1));
	timer[id] = window.setTimeout("scroll('"+id+"', '"+direction+"')", 100);
}
function need_scroll(id) {	
	if($("#playlist #"+id).width() > 290) {
		scroll(id, 'left');
	}
	return false;
}

function change_text(id, value, scroll) {
	$("#playlist #"+id).fadeOut();
	clearTimeout(timer[id]);
	$("#playlist #"+id).css('margin-left', '0px');
	$("#playlist #"+id).html(value);
	$("#playlist #"+id).fadeIn();
	if(scroll) {
		need_scroll(id);
	}
}

function calculateTimer(curDate, targetDate)
{

}

function xmlPlaylistLoaded(data, textStatus) 
{
	
	if($(data).find("song[position=now]").find("title").text()!=$("#playlist #title").html()) {
		
		$(data).find("song[position=now]").each(function() {
		
			var artist = $(this).find("artist").text();
			var album = $(this).find("album").text();
			var title = $(this).find("title").text();
			var played_at = $(this).find("played_at").text();
			var length = $(this).find("length").text();
			
			change_text('title', title, true);
			change_text('artist', artist, true);
			change_text('album', album, true);
			
			$("#playlist #info_button_url").attr('href', '/infos/'+artist.replace(new RegExp(" ", "g"), "_")+'/'+album.replace(new RegExp(" ", "g"), "_")+'.html');
			
			// iTunes
			var iTunesJSONurl = "http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsSearch?term="+sanitize_for_url(artist)+"&media=music&entity=album&limit=1&callback=?";
			$.getJSON(iTunesJSONurl, updateBuyButton);
			
			// LastFM cover
			var LastFMJSONurl = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=dde10f27f642fac13c9557277f93c45f&artist="+artist+"&album="+album+"&format=json&callback=?";
			$.getJSON(LastFMJSONurl, updateCoverImage);
			
		});
		
		$(data).find("song[position=next]").each(function() {

			var next = $(this).find("artist").text()+" - "+$(this).find("title").text();
			change_text('next', '<span style="font-weight:bold">Next:</span> '+next);

		});
		
		$("#playlist-loader").fadeOut();
		$("#playlist").fadeIn();

	}			
}

function sanitize_for_url(data)
{
	data = data.replace(new RegExp("[/ ]", "g"), "+");
	data = data.replace(new RegExp("[']", "g"), "");
	data = encodeURIComponent(data);
	return data;
}

function updateCoverImage(json, textStatus)
{
	if(json.error)
	{
		$("#playlist #cover").attr("src", "/images/iphone/nopicture.png");
	}
	else
	{
		$("#playlist #cover").attr("src", json.album.image[2]['#text']);
		//$("#banner #album_infos").html(json.album.wiki.summary);
	}
}

function updateBuyButton(json, textStatus)
{
	if(json.resultCount==0)
	{
		$("#playlist #buy_button_url").hide();
	}
	else
	{
		$("#playlist #buy_button_url").show().attr('href', 'http://clkuk.tradedoubler.com/click?p=23753&amp;a=1709937&amp;url='+json.results[0].artistViewUrl+'&amp;partnerId=2003');
	}
}

function refreshIcon(action)
{
	if(action=="show") { document.getElementById('refresh-icon').style.display = "inline"; }
	else if(action=="hide") { document.getElementById('refresh-icon').style.display = "none"; }
	else { document.getElementById('refresh-icon').style.display = "none"; }
}

function displayError(request, TextStatus, errorThrown)
{
	//$("#playlist").html("<div class=\"\"><img src=\"/images/icons/16x16/important.png\" alt=\"\" /> An error occured while loading the playlist:<br/>"+errorThrown+"</div>");
}

function refreshPlaylist()
{

	var curUrl = window.location.toString();

	if(curUrl.search(/\?debugplaylist$/)==21)
	{
		pStart();
	} else {
		$("#playlist-loader").fadeOut();
		$("#playlist").html("<div style=\"padding-top:30px;text-align:center\">Playlist currently disabled. We're fixing it!<br/>Meanwhile, feel free to explore the website and <a href=\"/forums\">the forums</a>!<br/>Did we say you can listen to the radio just right here? <img src=\"/images/tango/32x32/actions/go-next.png\"/></div>").fadeIn();
	}

}

function loadPlaylist()
{
	var playlistDOM = '<img src="" id="cover" alt=""/><div style="overflow:hidden">		<span id="title" class="text"></span><br/>		<span id="artist" class="text"></span><br/>		<span id="album" class="text"></span>	</div>	<div id="badges">		<a href="" id="info_button_url"><img src="/images/playlist/badgeinfo.png" alt="infos" width="51" height="15" /></a> 		<a href="" id="buy_button_url"><img src="/images/playlist/badgebuy.png" alt="buy" width="51" height="15"/></a><br/>		<a href="/history.html" id="songhistory_button_url"><img src="/images/playlist/songhistory.png" alt="song history" width="107" height="15"/></a>	</div>	<span id="next"></span><a href="javascript:refreshPlaylist()">refresh</a>';
	$('#playlist').html(playlistDOM);
	
	refreshPlaylist();
}

function startPlaylistTimer(playlistTimer)
{
	playlistTimer = setTimeout("refreshPlaylist()", playlistTimeBeforeRefresh);
}

function stopTimer()
{
	clearTimeout(playlistTimer);
}



function createCookie() {
	var date = new Date();
	date.setTime(date.getTime()+playlistTimeBeforeRefresh);
	var expires = "; expires="+date.toGMTString();
	document.cookie = "morowPlaylist="+value+expires+"; path=/";
}

function readCookie() {
	var nameEQ = "morowPlaylist" + "=";
	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() {
	createCookie("morowPlaylist","",-1);
}

