;(function($) {
	$.fn.iPhorm = function(options) {
		return $(this).each(function() {
			var settings = {
				successRedirect: null
			}
			
			if (options) {
				$.extend(settings, options);
			}
			
			var $form = $(this);
			$form.submit(function(event) {
				// Insert the animated loading image to fade in after one second			
				var loadingTimeoutId = setTimeout(function() { $('.submit-button-wrapper .loading', $form).fadeIn('fast') }, 1);
				// Prevent the browser submitting the form normally
				event.preventDefault();
				// Bind the form submit to use the ajax form plugin
				$form.ajaxSubmit({
					async: false,
					dataType: 'json',
					data: { 'iphorm_submitted_by_js': 1 },
					iframe: true,
					success: function(response) {
						// Remove the animated loading image timeout and hide the image
						clearTimeout(loadingTimeoutId);
						$('.submit-button-wrapper .loading', $form).hide();
						// Check if the form submission was successful
						if (response.type == 'success') {
							if (typeof(settings.successRedirect) === 'string') {
								window.location = settings.successRedirect;
							}
							// Hide any tooltips
							$('.qtip').hide();
							// Fade out the form
							$('.iphorm-container', $form).fadeOut('fast').hide(0, function() {
								// Then fade in the success message
								$('.iphorm-message', $form).hide().html(response.data).fadeIn('fast');
							});
						} else if (response.type == 'message') {
							// Remove any previous errors from the DOM
							$('.form-errors', $form).remove();
							// Display the message
							$('.iphorm-message', $form).hide().html(response.data).fadeIn('fast');
						} else if (response.type == 'error') {
							// Remove any previous errors from the DOM
							$('.form-errors', $form).remove();
							// Go through each element containing errors					
							$.each(response.data, function(index, info) {
								// If there are errors for this element
								if (info.errors != undefined && info.errors.length > 0) {
									// Save a reference to this element									
									$element = $("[name='" + index + "']", $form);
									// If the returned element exists
									if ($element.size()) {
										// Create a blank error list
										var $errorList = $('<ul class="form-errors"></ul>');
										// Go through each error for this field
										$.each(info.errors, function(i, e) {
											// Append the error to the list as a list item
											$errorList.append('<li>' + e + '</li>');
											return false; // Just display one error per element
										});
										// Add the error list after the element's wrapper
										$element.last().parent().after($errorList);
									}
								}
							});
							// Fade all errors in
							$('.form-errors', $form).fadeIn(1);			
						}
					}
				}); // End ajaxSubmit()
			}); // End form.submit()
		}); // End this.each()
	};
})(jQuery);
