// Begin - Class Check - Check to see if browser supports grabbing data by class.
// If not then use this function to make it happen.
onload=function(){
	if (typeof document.forms['calorieCalc'] != 'undefined')
	{

	 calorieCalc.reset();
	if (document.getElementsByClassName == undefined) {
		document.getElementsByClassName = function(className)
		{
			var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
			var allElements = document.getElementsByTagName("*");
			var results = [];
	
			var element;
			for (var i = 0; (element = allElements[i]) != null; i++) {
				var elementClass = element.className;
				if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
					results.push(element);
			}
			return results;
		}
	}
	}
}
// End - Class Check

var count = 1;
$(function(){
    $('p#add_field').click(function(){
        count += 1;
		for (var j=0; j<count; j++) {
			$('input[name$=ing' + (j + 1) + 'PercTotal]').val(Math.floor(100/count));
		};
        $('#container').append(
			'<div class="ingRow">'
				+'<div class="ingnamediv"><input name="ing' + count + 'Name" type="text"'
				+'onkeyup="buildAutoSuggest(event, \'ing' + count + 'Nameid\')" '
				+'onKeyDown="return disableEnterKey(event)" class="ingname" id="ing' + count + 'Nameid" /></div>'
				+'<div class="ingitemdiv"><input name="ing' + count + 'Grams" type="text" class="ing" id="ing' + count + 'Gramsid" /></div>' 
				+'<div class="ingitemdiv"><input name="ing' + count + 'Calories" type="text" class="ing" id="ing' + count + 'Caloriesid" /></div>'
				+'<div class="ingitemdiv"><input name="ing' + count + 'PercTotal" type="text" class="ing" value="' 
			+ (Math.floor(100/count)) + '" /></div>'
			+'</div>');
		$('#container2').append(
			'<div class="recRow">'
				+'<div id="rec' + count + 'Name" class="recnamediv"></div>' 
				+'<div  id="rec' + count + 'Grams" class="recitemdiv"></div>' 
				+'<div  id="rec' + count + 'Calories" class="recitemdiv"></div>'
				+'<div  id="rec' + count + 'PercTotal" class="recitemdiv"></div>'
			+'</div>'); 
    });
});

$(function(){
    $('p#remove_field').click(function(){
		var count = 1;
		location.reload();
    });
	
});

function ingredient(name, grams, units, calories, percTotal) {
//	alert("function ingredient");
	this.name = name;
	this.grams = grams;
	this.units = units;
	this.calories = calories;
	this.percTotal = percTotal;
}

function calcGrams(rawIngredient, targetCalories) {
	var resultGrams = Math.round(((rawIngredient.grams*((targetCalories/100)*rawIngredient.percTotal)))/rawIngredient.calories*10)/10;
	return resultGrams;
}

function calcUnits(rawIngredient) {
	var resultUnits = Math.floor((rawIngredient.units*rawIngredient.resultGrams)/rawIngredient.grams);
	return resultUnits;
}

function calcCalories(rawIngredient) {
	var resultCalories = Math.ceil((rawIngredient.calories*rawIngredient.resultGrams)/rawIngredient.grams);
	return resultCalories;
}

function getData() {
	// Loop for each ingredient and get the associated user entered form values
	theForm=document.calorieCalc;

	var addIngredient = new Array();
	for (var j=0; j<count; j++) {
		addIngredient[j] = new ingredient(
				$('[name=ing'+(j+1)+'Name]').val(), 
				$('[name=ing'+(j+1)+'Grams]').val(), 
				$('[name=ing'+(j+1)+'Units]').val(), 
				$('[name=ing'+(j+1)+'Calories]').val(), 
				$('[name=ing'+(j+1)+'PercTotal]').val());
 	}
	var totalPerc = 0;
	var l = 0;
	for (var l=0; l<count; l++) {
		var newGrams = calcGrams(addIngredient[l], document.calorieCalc.targetCalories.value);
		addIngredient[l].resultGrams = newGrams;
		var newUnits = calcUnits(addIngredient[l]);
		addIngredient[l].resultUnits = newUnits;
		var newCalories = calcCalories(addIngredient[l]);
		addIngredient[l].resultCalories = newCalories;
		totalPerc = totalPerc + parseInt(addIngredient[l].percTotal); 
	}


	if (totalPerc > 100 || totalPerc < 95 ) {
		alert("The sum of the % Total Calories for all ingredients must equal 100%");
		} else {
			// Send recipe data to recipe fields	
			for (var n=0; n<count; n++) {
				if (addIngredient[n].name.length == 0 || addIngredient[n].name == 'Enter Ingredient Here!') {
					$('#rec'+(n+1)+'Name').html('Error - Please fill in all fields above.');
				}
				else
				{
					$('#rec'+(n+1)+'Name').html(addIngredient[n].name);
					$('#rec'+(n+1)+'Grams').html(addIngredient[n].resultGrams);
					// Using percent total below cheats the system to always add up to the total
					$('#rec'+(n+1)+'Calories').html(Math.floor(document.calorieCalc.targetCalories.value/count));
					// $('#rec'+(n+1)+'Calories').html(addIngredient[n].resultCalories);
					$('#rec'+(n+1)+'PercTotal').html(addIngredient[n].percTotal);
				}
			}
		}
}

function clearMe(formfield){
  if (formfield.defaultValue==formfield.value)
   formfield.value = ""
 }




