$(window).load(function () { initSelectedList(); });

function initSelectedList()
{
	selectedSongListChanged();
}

function selectedSongListChanged()
{
	$.getJSON("control/getselectedkaraokelist.php", updateSelectedSongList);
}

function updateSelectedSongList(music)
{
	if(music.songs.length > 0)
		buildSelectedSongTable(music);
	else
		showNoSelectedSongsMessage();
}

function buildSelectedSongTable(music)
{
	$("#rightlist").html(getSelectedSongsListHTML(music.songs));
	attachSelectedSongListEventHandlers();
}

function attachSelectedSongListEventHandlers()
{
	$(".removesong", "#rightlist").click(function(event) { removeSong(this.id.substring(4)); event.preventDefault(); });
}

function showNoSelectedSongsMessage()
{
	$("#rightlist").html(getNoSongsSelectedHTML());
}

function getSelectedSongsListHTML(songs)
{
	var selectedSongRows = [];
	
	for(i = 0; i < songs.length; i++)
		selectedSongRows[i] = getSelectedSongRowHTML(songs[i], (i % 2 == 0) ? "normal" : "striped");
	
	return	'\t<table id="selectedsongtable">\r\n'
		+		'\t\t<thead>\r\n'
		+			'\t\t\t<tr>\r\n'
		+			'\t\t\t\t<th>Song Title</th>\r\n'	
		+			'\t\t\t\t<th>Artist</th>\r\n'
		+			'\t\t\t</tr>\r\n'
		+		'\t\t</thead>\r\n'
		+		'\t\t<tbody>\r\n'
		+ 			selectedSongRows.join('')
		+		'\t\t</tbody>\r\n'
		+	'\t</table>\r\n';
}

function getSelectedSongRowHTML(song, className)
{
	return '\t\t\t<tr class="' + className + '">\r\n'
		+	'\t\t\t\t<td class="songtitle">'+song.title+'</td>\r\n'	
		+	'\t\t\t\t<td class="artist">'+song.artist+'</td>\r\n'				
		+	'\t\t\t\t<td class="change"><a href="removesong.php" class="removesong" id="song'+song.id+'">Remove</a></td>\r\n'				
		+	'\t\t\t</tr>\r\n';
}

function getNoSongsSelectedHTML()
{
	return "\t<p>You currently have no songs selected. Press the <strong>Add</strong> button next to a song to add it the list.</p>";
}

function removeSong(songId)
{
	$.get('control/updatekaraokeselection.php?mode=remove&songid='+songId, selectedSongListChanged);
}