﻿
(function($) {

	$.fn.forms = function( settings ) 
	{

		var formObj = this;
		var msgObj = $( this ).children( 'p.message' );
		
		$( this ).children( '.required' ).append( '<span>* required</span>' );


		$( this ).submit(function() 
		{
			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 ).html( 'OOps...<br/>Required entries were not typed in!' );
				return false;
			}
			else
			{
				$( msgObj ).addClass( 'loading' );
				$( msgObj ).html( 'Sending...<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,
					data: 		inputs.join('&'),
					dataType: 	"text",
					timeout: 	2000,
					error: function() 
					{
						$( msgObj ).removeClass( 'loading' );
						$( msgObj ).html( "Error!<br />Try again, please.." );
					},
					success: function(data) 
					{
						$( msgObj ).removeClass( 'loading' );
						$( msgObj ).html( data );
					}
				});

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

				return false;
			}
		});

	};

})(jQuery);
