jQuery(function($) {
	$('form.ingredientsForm.ajax').each(function() {

		var form = $(this),
			url = form.find('input:nth-child(1)').val(),
			data = $.parseJSON(form.find('input:nth-child(2)').val()),
			submitButton = form.find('input[type=submit],button'),
			loader = form.find('img.ajaxLoader'),
			formCss = form.attr('class');

		form.ajaxForm({
			url:url,
			data:data,
			dataType:'json',
			beforeSubmit:function() {
				submitButton.attr('disabled', true);
				loader.fadeIn();
			},
			success:function(json, status, xhr, $form) {
				submitButton.attr('disabled', false);
				loader.fadeOut();

				// Set the form class
				if (json.css) {
					$form.attr('class', json.css);
				}

				// Remove old message if it exists and replace with new
				$form.find('span.ajaxMessageContainer').remove();
				$form.prepend('<span class="ajaxMessageContainer">' + json.message + '</span>');

				// Prep the errors for the fields
				if (json.fields) {
					$.each(json.fields, function(key, data) {
						var field = $('#formField_' + key);
						field.attr('class', data.css);
						field.find('.formHint').html(data.hint);
					});
				}

				if (json.redirect) {
					var count = 3;
					setInterval(function() {
						count--;
						if (count == 0) {
							document.location = json.redirect;
						}
					}, 1000);
				} else if (json.reset) {
					$form.resetForm();
					setTimeout(function() {
						$form.find('span.ajaxMessageContainer').fadeOut('slow', function(){
							$(this).remove();
							$form.attr('class', formCss);
						})
					}, 3000);
				}

				$('html, body').animate({
					scrollTop: $('span.ajaxMessageContainer').offset().top
				}, 500);
			}
		});
	});

});

