function initRecalc() {
   // Get the value set in the form field.
	recalc_servings	= $("#recipe-recalc-form-input-recalc").val();
   recalc_servings   = parseFloat(recalc_servings);

	// Create new object to hold the data we need to update.
	var recalc_data	= {};

	// Get the ingredient wrapper.
  	$('.recipe-ingredients').find('.ingredient-block .ingredient-item').each(function (i) {

		// Array of Unit types that may need to be parsed more deeply.
		units_to_parse	= {
			'TEASPOON_US' 		: 'TEASPOON_US',
			'TABLESPOON_US' 	: 'TABLESPOON_US',
			'CUP_US' 			: 'CUP_US',
			'OUNCE_US' 			: 'OUNCE_US',
			'PINT_US' 			: 'PINT_US',
			'POUND' 				: 'POUND'
		};

      parse_units    = false;

		// Get the original quantity value, which is hidden.
		org_qty	= $(this).find('.ingredient-item-org_quantity').text();

		// Get the original serving value which is hidden.
		var org_servings 	= $('#org_servings').text();
		org_servings 	= parseFloat(org_servings);

		// Get the unit type.
		unit_system_name	= $(this).find('.ingredient-item-unit-system-name').text();
		org_unit_type  	= $(this).find('.ingredient-item-unit').text();
      org_unit_type  	= org_unit_type.toLowerCase();
		conversion_type	= $(this).find('.ingredient-item-unit-type').text();

		// If the unit is on the conversion list we need to set this flag to true to parse it.
		if (unit_system_name in units_to_parse) {
			parse_units	= true;
		}

		// Calculate the factor. ( Q/OS = F )
		factor	= (org_qty / org_servings);

		// Calculatee the new quantity. (F X S) = Q.
		new_qty	= (factor * recalc_servings);
      qty_obj  =  new Number(new_qty);    // Create number object to.
      qty_rnd  = qty_obj.toFixed(10);      // Obtain rounded to decimal.

		// Save the parsed data into an array for later.
		unit_data	= {
			'element': $(this).attr('id'),
			'measurement':qty_rnd,
			'conversion_type':conversion_type,
			'unit_system_name':unit_system_name
		};

		// Save this iteration in our data object.
		recalc_data[i]	= {'unit_data':unit_data };
	});

	updateUnits(recalc_data);
}

function updateUnits(recalc_data)
{

	var encoded_recipe_data = $.toJSON(recalc_data);
	request_url		= '/recipes/recalculate-units';

	// Start request now.
	try {

		// See if there is already an image set.
		if ($('.loading-image').html() != null){
			$('.loading-image').html('<img src="/assets/images/icons/loading.gif" />');
		}

		// Image doesn't exist so we'll append it to the submit element.
		else {
			$('#recipe-recalc-form-div-input-submit').append('<div class="loading-image"><img src="/assets/images/icons/loading.gif" /></div>');
		}

		// Fade in the new image, it is not displayed by default.
		$(".loading-image").fadeIn(1000);

		// Send reqeust to the controller to obtain the updated values.
		$.post(request_url, {'recalc_data' : encoded_recipe_data},
			function(data){
				replaceUnitContent(data);
			},
		"json");
	}

	// Uncomment for testing.
	catch (e) {
		 alert('Error: ' + e);
	}
}

function replaceUnitContent(unit_array)
{
	for (i = 0; i < unit_array.length; i++) {

		measurement				= null;
		measurement_decimal	= null;
		unit						= null;
		element					= null;

		// Check if this was a normal ingredient that has no units.
		if (unit_array[i].measurement) {
			measurement	= unit_array[i].measurement;
			element		= unit_array[i].element;
		}

		// Updated ingredient data.
		else if (unit_array[i].lowest_type) {
			measurement_decimal	= unit_array[i].lowest_type.decimal;
			measurement				= unit_array[i].lowest_type.fraction;
			element					= unit_array[i].lowest_type.element;

			// Determine if we need to make the unit plural.
			if (measurement_decimal > 1 && unit_array[i].lowest_type.unit_data.plural != '') {
				unit	= unit_array[i].lowest_type.unit_data.plural;
			}

			else if (unit_array[i].lowest_type.unit_data.name != '') {
				unit	= unit_array[i].lowest_type.unit_data.name;
			}

			else { alert(element); }
		}

      $("#" + element).animate({
         opacity: .1,
         fontSize:'20px'
      }, {queue:true, duration:200})
      .animate({
         opacity:1.0,
         fontSize:'11px'
      },500);

      if (measurement) {
	      $("#" + element).find('.ingredient-item-quantity_fraction').html(measurement + ' ');
   	}

      if (unit) {
      	$("#" + element).find('.ingredient-item-unit').text(unit + ' ');
      }
	}
	// Remove loading image.
	$(".loading-image").fadeOut(1000, function(){

		// Add the accepted icon.
		$(this).html('<img src="/assets/images/icons/accept.png" />');
		$(this).fadeIn(300);

		// Hide the icon after a moment.
		setTimeout(function() { $('.loading-image').fadeOut(300);}, 2000);
	});
}

function getRecalculatedData(element, measurement, conversion_type, unit_system_name)
{
	request_url		= '/recipes/get-unit-fraction/' + measurement + '/' + conversion_type + '/' + unit_system_name;

	$.getJSON(request_url,
		function(data) {

   		// Check if we need to parse the units.
   		if (parse_units) {
   			conversion_type	= 'volume'; // Hard coded for now. Might be updated upon a future release.

   			if (data.lowest_type != null){
   				// Update the fraction html.
   				$(element).find('.ingredient-item-quantity_fraction').html(data.lowest_type.fraction + ' ');

   				// Add in the correct unit type.
   				if (data.lowest_type.decimal > 1) {
   					$(element).find('.ingredient-item-unit').text(data.lowest_type.unit_data.plural + ' ');
   				} else {
   					$(element).find('.ingredient-item-unit').text(data.lowest_type.unit_data.name + ' ');
   				}
   	   	}

   		}
		}
	);
}
