(function($){

	jQuery.fn.createTwitterHeaderWidget = function(options) {
		// Set default arguments
		options = jQuery.extend({
			targets: new Array()
		}, options);

		// Make sure options.targets is an array
		if (!(options.targets instanceof Array))
		{
			options.targets = new Array();
		}

		// Start creating the widget
		this.each(function(){
			// DOM elements
			var container = jQuery(this);

			// Use ajax to pull in the template
			jQuery.get('widgets/TwitterHeaderWidget/jquery_template.html', function(result) { createWidget(result); });

			// Handles the creation of the widget html
			var createWidget = function(template) {
				// Insert the template html
				container.html(template);

				// Add events to buttons
				container.find('#twitter_login_button').click(login);
				container.find('#twitter_message_button').click(sendMessage);

				// Add events to text boxes (on enter being pressed)
				container.find('#twitter_password').keyup(function(event) { if (event.keyCode == 13) login(); });
				container.find('#twitter_message').keyup(function(event) { if (event.keyCode == 13) sendMessage(); });

				// Add focus detection to the input elements
				addFocusDetection(container.find('#twitter_username'));
				addFocusDetection(container.find('#twitter_password'));
				addFocusDetection(container.find('#twitter_message'));

				// Set the default status
				if (options.targets.length == 1)
				{
					displayStatusMessage(('Log into Twitter to tweet to ' + options.targets[0]), true);
				}

				// Set the text for posting a message
				if (options.targets.length == 1)
				{
					container.find('#twitter_message_label').html('Post to ' + options.targets[0] + ':');
				}
				else if (options.targets.length > 1)
				{
					// Multiple targets are available, so give a select drop-down
					container.find('#twitter_message_label').html('Post to <select id="twitter_tag_select"></select>:');

					// Add each option to the select
					for (var i = 0; i < options.targets.length; i++)
					{
						container.find('#twitter_tag_select').append('<option value="' + i + '">' + options.targets[i] +'</option>');
					}
				}

				// Update the max length of the message box, according to how long the hash tag is
				if (options.targets.length > 0)
				{
					container.find('#twitter_message').attr('maxlength', (140 - getLongestString(options.targets).length - 1));
				}

				// Add an input counter to the message box
				jQuery('#twitter_message').inputlimiter({
					limit: parseInt(container.find('#twitter_message').attr('maxlength')),
					remText: '%n character%s remaining...',
					limitTextShow: false,
					boxId: 'twitter_status',
					boxAttach: false,
					remTextHideOnBlur: false
				});
			}

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

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

				// Status message
				displayStatusMessage('Authenticating...', true);

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

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

						// Hide the login form, and display the message form
						container.find('#twitter_login_form').hide();
						container.find('#twitter_message_form').fadeIn(1000);
					},
					error: function()
					{
						displayStatusMessage('An error occured while authenticating');
					},
					dataType: 'json'
				});
			}

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

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

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

				// Status message
				displayStatusMessage('Posting tweet...', true);

				// Add the hashtag to the message if needed
				if (options.targets.length == 1)
				{
					message += (' ' + options.targets[0]);
				}
				else if (options.targets.length > 1)
				{
					message += (' ' + options.targets[container.find('#twitter_tag_select').val()]);
				}

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

			// Displays a message in the status box, but with a fancy fade-in
			var displayStatusMessage = function(message, no_fade) {
				if (no_fade == true)
				{
					// Don't fade in
					container.find('#twitter_status').html(message);
				}
				else
				{
					container.find('#twitter_status').hide();
					container.find('#twitter_status').html(message);
					container.find('#twitter_status').fadeIn(1000);
				}
			}

			// Adds a data element that indicates if the element currently has focus or not
			var addFocusDetection = function(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);
				});
			}

			// Finds the longest string in an array of strings, and returns it
			var getLongestString = function(strings) {
				var longest = strings[0];

				// Find the longest string
				for (var i = 0; i < strings.length; i++)
				{
					if (strings[i].length > longest.length)
					{
						longest = strings[i];
					}
				}

				return longest;
			}
		});
	};
})(jQuery);