jQuery( document ).ready( function() {
	
	if ( jQuery( '.iwacontact' ).length > 0 ) {
		
		jQuery( '.iwacontact' ).submit( function() {
			
			var currentForm = jQuery( this );
			
			currentForm.find( '.buttons .ajax-result' ).hide();
			currentForm.find( '.buttons .ajax-result' ).removeClass( 'error' );
			var validationError = 0;
			var firstError = 1;
			
			currentForm.find( ':input' ).each( function( i ) {
				
				jQuery( this ).removeClass( 'error' );
				jQuery( this ).parent().children( '.ajax-feedback' ).remove();
				
				if ( jQuery( this ).hasClass( 'required-field' ) && ( jQuery( this ).val() == '' || jQuery( this ).val() == null ) ) {
					validationError = 1;
					jQuery( this ).addClass( 'error' );
					jQuery( this ).after( '<span class="ajax-feedback error">This field is required</span>' );
					jQuery( this ).parent().children( '.ajax-feedback' ).fadeIn();
				}
				else if ( jQuery( this ).hasClass( 'validate-email' ) && !jQuery( this ).val().match( /^[A-Z0-9._%-]+@[A-Z0-9._%-]+.[A-Z]{2,4}$/i ) ) {
					validationError = 1;
					jQuery( this ).addClass( 'error' );
					jQuery( this ).after( '<span class="ajax-feedback error">Please enter a valid email address</span>' );
					jQuery( this ).parent().children( '.ajax-feedback' ).fadeIn();
				}
				
				if ( validationError && firstError ) {
					this.focus();
					firstError = 0;
				}
				
			} );
			
			if ( validationError ) {
				currentForm.find( '.buttons .ajax-result' ).addClass( 'error' );
				currentForm.find( '.buttons .ajax-result' ).html( "There was an error processing your request" );
				currentForm.find( '.buttons .ajax-result' ).fadeIn();
				return false;
			}
			
			currentForm.find( '.ajax-loading' ).show();
			
			var postData = currentForm.find( ':input').serialize();
			var submitURL = currentForm.attr( 'action' );
			
			jQuery.ajax( {
				type: "POST",
				url: submitURL,
				data: postData,
				complete: function( html ) {
					currentForm.find( '.ajax-loading' ).hide();
					currentForm.find( '.buttons .ajax-result' ).html( "Your message has been sent successfully!" );
					currentForm.find( '.buttons .ajax-result' ).fadeIn();
					currentForm.find( ':input' ).attr( 'disabled', 'disabled' );
					currentForm.find( '.buttons #submit' ).addClass( 'disabled' );
				}
			} );
			
			return false;
			
		} );
		
	}
	
} );
