// ---------------------------------------------
//                Sample playing
// ---------------------------------------------
STOPPED = 1;
LOADING = 2;
PLAYING = 3;
ERROR = 4;

var gHomePage = 'http://www.pandora.com/';
var gCurrentSample = null;
var gCurrentName = null;
var gSampleState = STOPPED;
var gTimeoutID = null;
var gTimeoutStep = -1;
var gTokenList = [];
var gCurrentDisc = 0;

// This function assumes the samples have no unique "name" appended to the tokens
function playAllSamples(/*int*/ discNum, /*string[]*/ tokenList) {
	stopCurrentSample(false);
	gTokenList = tokenList;
	gCurrentDisc = discNum;
	var img = $("#sampleAllStop" + gCurrentDisc).css("display","inline");
	img = $("#sampleAllPlay" + gCurrentDisc).css("display","none").attr("src","images/sample-all.gif");
	playNextSample();
}

function playNextSample(/*string*/ name) {
	if (gTokenList.length > 0) {
		var token = gTokenList.shift();
		playSampleAudio(token, "", true);
	} else {
		stopCurrentSample(false);
	}
}

// Play a 30-second clip for the specified token.  The "name" arg is a unique
// string that is appended to the token to come up with the DIV names for the DHTML.
// This is to allow the same sample to appear on a page in more than one location
// without interference (i.e. the profile page)
function playSampleAudio(/*string*/ token, /*string*/ name, /*boolean*/ leaveTokenList, /*boolean*/ allowExplicit) {
	stopCurrentSample(leaveTokenList);

	gCurrentSample = token;
	gCurrentName = name;
	setSampleDisplay(token, name, LOADING);

	flashVars = ["musicId=" + token + "&uniqueName=" + name + "&sampleURL=" + escape(gHomePage + "favorites/getSample.jsp?token=" + token + "&allowExplicit=" + allowExplicit)];
	getAudioDiv().innerHTML = [
			'<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"',
			'		codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"',
			'		WIDTH="1"',
			'		HEIGHT="1"',
			'       id="SamplePlayer">',
			'	<PARAM NAME=movie VALUE="' + gHomePage + 'SamplePlayer.swf">',
			'	<PARAM NAME=quality VALUE=high>',
			'	<PARAM NAME=bgcolor VALUE=#FFFFFF>',
			'	<PARAM NAME=menu VALUE=false>',
			' <PARAM NAME="FlashVars" VALUE="' + flashVars + '">',
			'<EMBED src="' + gHomePage + 'SamplePlayer.swf"',
			'       quality=high',
			'       bgcolor=#FFFFFF',
			'       WIDTH="1"',
			'       HEIGHT="1"',
			'       MENU="false"',
			'       NAME="SamplePlayer" ALIGN="" TYPE="application/x-shockwave-flash"',
			'       PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"',
			'       FlashVars="' + flashVars + '">',
			'</EMBED>',
			'</OBJECT>'
			].join("");
}

// stop the current sample, unless it errored (we want errored load to stay
// displayed as errors)
function stopCurrentSample(/*boolean*/ leaveTokenList) {
	if (gCurrentSample != null && gSampleState != ERROR) {
		stopSampleAudio(gCurrentSample, gCurrentName, leaveTokenList);
	}
}

function stopSampleAudio(/*string*/ token, /*string*/ name, /*boolean*/ leaveTokenList) {
	getAudioDiv().innerHTML = "";
	setSampleDisplay(token, name, STOPPED);
	if (!leaveTokenList) {
		gTokenList = [];
		var img = $("#sampleAllStop" + gCurrentDisc).css("display","none");
		img = $("#sampleAllPlay" + gCurrentDisc).css("display","inline");
	}
}

function onSampleLoad(/*string*/ token, /*string*/ name, /*boolean*/ success) {
	if (success) {
		setSampleDisplay(token, name, PLAYING);
	} else {
		setSampleDisplay(token, name, ERROR);
	}
}

function onSampleComplete(/*string*/ token, /*string*/ name) {
	setSampleDisplay(token, name, STOPPED);
	playNextSample();
}

function getAudioDiv() {
	var div = $("#audioDiv").get(0);
	if (div == null) {
		div = document.createElement("DIV");
		div.id = "audioDiv";
		document.documentElement.appendChild(div);
	}
	return div;
}

function setSampleDisplay(token, name, state) {
	gSampleState = state;

	setDisplay("sampleStopped" + token + name, state == STOPPED);
	setDisplay("sampleLoading" + token + name, state == LOADING);
	setDisplay("samplePlaying" + token + name, state == PLAYING);
	setDisplay("sampleError" + token + name, state == ERROR);
	if (state == LOADING) {
		// workaround for Safari which doesn't send onmouseout when the stopped
		// div is hidden
		document.getElementById("sampleStoppedImg" + token + name).src = gHomePage + "images/30-play.gif";
	}

	// update the title text flashing except when we're transitioning from
	// LOADING to PLAYING (in that case, we want to keep flashing at regular
	// intervals rather than throwing of the rhythm)
	if (state != PLAYING) {
		if (gTimeoutID != null) clearTimeout(gTimeoutID);
		updateStep();
	}
}

function updateStep() {
	gTimeoutStep++;

	if (gTimeoutStep % 2 == 0) {
		setTitleDisplay(gCurrentSample, gCurrentName, gSampleState);
	} else {
		setTitleDisplay(gCurrentSample, gCurrentName, STOPPED);
	}

	if (gSampleState == LOADING || gSampleState == PLAYING) {
		gTimeoutID = setTimeout(updateStep, 1500);
	} else {
		gTimeoutStep = -1;
		gTimeoutID = null;
	}
}

function setTitleDisplay(token, name, state) {
	setVisibility("titleStopped" + token + name, state == STOPPED || state == ERROR);
	setVisibility("titleLoading" + token + name, state == LOADING);
	setVisibility("titlePlaying" + token + name, state == PLAYING);
}

function setDisplay(id, displayed) {
	if (document.getElementById(id) != null) {
		document.getElementById(id).style.display = displayed ? "" : "none";
	}
}

function setVisibility(id, displayed) {
	if (document.getElementById(id) != null) {
		document.getElementById(id).style.visibility = displayed ? "visible" : "hidden";
	}
}

function sampleHTML(token, uniqueName, allowExplicit) {
	if (window.ipBlocked) {
		return "&nbsp;";	// Don't allow 30-second samples for blocked IPs
	}
	var s = "";
	if (allowExplicit == null) {
		allowExplicit = false;
	}

	s += '<a id="sampleStopped' + token + uniqueName + '" title="Play sample" href="javascript:playSampleAudio(\'' + token + '\', \'' + uniqueName + '\', false, ' + allowExplicit + ');">';
	s += '<img id="sampleStoppedImg' + token + uniqueName + '" src="' + gHomePage + 'images/30-play.gif" ';
	s += 'border=0 width="14" height="15" alt="play sample" onmouseover="this.src=\'' + gHomePage + 'images/30-play-hover.gif\'" onmouseout="this.src=\'' + gHomePage + 'images/30-play.gif\'"></a>';
	// Loading icon
	s += '<span id="sampleLoading' + token + uniqueName + '" style="display:none">';
	s += '<img src="' + gHomePage + 'images/30-play-hover.gif" width="14" height="15" alt="play sample"></span>';
	// Stop icon
	s += '<a id="samplePlaying' + token + uniqueName + '" href="javascript:stopSampleAudio(\'' + token + '\', \'' + uniqueName + '\');" style="display:none">';
	s += '<img src="' + gHomePage + 'images/30-play-stop.gif" border=0 width="14" height="15" alt="stop"></a>';
	// Error icon
	s += '<span id="sampleError' + token + uniqueName + '" style="display:none">';
	s += '<img src="' + gHomePage + 'images/30-play-error.gif" width="14" height="15" alt="sample not available"></span>';

	return s;
}

function trackHTML(token, title, linkToDetail, textClass, playingClass){
	if (window.ipBlocked && title == "Play Sample") {
		return "&nbsp;";	// Don't allow 30-second samples for blocked IPs
	}
	var s = "";

	// Loading icon
	s += '<span id="titleLoading' + token + '" class="' + playingClass + '">Loading Sample</span>';
	// Play indicator
	s += '<span id="titlePlaying' + token + '" class="' + playingClass + '">Playing Sample</span>';
	// Song title
	if (linkToDetail) {
		s += '<a href="' + gHomePage + 'music/song/' + token + '" class="' + textClass + '" title="Song details" id="titleStopped' + token + '">' + title + '</a>';
	} else {
		s += '<span id="titleStopped' + token + '" class="' + textClass + '">' + title + '</span>';
	}

	return s;
}

// Used by #sampleLink macro to render 30-second sample UI using javascript to reduce size of HTML
function insertSample() {
	var jqThis = $(this);

	var token = jqThis.attr('token');
	var uniqueName = jqThis.attr('uniqueName');
	var allowExplicit = jqThis.attr('allowExplicit');

	var s = sampleHTML(token, uniqueName, allowExplicit);

	$(this).html(s);
}


// Used by #trackTitle macro to render 30-second sample track title using javascript to reduce size of HTML
// NOTE: title must be HTML-escaped
function insertTrackTitle() {
	var jqThis = $(this);

	var token = jqThis.attr('token');
	var title = jqThis.attr('trackTitle');
	var linkToDetail = jqThis.attr('linkToDetail');
	var textClass = jqThis.attr('textClass');
	var playingClass = jqThis.attr('playingClass');

	var s = trackHTML(token, title, linkToDetail, textClass, playingClass);

	$(this).html(s);
}

// Used by #sampleLink macro to render 30-second sample UI using javascript to reduce size of HTML
function drawSample(token, uniqueName, allowExplicit) {
	var s = sampleHTML(token, uniqueName, allowExplicit);

	document.write(s);	
}


// Used by #trackTitle macro to render 30-second sample track title using javascript to reduce size of HTML
// NOTE: title must be HTML-escaped
function trackTitle(token, title, linkToDetail, textClass, playingClass) {
	var s = trackHTML(token, title, linkToDetail, textClass, playingClass);

	document.write(s);
}