/***** VARS *****/
var pURL = '/playlist.xml';
var pCurArtist = {id: 'p_cur_artist', val: ''};
var pCurAlbum = {id: 'p_cur_album', val: ''};
var pCurTitle = {id: 'p_cur_title', val: ''};
var pCurPlayedAt = {id: 'p_cur_playedat', val: ''};
var pCurLength = {id: 'p_cur_length', val: ''};
var pNexArtist = {id: 'p_nex_artist', val: ''};
var pNexTitle = {id: 'p_nex_title', val: ''};
var pCookieName = "morowPlaylist";
var timer = [];

var curUrl = window.location.toString();
var debugplaylist = false;
if(curUrl.search(/\?debugplaylist$/)==21) {
	debugplaylist = true;
}

// Démarre le chargement de la playlist
function pStart() {

	if(pCookieVal = pReadCookie()) {
		pParseCookie(pCookieVal);
		pDisplay();
	} else {
		pDisplayLoadWaiting();
		pLoadXML();
	}

}

// Lit le cookie contenant la playlist
function pReadCookie() {
	if(debugplaylist) { $("#debugplaylist").html("cookie"); }
	var nameEQ = pCookieName + "=";
	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;
}

// Parse le cookie
function pParseCookie(value) {
	newValue = unserialize(unescape(value));
	
	pCurArtist.val = newValue.pCurArtist;
	pCurAlbum.val = newValue.pCurAlbum;
	pCurTitle.val = newValue.pCurTitle;
	pCurPlayedAt.val = newValue.pCurPlayedAt;
	pCurLength.val = newValue.pCurLength;
	pNexArtist.val = newValue.pNexArtist;
	pNexTitle.val = newValue.pNexTitle;

}

// Charge le playlist.xml depuis une URL
function pLoadXML() {
	if(debugplaylist) { $("#debugplaylist").html("xml"); }
	$.ajax({
		type: "GET",
		url: pURL,
		success: pParseXML,
		error: pErrorDisplay,
		dataType: "xml",
		cache: false
	});
}

// Callback qui parse le XML
function pParseXML(data, textStatus) {
	$(data).find("song[position=now]").each(function() {
		pCurArtist.val 		= 	$(this).find("artist").text();
		pCurAlbum.val 		= 	$(this).find("album").text();
		pCurTitle.val 		= 	$(this).find("title").text();
		pCurPlayedAt.val 	=	$(this).find("played_at").text();
		pCurLength.val 		= 	$(this).find("length").text();
	});
	$(data).find("song[position=next]").each(function() {
		pNexArtist.val		=	$(this).find("artist").text();
		pNexTitle.val		=	$(this).find("title").text();
	});
	
	pCreateCookie();
	pDisplay();
}

// Créé le cookie avec la playlist actuelle
function pCreateCookie() {
	var date = new Date();
	date.setTime(date.getTime()+60000);
	var expires = "; expires="+date.toGMTString();
	var value = escape(pSerialize());
	document.cookie = pCookieName+'='+value+expires+'\'; path=/';
}

// Affiche la playlist
function pDisplay() {
	pLoadStruct(); // On charge le squellette
	pUpdateField(pCurArtist);
	pUpdateField(pCurAlbum);
	pUpdateField(pCurTitle);
	pUpdateField(pNexArtist);
	pUpdateField(pNexTitle);
	
	pUpdateButtons();
	
	$("#playlist-loader").fadeOut();
	$("#playlist").fadeIn();
	
	pStartTimer();
}

// Démarre le compte à rebourd avant prochaine MAJ
function pStartTimer() {
	playlistTimer = setTimeout("pLoadXML()", 30000);
}

// Affiche une erreur de Playlist
function pErrorDisplay() {

}

function pDisplayLoadWaiting() {
	$("#playlist").fadeOut();
	$("#playlist-loader").fadeIn();
}


/**********************/
/* Fonctions internes */
/**********************/

function pUpdateButtons() {

	var LastFMJSONurl = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=dde10f27f642fac13c9557277f93c45f&artist="+pCurArtist.val+"&album="+pCurAlbum.val+"&format=json&callback=?";
	var iTunesJSONurl = "http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsSearch?term="+sanitize_for_url(pCurArtist.val)+"&media=music&entity=album&limit=1&callback=?";
	
	$.getJSON(LastFMJSONurl, pLoadCover);
	$.getJSON(iTunesJSONurl, pUpdateBuyButton);
	$("#playlist #info_button_url").attr('href', '/infos/'+sanitize_for_url(pCurArtist.val)+'/'+sanitize_for_url(pCurAlbum.val)+'.html');
	$("#playlist #coverlink").attr('href', '/infos/'+sanitize_for_url(pCurArtist.val)+'/'+sanitize_for_url(pCurAlbum.val)+'.html');
}

function pLoadCover(json, textStatus) {
	if(json.error) {
		$("#playlist #cover").attr("src", "/images/iphone/nopicture.png");
	} else {
		$("#playlist #cover").attr("src", json.album.image[2]['#text']);
	}
}

function pUpdateBuyButton(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&a=1709937&url='+encodeURIComponent(json.results[0].artistViewUrl+'&partnerId=2003'));
	}
}

function pLoadStruct() {
	$('#playlist').html('<a id="coverlink" href="#"><img src="" id="cover" alt="" /></a><div style="overflow:hidden"><span id="p_cur_title" class="text"></span><br/><span id="p_cur_artist" class="text"></span><br/><span id="p_cur_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"><strong>Next:</strong> <span id="p_nex_artist"></span> - <span id="p_nex_title"></span></span>');
}

function pUpdateField(obj) {
	clearTimeout(timer[obj.id]);
	$("#playlist #"+obj.id).css('margin-left', '0px');
	$("#playlist #"+obj.id).html(obj.val);
	if(scroll) {
		pNeedScroll(obj.id);
	}
}

function pNeedScroll(id) {	
	if($("#playlist #"+id).width() > 290) {
		pFieldScroll(id, 'left');
	}
	return false;
}

function pFieldScroll(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 pSerialize()
{
	var pObject = {
					pCurArtist: pCurArtist.val,
					pCurAlbum: pCurAlbum.val,
					pCurTitle: pCurTitle.val,
					pCurPlayedAt: pCurPlayedAt.val,
					pCurLength: pCurLength.val,
					pNexArtist: pNexArtist.val,
					pNexTitle: pNexTitle.val
	}
	return serialize(pObject);
}

function sanitize_for_url(data)
{
	data = data.replace(new RegExp("[/ ]", "g"), "+");
	data = data.replace(new RegExp("[']", "g"), "");
	data = encodeURIComponent(data);
	return data;
}

