/**
 * Author: Dennis Robinson
 * Date: November 20, 2009
 * Copyright: Mergenta (c) 2009
 *
 * jQuery functionality to login and post status updates to twitter.com
 */

// Anything in this function will execute when the page has loaded
$(document).ready(function()
{
	// Add events to buttons
	jQuery('#twitter_login_button').click(TwitterLogin);
	jQuery('#twitter_message_button').click(TwitterSendMessage);

	// Add events to text boxes
	jQuery('#twitter_password').keyup(function(event) {
		// Check if enter was pressed
		if (event.keyCode == 13)
		{
			TwitterLogin();
		}
	});
	jQuery('#twitter_message').keyup(function(event) {
		// Check if enter was pressed
		if (event.keyCode == 13)
		{
			TwitterSendMessage();
		}
	});

	// Add focus detection to the input elements
	TwitterAddFocusDetection(jQuery('#twitter_username'));
	TwitterAddFocusDetection(jQuery('#twitter_password'));
	TwitterAddFocusDetection(jQuery('#twitter_message'));

	// Set the default status
	jQuery('#status').html('Log into Twitter to tweet to ' + twitterHashTag);

	// Set the text for posting a message
	jQuery('#twitter_message_label').html('Post to ' + twitterHashTag + ':');

	// Update the max length of the message box, according to how long the hash tag is
	jQuery('#twitter_message').attr('maxlength', (140 - twitterHashTag.length - 1));

	// Add an input counter to the message box
	jQuery('#twitter_message').inputlimiter({
		limit: (140 - twitterHashTag.length - 1),
		remText: '%n character%s remaining...',
		limitTextShow: false,
		boxId: 'status',
		boxAttach: false,
		remTextHideOnBlur: false
	});
});

// Adds a data element that indicates if the element currently has focus or not
function TwitterAddFocusDetection(element)
{
	// Add the boolean flag
	element.data('hasFocus', false);

	// Add the focus event handlers
	element.focus(function() {
		$(this).data('hasFocus', true);
	});

	element.blur(function() {
		$(this).data('hasFocus', false);
	});
}

// Displays a message in the status box, but with a fancy fade-in
function TwitterDisplayStatusMessage(message)
{
	jQuery('#status').hide();
	jQuery('#status').html(message);
	jQuery('#status').fadeIn(1000);
}

// Handles the login request to Twitter
function TwitterLogin()
{
	var username = jQuery('#twitter_username').val();
	var password = jQuery('#twitter_password').val();

	// Make sure a username and password was provided
	if (username == "" || password == "")
	{
		TwitterDisplayStatusMessage('Please enter a username and password');
		return;
	}

	// Status message
	// Don't fade in this message, or it wont be seen
	jQuery('#status').html('Authenticating...');

	// Query the twitter server to verify the user's credentials
	jQuery.ajax({
		type:'POST',
		cache:false,
		data:{ 'username':username, 'password':password },
		url:('twitter/api_login.php'),
		success:function(response, status)
		{
			if (response.error != null)
			{
				// Invalid login
				TwitterDisplayStatusMessage('Invalid username or password');
				return;
			}

			// Display a success message
			TwitterDisplayStatusMessage('Login successful');

			// Hide the login form, and display the message form
			jQuery('#login-form').hide();
			jQuery('#message-form').fadeIn(1000);
		},
		error:function()
		{
			TwitterDisplayStatusMessage('An error occured while authenticating');
		},
		dataType:'json'
	});
}

// Handles the status update request to Twitter
function TwitterSendMessage()
{
	var username = jQuery('#twitter_username').val();
	var password = jQuery('#twitter_password').val();
	var message = jQuery('#twitter_message').val();

	// Make sure a username and password was provided
	if (username == "" || password == "")
	{
		TwitterDisplayStatusMessage('Please enter a username and password');
		return;
	}

	// Make sure a message was provided
	if (message == "")
	{
		TwitterDisplayStatusMessage('Please enter a message to tweet');
		return;
	}

	// Status message
	jQuery('#status').html('Posting tweet...');

	// Add the hashtag to the message
	message += (' ' + twitterHashTag);

	// Query the twitter server to update the user's status
	jQuery.ajax({
		type:'POST',
		cache:false,
		data:{ 'username':username, 'password':password, 'message':message },
		url:('twitter/api_sendmessage.php'),
		success:function(response)
		{
			// Display a success message
			TwitterDisplayStatusMessage('Tweet posted successfully');
			jQuery('#twitter_message').val('');
		},
		error:function()
		{
			TwitterDisplayStatusMessage('An error occured while posting your tweet');
		},
		dataType:'json'
	});
}