﻿
var forms = function() 
{
	$( "form#storyFrom" ).submit(function() 
	{
		var formObj = this;
		var msgObj = $( this ).children( 'p.response' );

		var hasError = false;

		$.each( $( this ).children( '.required' ), function() 
		{
			if( $.trim( $( this ).children( ':input' ).val() ) == '' ) 
			{
				$( this ).addClass( 'warning' );
				hasError = true;
			}
			else
			{
				if( $( this ).hasClass( 'warning' ) )
					$( this ).removeClass( 'warning' );
			}
		});

		if(hasError) 
		{
			$( msgObj ).fadeIn( 300 ).html( '<b>Required entries were not typed in!</b>' );
			return false;
		}
		else
		{
			$( msgObj ).fadeIn( 300 ).html( '<b>Sending...</b><br />Please wait!' );

			var inputs = [];
			inputs.push( 'type=' + this.className );
			$( ':input', this ).each(function() 
			{
				if( this.type != 'radio' )
					inputs.push( this.name + '=' + escape( this.value ) );
			});

			if( $( "input[type=radio]:checked" ).val() != null )
				inputs.push( $( "input[type=radio]:checked" ).attr('name') + '=' + $( "input[type=radio]:checked" ).val() );

			jQuery.ajax(
			{
				url: 		this.action,
				type:		this.method,
				data: 		inputs.join('&'),
				dataType: 	"text",
				timeout: 	2000,
				error: function() 
				{
					$( msgObj ).fadeIn( 300 ).html( "<b>Error!</b><br />Try again, please..." );
				},
				success: function(data) 
				{
					$( msgObj ).fadeIn( 300 ).html( data );

					$.each( $( formObj ).children( '.item' ).children( ':input' ), function()
					{
						if( this.type != "submit" ) $( this ).val( '' );
					});
				}
			});

			return false;
		}
	});

};

$( window ).load( forms );
