
//Make sure messaging.js is loaded first!

//global handles
var word_input;
var word_submit;
var chat_input;
var chat_submit;
var chat_message_area;

//special object for the chat scrolling
var obj_chat_scroll;


// Set up our ui event handlers when the dom is ready for observation
jQuery(document).ready(function(){
  //observe the word input 	
	jQuery('#WordForm').submit(WordSubmitted);
	
	//observe the chat input
	jQuery('#ChatForm').submit(ChatSubmitted);
        
	//observe the buttons for leaving the game
  jQuery('#LeaveSubmit').click(PlayerWantsToLeave);
	
	//observe if the player wants to change his/her handle
	jQuery('#PlayerHandleSubmit').click(PlayerWantsToChangeHandle);
	
	//observe if the player wants to change his/her handle change attempt
	jQuery('#PlayerHandleCancel').click(PlayerWantsToCancelHandleChange);

	//set some helpful handles for functions to use
	word_input = jQuery('#WordInput');
	word_submit = jQuery('#WordSubmit');
	
	chat_input = jQuery('#ChatInput');	
	chat_submit = jQuery('#ChatSubmit');
        
  chat_message_area = jQuery('#ChatMessages ul');
  
  //setting the chat div for scrolling
  obj_chat_scroll = new chatscroll.Pane('ChatMessages');
});


/* =========================================================================================
 		UI Event Handlers
   =======================================================================================*/
function WordSubmitted(event) {
	if (word_input.val() != '') {
		AddMessageToQueue(MessageType.CLI_WordSubmit, word_input.val());
		word_input.attr('disabled', 'disabled');
		word_submit.attr('disabled', 'disabled');
	}

	event.preventDefault();		
	return false;	
}

function ChatSubmitted(event) {
	if (chat_input.val() != '') {
		AddMessageToQueue(MessageType.CLI_ChatSubmit, chat_input.val());
		chat_input.val('');
		chat_input.focus();
	}

	event.preventDefault();	
	return false;	
}

function PlayerWantsToLeave(event){
        if(confirm("Are you sure you want to leave?"))
        {
          SendWithoutQueue(MessageType.CLI_UserLeave, 'bye', function(){ window.location = '/'; })
        }
	event.preventDefault();	
	return false;
}

function PlayerWantsToChangeHandle(event){
	var newName = jQuery('#PlayerHandleInput').val();
	if (newName != ''){
		
		AddMessageToQueue(MessageType.CLI_UserHandleChange, newName);

		//We'll assume that the user was able to change handles
		//Must fix before we start creating persistant accounts

		jQuery('#PlayerHandle').html(newName);
	}
	HidePlayerEditHandle();
	event.preventDefault();
	return false;
}


function PlayerWantsToCancelHandleChange(event){
	HidePlayerEditHandle();
	event.preventDefault();
	return false;
}

function ShowPlayerEditHanlde(){
	
	jQuery('#MyPlayerContols').hide();
        jQuery('#ChangePlayerInfo').fadeIn();
        jQuery('#PlayerHandleInput').focus();
}

function HidePlayerEditHandle(){
	jQuery('#ChangePlayerInfo').hide();
	jQuery('#PlayerHandleInput').html("");
	jQuery('#MyPlayerContols').fadeIn();
}

function ToggleSelectInviteURL(){
  var invTbx = jQuery('#InviteFriendURL');
  if (invTbx.is(':hidden'))
  {
    invTbx.val(location.href);
    invTbx.fadeIn();
    invTbx.select();
  }
  else
  {
    invTbx.fadeOut();
  }
}
/* =========================================================================================
 		Message Handlers
   =======================================================================================*/
function Handle_SRV_ChatSent(message) {
	//add new list item to chat messages
	jQuery('#ChatMessages ul').append('<li><span class="Player">' + message.user_handle + ': </span>' + message.data + '</li>');

	PlayChat();	
}

/*===== Round Area UI Updates =====*/

function Handle_SRV_0Words(message) {
	word_input.removeAttr('disabled');
}

function Handle_SRV_1Word (message) {
	jQuery('#GameNotifcations SPAN:visible').hide();
        
	//alert('message-id:'+message.user_id+'/n my id:'+jQuery('#PlayerId').val());

	if (message.user_id == jQuery('#PlayerId').val())
	{
	  jQuery('#UserSubmittedWord').slideDown();
	}
	else
	{
	  jQuery('#1Word').slideDown();
	}

	jQuery('#NextGameForm').fadeOut("slow");
}

function Handle_SRV_2Words (message) {
  //The server has received 2 words.  It's going to send them down to the client because they don't match!'		

	//Show proper gamestate notification
	jQuery('#GameNotifcations SPAN:visible').hide();
	jQuery('#2Words').slideDown();
		
	//re-enable word inout in case it was disabled by a submit
	word_input.val('');
	word_input.removeAttr('disabled');
	word_submit.removeAttr('disabled');
				
	//if we have a word pair (ie not the beginning the room), slot the existing word pair into the history item html to be added
	if (jQuery('#RoundHistory ul li.current').length != 0) {
		var old_player_a 	= jQuery('#RoundHistory ul li.current div.PlayerA div.UserInfo').html(); 			//jQuery('#FirstWord_PlayerAHandle').html();
		var old_player_b 	= jQuery('#RoundHistory ul li.current div.PlayerB div.UserInfo').html(); 			//jQuery('#SecondWord_PlayerBHandle').html();
		var old_word_a 		= jQuery('#RoundHistory ul li.current div.PlayerA div.SubmittedWord').html(); 	//jQuery('#FirstWord').html();
		var old_word_b 		= jQuery('#RoundHistory ul li.current div.PlayerB div.SubmittedWord').html(); 	//jQuery('#SecondWord').html();	
	
		var new_history_item_html = jQuery('#RoundHistoryTemplate').html();
		var tmpl = new Template(new_history_item_html);	
		var data = {player_a_handle: old_player_a, player_a_word: old_word_a, player_b_handle: old_player_b, player_b_word: old_word_b}
		new_history_item_html = tmpl.evaluate(data);
	
		//now put the existing word pair html into the history list
		//TODO: clean these effects up
		jQuery('#RoundHistory ul li.current').after('<li id="LatestRoundHistory" style="display: none;">' + new_history_item_html + '</li>');

		//set the alt class for zebra striping		
		var most_recent_old_item = 		jQuery('#RoundHistory ul li:visible:not(.current)');
		if (most_recent_old_item.attr('class') != 'alt') {
			jQuery('#LatestRoundHistory').addClass('alt');
		}
		
		//get the data out of our message
		var bits 			= message.data.split('|');
		var new_player_a 	= bits[0];
		var new_word_a 		= bits[1];
		var new_player_b 	= bits[2];
		var new_word_b 		= bits[3];

		//update the current words
		setCurrentWords(new_player_a, new_word_a, new_player_b, new_word_b);
	}
	else {		
		//get the data out of our message
		var bits 			= message.data.split('|');
		var new_player_a 	= bits[0];
		var new_word_a 		= bits[1];
		var new_player_b 	= bits[2];
		var new_word_b 		= bits[3];

		//do the insertion of the words in the beginning of the list
		var new_history_item_html = jQuery('#RoundHistoryTemplate').html();
		var tmpl = new Template(new_history_item_html);	
		var data = {player_a_handle: new_player_a, player_a_word: new_word_a, player_b_handle: new_player_b, player_b_word: new_word_b}
		new_history_item_html = tmpl.evaluate(data);

		jQuery('#RoundHistory ul').append('<li id="LatestRoundHistory" class="current" style="display: none;">' + new_history_item_html + '</li>');		
	}

	//jQuery('#RoundHistory ul li.current').fadeOut("slow", function() {		
		jQuery('#LatestRoundHistory').slideDown("slow");
//		jQuery('#LatestRoundHistory').attr(id, )
	//});	
	jQuery('#LatestRoundHistory').removeAttr('id');

	PlayNewWords();
}

function Handle_SRV_Victory(message) {
	//The server has received 2 words.  They match! Game ends'

	//get the data out of our message
	var bits			 				= message.data.split('|');
	var winning_player_a 	= bits[0];
	var winning_player_b 	= bits[1];
	var winning_word 			= bits[2];

	//pick random victory exclamation
	var exclamations = ['Yay', 'Woot', 'Awesome', 'Nice', 'Congrats'];
	var rand = Math.floor(Math.random()*exclamations.length);// + 1) // get random number between 0 and exclamations.length

	//update victory info
	var victory_html = jQuery('#GameVictory').html();
	var tmpl = new Template(victory_html);
	var data = {exclamation: exclamations[rand], player_a: winning_player_a, player_b: winning_player_b, word: winning_word}
	jQuery('#GameVictory').html(tmpl.evaluate(data));
		
	//show game victory
	jQuery('#GameNotifcations SPAN').hide();
	$$('#GameNotifcations span').each(function(i){ i.hide(); });
	        
  //Now hide the input form and display the 'ready for next game' / 'leave game' options
  //jQuery('#WordForm').hide();
  
		
	//get last pre-winning word pair into history
	var old_player_a 	= jQuery('#RoundHistory ul li.current div.PlayerA div.UserInfo').html(); 			//jQuery('#FirstWord_PlayerAHandle').html();
	var old_player_b 	= jQuery('#RoundHistory ul li.current div.PlayerB div.UserInfo').html(); 			//jQuery('#SecondWord_PlayerBHandle').html();
	var old_word_a 		= jQuery('#RoundHistory ul li.current div.PlayerA div.SubmittedWord').html(); 	//jQuery('#FirstWord').html();
	var old_word_b 		= jQuery('#RoundHistory ul li.current div.PlayerB div.SubmittedWord').html(); 	//jQuery('#SecondWord').html();	

	var new_history_item_html = jQuery('#RoundHistoryTemplate').html();
	var tmpl = new Template(new_history_item_html);	
	var data = {player_a_handle: old_player_a, player_a_word: old_word_a, player_b_handle: old_player_b, player_b_word: old_word_b}
	new_history_item_html = tmpl.evaluate(data);

	//now put the existing word pair html into the history list
	//TODO: clean these effects up
	jQuery('#RoundHistory ul li.current').after('<li id="LatestRoundHistory" style="display: none;">' + new_history_item_html + '</li>');
	jQuery('#RoundHistory ul li.current').after('<li id="LatestRoundHistory" style="display: none;">' + new_history_item_html + '</li>');
	jQuery('#LatestRoundHistory').slideDown("slow").removeAttr("id");
	jQuery(':disabled').removeAttr('disabled').val('');
	setCurrentWords(winning_player_a, winning_word, winning_player_b, winning_word);

	//take current and put it in history, then set continue message as current
/*	var current_html = jQuery('#RoundHistory ul li.current').html();
	jQuery('#RoundHistory ul li.current').after('<li id="old_current" style="display: none;">' + current_html + '</li>');	
	jQuery('#old_current').slideDown("slow");
	jQuery('#old_current').removeAttr('id');
			
	//Add a copy of the RoundDoneTemplate and let players enter new words to start a new round
	var keep_playing_html = jQuery('#RoundDoneTemplate').html();
	jQuery('#RoundHistory ul li.current').after('<li id="VictoryNotice" style="display: none;">' + keep_playing_html + '</li>');	
	jQuery('#VictoryNotice').slideDown("slow");
	jQuery('#VictoryNotice').addClass('current');
	jQuery('#VictoryNotice').removeAttr('id');
	
	//don't forget to hide the current and re-enable the word form input
	//jQuery('#RoundHistory ul li.current').hide();
	//jQuery('#RoundHistory ul li.current:not(#VictoryNotice)').remove();

*/


	PlayVictory();
	if (LAST_MESSAGE_ID != 0) { jQuery('#NextGameForm').fadeIn("slow"); }
}

/*===== Other game updates =====*/
function Handle_SRV_ChatSent(message) {
	//add new list item to chat messages
        addMessageToChat('<li><span class="Player">' + message.user_handle + ': </span>' + message.data + '</li>');
}

function Handle_SRV_UserLeft(message) {
        //Add notifcation to the chat area
	addMessageToChat('<li><span class="System">' + message.user_handle + ' has left the room.</span></li>');		
        
        //Remove the user from the current player list
        jQuery('#OtherPlayers').remove('li[value='+message.user_id+']');

				PlayGoodbye();
}

function Handle_SRV_UserJoined(message) {
        //Add a notifcation to the chat area
				addMessageToChat('<li><span class="System">' + message.user_handle + ' has joined the room.</span></li>');	
        
        //If it's not us, update the players list
        if (message.user_id != jQuery('#PlayerId').val())
        {
          jQuery('#OtherPlayers ul').append('<li value='+message.user_id+'>'+message.user_handle+';</li>');
        }

				//PlayHello();
}

function Handle_SRV_UserHandleChanged(message) {
        //Add a notifcation to the chat area
				addMessageToChat('<li><span class="System">' + message.data + ' is now known as ' + message.user_handle + '</span> </li>');
        
        //If it's not the current player, update the name in the player list area
        if (message.user_id != jQuery('#PlayerId').val())
        {
          jQuery('#OtherPlayers li[value='+message.user_id+']').html(message.user_handle+';');
        }
}


/* =========================================================================================
 		Helpers
   =======================================================================================*/
function setCurrentWords(player_a, word_a, player_b, word_b) {
	if (typeof word_b == 'undefined') {
		word_b = word_a
	}
	jQuery('#RoundHistory ul li.current div.PlayerA div.SubmittedWord').html(word_a);
	jQuery('#RoundHistory ul li.current div.PlayerA div.UserInfo').html(player_a);
	jQuery('#RoundHistory ul li.current div.PlayerB div.SubmittedWord').html(word_b);
	jQuery('#RoundHistory ul li.current div.PlayerB div.UserInfo').html(player_b);		
}

function addMessageToChat(NewMsg)
{
  chat_message_area.append(NewMsg);
  obj_chat_scroll.activeScroll();
}
