
function recordingInit() {
	loadCommentUserInfo();
}

function getSongName(recording) {
	return recording.songId < 100000 ? recording.song.name : recording.zingSong.title;
}

function openRecording(recording) {
	var title = recording.artist.name + " - " + getSongName(recording);
	document.getElementById("mplayer").playURL(String(getDownloadURL(recording)), String(title));
	showRecordingInfo(recording);
}

function showRecordingInfo(item) {
	showRecordingData(item);
	getMyVote(item);
	loadComments(item.id);
	showPostCommentForm(item.id);
}

function showRecordingData(item) {
	var html = new StringBuilder();
	html.append('<table>');
	html.append('<tr><td>Nh&#x1EA1;c Ph&#x1EA9;m:</td><td>').append(getSongName(item)).append('</td></tr>');
	html.append('<tr><td>Ca S&#x1EF9;:</td><td><a href="mailto:').append(item.artist.email).append('">').append(item.artist.name).append('</a></td></tr>');
	html.append('<tr><td>Download MP3:&nbsp;&nbsp;&nbsp;</td><td><a href="').append(getDownloadURL(item)).append('" title="Right click, choose Save As">Link</a></td></tr>');
	html.append('<tr><td>URL:</td><td><form><input type="text" onfocus="this.select()" readonly value="').append(getRecordingURL(item)).append('"/></form></td></tr>');
	html.append('<tr><td>Embed Audio:</td><td><form><input type="text" onfocus="this.select()" readonly value=\'').append(getAudioEmbedCodeForRecording(item)).append('\'/></form></td></tr>');
	html.append('<tr><td>Embed Video:</td><td><form><input type="text" onfocus="this.select()" readonly value=\'').append(getVideoEmbedCodeForRecording(item)).append('\'/></form></td></tr>');
	html.append('<tr><td>Your vote:</td><td><div id="my-vote"></div></td></tr>');
	html.append('</table>');
	document.getElementById("recording-info").innerHTML = html;
}

function timestampToDate(ts) {
	var date = new Date();
	date.setTime(ts);
	return (date.getMonth()+1) + "-" + date.getDate() + "-" + date.getFullYear();
}

function getRecordingURL(recording) {
	return "http://" + window.location.hostname + "/recordings.html?recordingId=" + recording.id;
}

function getVideoEmbedCodeForRecording(recording) {
	var url = 'http://' + window.location.hostname + '/flash/KaraokePlayer.swf?contentServer=' + contentServer + '&songId=' + recording.songId + '&songTitle=' + encodeURIComponent(getSongName(recording)).replace("'", "%27") + '&artistId=' + recording.artist.id + '&artistName=' + encodeURIComponent(recording.artist.name).replace("'", "%27") + '&autoplay=false';
	var html = '<object width="440" height="370">';
	html += '<param name="movie" value="' +url+ '"></param>';
	html += '<param name="allowFullScreen" value="true"></param>';
	html += '<param name="allowScriptAccess" value="always"></param>';
	html += '<embed src="' +url+ '" type="application/x-shockwave-flash" allowFullScreen="true" allowScriptAccess="always" width="440" height="370"></embed>';
	html += '</object>';
	return html;
}

function getAudioEmbedCodeForRecording(recording) {
	var title = recording.artist.name + " - " + getSongName(recording);
	var url = 'http://' + window.location.hostname + '/flash/mplayer.swf?url=' + encodeURIComponent(getDownloadURL(recording)) + '&title=' + encodeURIComponent(title).replace("'", "%27") + '&autoplay=false';
	var html = '<object width="320" height="60">';
	html += '<param name="movie" value="' +url+ '"></param>';
	html += '<param name="allowFullScreen" value="true"></param>';
	html += '<param name="allowScriptAccess" value="always"></param>';
	html += '<embed src="' +url+ '" type="application/x-shockwave-flash" allowFullScreen="true" allowScriptAccess="always" width="320" height="60"></embed>';
	html += '</object>';
	return html;
}

function getDownloadURL(recording) {
	return "http://" + mediaServer + "/published/" + recording.songId + "-" + recording.artist.id + ".mp3";
}

// Voting -----------------------------

function getMyVote(recording) {
	document.getElementById("rating-submitter").retrieveRating(Number(recording.id));
/*
	var http = false;
	if (navigator.appName == "Microsoft Internet Explorer") {
		http = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		http = new XMLHttpRequest();
	}
	http.open("GET", "/servlet/getmyvote?recordingId=" + recording.id + "&ts=" + new Date().getTime(), true);
	http.onreadystatechange = function() {
		if (http.readyState == 4) {
			if (http.status == 200) {
				eval(http.responseText);
				setMyVote(rating);
			}
			else if (http.status == 404)
        		enableVoting(recording);
			else
				alert("Failed to get my vote - code " + http.status);
		}
	}
	http.send(null);
*/
}

function ratingRetrieved(recordingId, rating) {
	if (rating != 0)
		setMyVote(rating);
	else
		enableVoting(recordingId);
}

function submitMyVote(recordingId, rating) {
	document.getElementById("rating-submitter").submitRating(Number(recordingId), Number(rating));
	setMyVote(rating);
/*
	var params = "recordingId=" + recordingId + "&rating=" + rating;
	var http = false;
	if (navigator.appName == "Microsoft Internet Explorer") {
		http = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		http = new XMLHttpRequest();
	}
	http.open("POST", "/servlet/vote", true);
	http.onreadystatechange = function() {
		if (http.readyState == 4) {
			if (http.status == 200)
				setMyVote(rating);
			else
				alert("Failed to record vote - code " + http.status);
		}
	}
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-Length", params.length);
	http.send(params);
*/
}

function setMyVote(rating) {
	document.getElementById("my-vote").innerHTML = getRatingImage(rating);
}

function enableVoting(recordingId) {
	var html = new StringBuilder();
	html.append("<a href='javascript:submitMyVote(").append(recordingId).append(", 1)'><img id='vote-star-1' src='images/empty_star.gif' onMouseOver='showVoteStars(1)' onMouseOut='showVoteStars(0)'/></a>");
	html.append("<a href='javascript:submitMyVote(").append(recordingId).append(", 2)'><img id='vote-star-2' src='images/empty_star.gif' onMouseOver='showVoteStars(2)' onMouseOut='showVoteStars(0)'/></a>");
	html.append("<a href='javascript:submitMyVote(").append(recordingId).append(", 3)'><img id='vote-star-3' src='images/empty_star.gif' onMouseOver='showVoteStars(3)' onMouseOut='showVoteStars(0)'/></a>");
	html.append("<a href='javascript:submitMyVote(").append(recordingId).append(", 4)'><img id='vote-star-4' src='images/empty_star.gif' onMouseOver='showVoteStars(4)' onMouseOut='showVoteStars(0)'/></a>");
	html.append("<a href='javascript:submitMyVote(").append(recordingId).append(", 5)'><img id='vote-star-5' src='images/empty_star.gif' onMouseOver='showVoteStars(5)' onMouseOut='showVoteStars(0)'/></a>");
	document.getElementById("my-vote").innerHTML = html;
}

function showVoteStars(count) {
	for (var i=1; i<=5; i++)
		document.getElementById("vote-star-" + i).src = (i <= count)? "images/filled_star.gif" : "images/empty_star.gif";
}

function getRatingImage(rating) {
	return "<img src='images/stars" + (Math.round(rating*2)*5) + ".gif'/>";
}

// Comments -------------------------------------------------

var c_me = new Object();
c_me.nick = "anonymous";
c_me.email = "";

function loadCommentUserInfo() {
	var userInfo = getCookie("c_me");
	if (userInfo != "") {
		c_me = decodeObject(userInfo);
	}
}

function saveCommentUserInfo() {
	setCookie("c_me", encodeObject(c_me), 30);
}

function showPostCommentForm(recordingId) {
	var html = new StringBuilder();
	html.append('<form action="javascript:postComment()">');
	html.append("<input type='hidden' id='postCommentRecordingId' value='").append(recordingId).append("'/>");
	html.append('<label>Name:&nbsp;</label>');
	html.append("<input type='text' size='20' id='postCommentUser' value='").append(c_me.nick).append("'/><br/>");
	html.append('<label>(Email):&nbsp;</label>');
	html.append("<input type='text' size='20' id='postCommentEmail' value='").append(c_me.email).append("'/><br/>");
	html.append("<textarea rows='4' cols='40' id='postCommentText'></textarea><br/>");
	html.append("<input type='submit' value='Submit'/>");
	html.append('</form>');
	document.getElementById("post-comment-form").innerHTML = html;
}

function hidePostCommentForm() {
	document.getElementById("post-comment-form").innerHTML = "&nbsp;";
}

function loadComments(recordingId) {
	var http = false;
	if (navigator.appName == "Microsoft Internet Explorer") {
		http = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		http = new XMLHttpRequest();
	}
	http.open("GET", "/servlet/getcomments?recordingId=" + recordingId + "&ts=" + new Date().getTime(), true);
	http.onreadystatechange = function() {
		if (http.readyState == 4) {
			if (http.status == 200) {
				eval(http.responseText);
				printComments(itemList);
			}
			else if (http.status == 404)
				document.getElementById("recording-comments").innerHTML = "No comments";
			else
				alert("Failed to load comments - code " + http.status);
		}
	}
	http.send(null);
	document.getElementById("recording-comments").innerHTML = "<font color='red'>Loading...</font>";
}

function printComments(commentList) {
	var html = new StringBuilder();
	for (var i in commentList) {
		var comment = commentList[i];
		html.append("<div class='comment'>");
		html.append("<div class='comment-head'>");
		if (comment.email)
			html.append("<a href='mailto:").append(comment.email).append("'>").append(comment.user).append("</a>");
		else
			html.append(comment.user);
		html.append(" (").append(howLongAgo(comment.time)).append(")");
		html.append("</div>");
		html.append("<div class='comment-text'>");
		for (var j in comment.text)
			html.append(comment.text[j]).append("<br/>");
		html.append("</div>");
		html.append("</div>");
	}
	document.getElementById("recording-comments").innerHTML = html;
}

function postComment() {
	var recordingId = document.getElementById("postCommentRecordingId");
	var user = document.getElementById("postCommentUser");
	var email = document.getElementById("postCommentEmail");
	var text = document.getElementById("postCommentText");
	if (user.value == "") {
		alert("User name is empty!");
		return;
	}
	if (text.value.length < 10) {
		alert("Your comment must be at least 10 characters");
		return;
	}
	if (text.value.indexOf("<") != -1) {
		alert("Comment cannot contain HTML");
		return;
	}
	var params = "recordingId=" + recordingId.value + "&user=" + encodeURIComponent(user.value) + "&email=" + encodeURIComponent(email.value) + "&comment=" + encodeURIComponent(text.value);

	var http = false;
	if (navigator.appName == "Microsoft Internet Explorer") {
		http = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		http = new XMLHttpRequest();
	}
	http.open("POST", "/servlet/postcomment", true);
	http.onreadystatechange = function() {
		if (http.readyState == 4) {
			if (http.status == 200) {
				c_me.nick = user.value;
				c_me.email = email.value;
				saveCommentUserInfo();
				hidePostCommentForm();
				loadComments(recordingId.value);
				document.getElementById("recording-comments").innerHTML = "<font color='red'>Loading...</font>";
			}
			else {
				alert("Failed to post comment, please try again later - code " + http.status);
			}
		}
	}
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-Length", params.length);
	http.send(params);
}

function howLongAgo(timestamp) {
	var seconds = (new Date().getTime() - timestamp) / 1000;
	if (seconds < 60)
		return Math.round(seconds) + " seconds ago";
	var minutes = seconds / 60;
	if (minutes < 60)
		return Math.round(minutes) + " minutes ago";
	var hours = minutes / 60;
	if (hours < 24)
		return Math.round(hours) + " hours ago";
	var days = hours / 24;
	if (days < 7)
		return Math.round(days) + " days ago";
	var weeks = days / 7;
	if (weeks < 5)
		return Math.round(weeks) + " weeks ago";
	var months = days / 30;
	if (months < 12)
		return Math.round(months) + " months ago";
	var years = days / 365;
	return Math.round(years) + " years ago";
}
