var tdEmail;
(function($) {
	// Provide a feedback message to the user
	$.fn.emailFeedback = function(options) {
		options = $.extend({color: 'red', message: '', fadeIn: 100, delay: 4250, fadeOut: 250}, options);
		return this.each(function() {
			$(this).stop(true)
			.css({'color' : options.color, 'opacity' : 'hide'})
			.text(options.message)
			.fadeTo(options.fadeIn, 1)
			// .delay(options.delay)
			.fadeTo(options.delay, 1)
			.fadeTo(options.fadeOut, 0);
		});
	};
	
	tdEmail = {
		submit : function() {
			// Get all form element data
			var post = {};
			$("#emailform form input").each(function() {
				post[$(this).attr('name')] = $(this).val();
			});

			// If our content hasn't changed, don't do anything
			if ( tdEmail.last == post['email'] || '' == post['email'] ) {
				return false;
			}
			tdEmail.last = post['email'];

			// Disable the form
			$("#emailform form").unbind('submit').submit(function() {
				return false;
			});

			// Display the spinner
			$("#emailform .email").addClass('spinner');

			// Submit the form
			$.ajax({
				type: "POST",
				url: window.tdLocal.ajaxurl,
				data: post,
				success: function(x) {
					if ( x == '1' ) {
						// Remove the spinner
						$("#emailform .email").removeClass('spinner');

						// Provide feedback
						$("#emailform .feedback").emailFeedback({color: 'green', message: 'Thank you!'});

						// Clear the form
						$("#emailform .email").val('');

						// Re-enable the form
						$("#emailform form").unbind('submit').submit(tdEmail.submit);

						return true;
					}
					else {
						this.error(x);
						return false;
					}
				},
				error: function(x) {
					// Remove the spinner
					$("#emailform .email").removeClass('spinner');
					
					// Provide feedback
					$("#emailform .feedback").emailFeedback({color: 'red', message: x})
					
					// Animate a "nuh-uh!"
					$("#emailform .input")
		                .animate({left: '-=8px'}, 100)
						.animate({left: '+=20px'}, 100)
		                .animate({left: '-=20px'}, 100)
						.animate({left: '+=8px'}, 100, 'swing', function() {
							// Re-enable the form in a callback, so it remains
							// disabled for the duration of the animation
							$("#emailform form").unbind('submit').submit(tdEmail.submit);
						});
						
					return false;
				}
			});
			return false;
		},
		
		// Most recently submitted e-mail address
		last : ''
	}
	
	$(document).ready(function() {
		// Attach click handler for e-mail form
		$("form a.submit").click(function() {
			$(this).closest("form").submit();
		});
	
		// Create a new feedback input
		$('<div class="feedback"></div>').appendTo("#emailform form").hide();
	
		// Bind actions to the submit button
		$("#emailform form").submit(tdEmail.submit);
	});
})(jQuery);
