// The player.
var player = null;

// So the addListeners() function works.
function playerReady(thePlayer) {
	player = $(thePlayer.id);
	addListeners();
}

// So the stateListener() function works.
function addListeners() {
	if(player) player.addModelListener("STATE","stateListener");
	else setTimeout("addListeners()",100);
}

// Includes: IDLE, BUFFERING, PLAYING, PAUSED, and COMPLETED
function stateListener(obj) {

	// Keeps track of states.
	currentState = obj.newstate;
	previousState = obj.oldstate;
	
	// If the player wasn't playing previously.
	if(currentState=="PLAYING" && previousState!="PLAYING") {
		
		// Player must watch player_x for 10 seconds (where x is the entry ID).
		setTimeout("Contests.do_view("+obj.id.substr(7)+");",10000);
	}
}

// Contests functions.
var Contests = {

	// Shows the user information about the Elo Rating System.
	about_elo:function() {
		Container.show_alert('TalentTrove uses the Elo Rating System to calculate points during contest voting. You can read more about the Elo system on <a href="http://en.wikipedia.org/wiki/Elo_rating_system" target="_blank">Wikipedia</a>.','Elo Rating System');
	},
	
	// For admins to delete a contest.
	delete_contest:function(contest_id) {
		
		// You must specify a contest to delete.
		if(contest_id!=undefined && confirm('Are you sure you want to delete this contest?')) {
		
			// The Ajax.
			new Ajax.Request(engineURL, { method:'post',
				parameters:{ control:'contests', action:'delete_contest', contest_id:contest_id },
			onComplete:function(transport) {
				
				// Connection problem, most likely.
				if(transport.responseText=='') Contests.show_error();
				
				// If the user is not logged-in.
				else if(transport.responstText=='login') {
										
					// Will attempt to re-vote automatically following successful login.
					Container.task = "Container.hide_popup('popup_login');Contests.leave_feedback();";
					
					// Shows the "Login" pop-up container.
					Container.show_popup('login');
				}
				
				// If successful, refresh the "Browse Contests" container.
				else if(transport.responseText=='success') Container.refresh_container('browse_contests');
				
				// For some other error, shows an error message.
				else Contests.show_error(transport.responseText);
			}});
		}
	},
	
	// Returns true or false, depending on whether or not the entry has been viewed.
	did_view:function(entry_id) {
		
		// Returns false by default.
		var return_value = false;
		
		// Loops through the array of viewed entries.
		for(var counter=Contests.viewed.length-1; counter>=0; --counter) {
			
			// If the entry was viewed.
			if(Contests.viewed[counter]==entry_id) return_value = true;
		}
		
		// Returns true or false.
		return return_value;
	},
	
	// Keeps track of which entries the user has viewed.
	do_view:function(entry_id) {
		Contests.viewed[Contests.viewed.length] = entry_id;
	},

	// For voting, if it's a tie between two entries.
	draw:function(entry_1,entry_2) {
		
		// Uses the vote() function. True indicates it's a draw.
		Contests.vote(entry_1,entry_2,true);
	},

	// For admins to edit a contest.
	edit_contest:function(contest_id) {
		Container.show_popup('contests_admin',contest_id);
	},

	// Brings the user to the page of his/her highest rated entry.
	find_my_entry:function() {
		
		var container_id = 'contests_standings_'+Contests.get_contest_id();
		
		// The Ajax for the first container.
		new Ajax.Request(engineURL, { method:'post',
			parameters:{ control:'contests', action:'find_my_entry', contest_id:Contests.get_contest_id() },
		onComplete:function(transport) {
			
			// Connection problem, most likely.
			if(transport.responseText=='') Contests.show_error();
			
			// If the user was able to get a response.
			else {
				
				// Makes sure the page number is an integer.
				var page_number = parseInt(transport.responseText);
			
				// If the page number returned is 0, the entry was likely deleted.
				if(page_number==0) Contests.show_error('entryremoved');
			
				// If the was a page number returned, this will go to it.
				else Container.pagination(container_id,page_number-Container.pagination_page_number[Container.pagination_get_index(container_id)]);
			}
		}});
	},

	// Gets the ID of the current contest.
	get_contest_id:function() {
		return (Contests.contest_id==undefined ? 0 : Contests.contest_id);
	},
	
	// Similar to the "Leave Feedback" pop-up, except without the container.
	leave_feedback:function() {
		
		// The ID of the textbox that has the message in it.
		var textbox_id = 'contests_feedback_text';
		
		// Gets the text to leave as feedback.
		var text = ($(textbox_id) && !Container.lacks_value(textbox_id) ? $(textbox_id).value : '');
		
		// If the text wasn't entered.
		if(text=='') Contests.show_error('nofeedback');
		
		// If there was a message entered.
		else {
		
			// The Ajax for the first container.
			new Ajax.Request(engineURL, { method:'post',
				parameters:{ control:'container', action:'submit_form', type:'contests', to:Contests.get_contest_id(), popup_id:'feedback_leave', text:text },
			onComplete:function(transport) {
				
				// The user needs to be logged-in to vote.
				if(transport.responseText=='login') {
					
					// Will attempt to re-vote automatically following successful login.
					Container.task = "Container.hide_popup('popup_login');Contests.leave_feedback();";
					
					// Shows the "Login" pop-up container.
					Container.show_popup('login');
				}
				
				// Submitting feedback was successful.
				else if(transport.responseText=='success') {
					
					// Reloads the container.
					// This function is different from Contests.refresh_feedback(). It reloads the entire container, bringing the user back to the first page.
					Container.refresh_feedback();

					// For the focusing of the textbox, refer to the Container.refresh_container() function.
				}
				
				// If there's some other error, show an error message. Likely a connection problem.
				else Contests.show_error();
			}});
		}
		
		// Returns false.
		return false;
	},
	
	// Loads a new pair of entries for the user to vote on.
	load_new_faceoff:function() {
		
		// The Ajax for the first container.
		new Ajax.Request(engineURL, { method:'post',
			parameters:{ control:'contests', action:'get_faceoff', contest_id:Contests.get_contest_id() },
		onComplete:function(transport) {
			
			// Evaluates the JSON string.
			var json_object = eval("("+transport.responseText+")");
			
			// Reloads the containers.
			if($('entry_0')) $('entry_0').replace(json_object[0]);
			if($('entry_1')) $('entry_1').replace(json_object[1]);
		}});
	},
	
	// Refreshes the live feedback. Does not reload the container.
	refresh_feedback:function() {
		Container.pagination('feedback_contests_'+Contests.get_contest_id(),0);
	},
	
	// Refreshes the current_standings. Does not reload the container.
	refresh_standings:function() {
		Container.pagination('contests_standings_'+Contests.get_contest_id(),0);
	},
	
	// For admins to remove/verify entries.
	remove_verify:function(remove_verify,entry_id) {
		
		// Can only perform an action on a valid entry.
		if(entry_id!=undefined) {
			
			// If there's a problem with the variable, undo the action.
			if(remove_verify==undefined) remove_verify = 'undo';
			
			// The Ajax.
			new Ajax.Request(engineURL, { method:'post',
				parameters:{ control:'contests', action:'remove_verify', entry_id:entry_id, remove_verify:remove_verify },
			onComplete:function(transport) {
				$('admin_'+entry_id).replace(transport.responseText);
			}});
		}
	},
	
	// Shows contest-specified error messages.
	show_error:function(error_code) {
		
		// In case no error code was specified.
		if(error_code==undefined) error_code = false;
		
		// A default error message.
		var error_message = 'There was an error. Please try again later.';
		
		// The user is trying to do something only an admin can do.
		if(error_code=='admin') error_message = 'You are not allowed to do that because you are not an admin.';

		// The user is trying to submit the incorrect type of media.
		else if(error_code=='badtype') error_message = 'You are not allowed to submit this type of media to this contest.';

		// The user was trying to find his/her entry, but couldn't.
		else if(error_code=='entryremoved') error_message = 'Sorry, but we couldn\'t find your message. It was most likely removed by an administrator. If you believe this to be an error, please <a href="javascript:void(0);" onclick="Container.report_bug();">contact us</a>.';
		
		// The entry limit for this contest was exceeded.
		else if(error_code=='limit') error_message = 'Entry limit exceeded. To submit another entry, you must first remove one.';
		
		// The user is trying to do something that requires him/her to login.
		else if(error_code=='login') error_message = 'You must be logged-in to do that.';

		// The user is trying to submit feedback without typing anything.
		else if(error_code=='nofeedback') error_message = 'In order to submit feedback, you must first type something.';
		
		// The user is trying to vote without having viewed both entries.
		else if(error_code=='viewboth') error_message = 'You must view both entries in order to vote.';
		
		// The user is trying to vote, but voting is over.
		else if(error_code=='postvote') error_message = 'Sorry, but voting has ended for this contest.';
		
		// The user is trying to vote, but voting hasn't started yet.
		else if(error_code=='prevote') error_message = 'Sorry, but voting has not yet begun for this contest.';
		
		// Shows the error message to the user.
		Container.show_error(error_message,'popup_contests_submit');
	},
	
	// Submits an entry to or removes an entry from the contest.
	toggle_entry:function(media_id,contest_id,entry_limit) {
		
		// At the very least, the media ID and contest ID must be specified.
		if(media_id!=undefined && contest_id!=undefined) {
			
			// If there's no entry limit, assume the contest allows unlimited submissions.
			if(entry_limit==undefined) entry_limit = 0;
			
			// If the item has the classes, it must be currently submitted. That means the user is trying to remove the submission.
			var remove_entry = $('entry_'+media_id).hasClassName('on attn');
			
			// This determines what the total number of entries will be when the function completes.
			var entry_counter = (remove_entry ? 0 : 1);
			var other_entries = $('entry_'+media_id).siblings();
			for(var counter=other_entries.length-1; counter>=0; --counter) {
				if(other_entries[counter].hasClassName('on attn')) entry_counter++;
			}
			
			// Removing entries is always allowed, but adding is only allowed when the entry limit is unlimited or not exceeded.
			if(remove_entry || entry_limit==0 || entry_counter<=entry_limit) {
				
				// The Ajax.
				new Ajax.Request(engineURL, { method:'post',
					parameters:{ control:'contests', action:'toggle_entry', media_id:media_id, contest_id:contest_id, submit_remove:(remove_entry ? 'remove' : 'submit') },
				onComplete:function(transport) {
					
					// The submission or removal was successful.
					if(transport.responseText.substr(0,7)=='success') {
						
						// Updates the link text to reflect changes. This is so the user knows what future clicks of the link will do.
						$('submit_remove_'+media_id).update(remove_entry ? 'Submit to' : 'Remove from');
						
						// Shows a message to the user indicating that he/she has reached the submission limit.
						if(entry_counter==entry_limit && entry_limit>0) Container.show_info('You have submitted the maximum number of entries allowed for this contest.','popup_contests_submit');
						
						// Hides the entry limit error message, if it's being shown.
						else $('info_popup_contests_submit').hide();
						
						// Adds or removes the classes indicating submission.
						$('entry_'+media_id).toggleClassName('on attn');
						
						// Updates the submission counter.
						$('entry_counter_display').update(transport.responseText.substr(7));
					}
					
					// There was an error.
					else Contests.show_error(transport.responseText);
				}});
			}
			else Contests.show_error('limit');
		}
	},
	
	// For the user to vote between two entries.
	vote:function(winner_id,loser_id,is_draw) {
		
		// Variables to keep track of which entries were viewed.
		var viewed_winner = Contests.did_view(winner_id);
		var viewed_loser = Contests.did_view(loser_id);
		
		// If one of the two entries has not yet been viewed, voting will not be allowed.
		if(!viewed_winner || !viewed_loser) Contests.show_error('viewboth');
		
		// Makes sure both the winner and loser are specified.
		else if(winner_id!=undefined && loser_id!=undefined) {
			
			// If is_draw is undefined, assume that it is NOT a draw.
			if(is_draw==undefined) is_draw = false;
			
			// The Ajax.
			new Ajax.Request(engineURL, { method:'post',
				parameters:{ control:'contests', action:'vote', contest_id:Contests.get_contest_id(), winner_id:winner_id, loser_id:loser_id, is_draw:(is_draw ? '1' : '0') },
			onComplete:function(transport) {
				
				// The user needs to be logged-in to vote.
				if(transport.responseText=='login') {
					
					// Will attempt to re-vote automatically following successful login.
					Container.task = "Container.hide_popup('popup_login');Contests.vote("+winner_id+","+loser_id+","+is_draw+");";
					
					// Shows the "Login" pop-up container.
					Container.show_popup('login');
				}
				
				// If there's no error message or if the error message is related to not being in the voting stage, show an error message.
				else if(transport.responseText=='' || transport.responseText=='postvote' || transport.responseText=='prevote') Contests.show_error();
				
				// This loads a new faceoff. Does not show any possible error message so the user won't notice a thing.
				// For reference, possible error codes include:
				//   success => no error; voting was successful
				//   already => the user has already voted for this faceoff
				//   badentry => at least one of the entries was not valid
				//   self => the user is trying to vote for himself/herself
				else Contests.load_new_faceoff();
			}});
		}
	}
}

// An array of media files that have been viewed.
Contests.viewed = new Array();

// Refreshes the standings every 20 seconds. If live feedback was enabled, refresh_feedback() would be used also.
setInterval("Contests.refresh_standings();",20000);