$(document).ready(function(){

// Never cache song views, since it can sometimes load the whole template into the div
	$.ajaxSetup({
		cache: false
	});

//Admin functions
	// var url = $('div.media_admin').attr('href');
	// $('div.media_admin').media({
	// 	flashvars:{autoplay:false},
	// 	params:{ song_url: url }
	// });

//User-level functions

	$('div.audio').click(function(){
		if ($(this).hasClass('audio_on')) return false;
		var url = $(this).children("div.media").attr('href');  //get song url
		$("div.audio").removeClass('audio_on');
		$("div.media_on").remove();  //stop all audio, remove all players
		$("div.audio").children('img').show(); //show all icons
		$(this).prepend("<div class='media_on' href='"+url+"'></div>");  //add new player container
		$(this).children('img').hide(); //hide current icon

		$(this).addClass('audio_on');
		$(this).children('div.media_on').media({
			params:{ song_url: url }
		});
		var song_id = $(this).parents('.entry').attr('id').substring(5);
		$(this).parents('div.entry_wrap_top').click();
		playcounter(song_id);
		return false;
	});

	var song_arr = [];
	$(".voteinfo").children(".rank").children("span").each(function(){
		var song_position = $(this).html();  //get the id of the song (1-10)
		var song_file = song_arr[song_position-1];
		var song_id = $(this).parents('div.entry').attr('id').substring(5);
	});


	function load_song_info(song_id) {
		if(show_all_comments==1) { comments = "/comments:all"; }
		else if(show_all_comments == -1) { comments = "/comments:none"; }
		else { comments = ''; }
		$('#entries_right').empty();
		$('#entries_right').load('/songs/view/'+song_id+comments, null, function(){
			
		});
	}
	
	$("div.entry_wrap_top").click(function(){
		if(!$(this).hasClass('selected')){
			var song_id = $(this).find('.entry').attr('id').substring(5);
			load_song_info(song_id); // load song details into #entries_right
			$(".selected").removeClass('selected'); // deselect old entry
			$(this).addClass('selected');
		}
	});
	
	// track the number of times this song has been played
	// (don't bother trying to abuse this -- play count won't affect the outcome of the contest.)
	function playcounter(id){
		$.post( '/songs/playcount/'+id, {
			'data[Song][save]': true
		}) 
	}
	
	load_first_entry = setTimeout(function(){jQuery("div.entry_wrap_top:first").click()}, 2000);
});
