var typed = {
	initForm: function() {
		$( "form#the-form" ).submit( function() {
			var form = $( this ), username = $( ":input#username" ), tweet = $( ":input#tweet" ), counter = $( ":input#counter" ), button = $( ":input[name=submit]", form ), loader = $( "img#loading" );
			
			if ( username.val().length == 0 ) {
				alert( "Oh, come on now. Tell us who you are!" );
				username.focus();
			} else if ( tweet.val().length == 0 ) {
				alert( "We're really looking forward to typing your tweet. We just need you to write a tweet first!" );
				tweet.focus();
			} else if ( counter.val() < 0 ) {
				alert( "We're sure it's a masterpiece, but your tweet is a little too long. Keep it under 140 characters, please!" );
				tweet.focus();
			} else {
				$.ajax({
					url: form.attr( "action" ),
					type: "POST",
					dataType: "json",
					data: form.serialize(),
					beforeSend: function() {
						button.attr( "disabled", "disabled" );
						loader.show();
					},
					success: function( rsp ) {
						if ( rsp.success ) {
							$( rsp.markup ).insertAfter( form ).submit();
						} else {
							loader.hide();
							button.removeAttr( "disabled" );
						}
					}
				});
			}
			
			return false;
		});
	},
	
	textarea: function() {
		var textarea = $( "textarea[data-maxlength]" ), maxlength = textarea.attr( "data-maxlength" ), counter = $( "div#count input" );
		
		textarea.keyup( function() {
			var currentlength = textarea.attr( "value" ).length;
			
			if ( currentlength > maxlength ) textarea.attr( "value", textarea.attr( "value" ).substring( 0, maxlength ) );
			else counter.attr( "value", parseInt( maxlength - currentlength ) );
		});
	}
};

$().ready( function() {
	typed.initForm();
	typed.textarea( $( "div#count input" ) );
	
	$( ":input[disabled]" ).removeAttr( "disabled" );
});
