//global var to keep track of if we've loaded the player yet (will be false until a playlist item is clicked)
var PLAYER_LOADED = false;

function player_init() {
	//attach playlist_item_click() to every li in uls with class="playlist"
	$$('ul.playlist li').each(function (item) {
		item.observe('click', playlist_item_click)
	});
	
	//attach playpause_clicked to our playpause link
	$('np_control_playpause').observe('click', playpause_clicked);
}

function playlist_item_click(event) {
	//if we haven't loaded the player yet, sub out the placeholder for the actual player
	if (PLAYER_LOADED == false) {
		$('now_playing_placeholder').hide();
		$('now_playing').show();
	}
	
	//what was clicked?
	var clicked = Event.element(event);
	var li =  clicked.up('li');
	if (li == null) return;
	
	//get the info for clicked song			
	var title			= li.down('.song_title').innerHTML;
	var url 			= li.down('.song_url').href;
	var cart_link = li.down('.song_cart_link').href;
	var notes 		= li.down('.song_notes').innerHTML;
	var lyrics 		= li.down('.lyrics').innerHTML;
	var album_link = li.up('.album_title').down('.album_url').href;
	
	//populate now playing section with this info
	$('np_title').innerHTML = title;
	$('button_add_song').writeAttribute('href', cart_link);
	$('button_add_album').writeAttribute('href', album_link);
	$('song_notes').innerHTML = notes;
	$('lyrics').innerHTML = lyrics;	
	
	
	//if we're alreadying playing a sound, we have to destroy 'now_playing' before we can play a new one
	soundManager.destroySound('now_playing');
	
	//play the song
	soundManager.play('now_playing', url);

	//make sure the pause control text is visible and play is hidden
	$('np_control_playpause_pause').show();	
	$('np_control_playpause_play').hide();

	//likewise, show the now playing text and hide the paused text
	$('np_status_playing').show();
	$('np_status_paused').hide();	
}

function playpause_clicked(event) {
	//what was clicked?
	var ele = Event.element(event);
	
	//toggle the sound
	soundManager.togglePause('now_playing');
	
	//toggle the displayed text
	$('np_control_playpause_play').toggle();
	$('np_control_playpause_pause').toggle();	
	
	//make sure we're showing the right now playing status message
	$('np_status_playing').toggle();
	$('np_status_paused').toggle();
}

// init our player once the dom is fully loaded
document.observe("dom:loaded", function() {
  player_init();
});
