// Copyright 2010 Keri Glassman LLC, All Rights Reserved

function initCalculator() {
	addNewFoodRow();
	initFoodSelectionEvents(1);	//Change handling for the first food row
	toggleSpinner('off');
}

var foodRowCounter = 0;
function addNewFoodRow() {
	
	foodRowCounter++;
	
	// Clone each element of a row and assign it an id that includes its row num (defined by foodRowCounter)
	var delete_img = $('delete_x').cloneNode(true);
	delete_img.id = ('delete_' + foodRowCounter);
	var category = $('category_x').cloneNode(true);
	category.id = 'category_' + foodRowCounter;
	var food = $('food_x').cloneNode(true);
	food.id = 'food_' + foodRowCounter;
	var serving = $('serving_x').cloneNode(true);
	serving.id = 'serving_' + foodRowCounter;
	var orac = $('orac_div_x').cloneNode(true);
	orac.id = 'orac_div_' + foodRowCounter;
	
	// Create a div container for the row and write all the elements into it
	var row = document.createElement('div');
	row.id = 'row_' + foodRowCounter;
	if (foodRowCounter != 1) {
		// Don't allow the first row to be deleted
		delete_img.style.visibility = "visible";
	}
	row.appendChild(delete_img);
	row.appendChild(category);
	row.appendChild(food);
	row.appendChild(serving);
	row.appendChild(orac);
	
	// Get the location to add the row and add it
	writeRoot = $('write_root');
	writeRoot.appendChild(row);
	
	// Wire up the selection events for the new row
	initFoodSelectionEvents(foodRowCounter);
	
	// Force category to its initial value (for FF)
	category[0].selected = true;

	// Make the food category visible
	category.style.display = 'inline';

}

function deleteFoodRow(num) {
	$('delete_' + num).stopObserving();
	$('category_' + num).stopObserving();
	$('food_' + num).stopObserving();
	$('serving_' + num).stopObserving();
	$('row_' + num).remove();
	displayOracTotal();
}

// Observe changes on all 3 dropdowns for the food row (identified by num)
function initFoodSelectionEvents(num) {
	Event.observe('category_'+num, 'change', function(event) {change_category(num)});
	Event.observe('food_'+num, 'change', function(event) {change_food(num)});
	Event.observe('serving_'+num, 'change', function(event) {change_serving(num)});
	Event.observe('delete_'+num, 'click', function(event) {deleteFoodRow(num)});
}

// Handle the change of the food category for the food row (identified by num)
function change_category(num) {
	var category = $('category_' + num); 
	if (category.value.strip() != 'Choose a food category') {
		// Get the value for food items from the server
		fillSelections(num, category.value);
	} else {
		$('food_' + num).style.display = 'none';
	}
	$('serving_' + num).style.display = 'none';
	$('orac_div_' + num).style.display = 'none';
	// Show the total ORAC value
	displayOracTotal();
}

// Handle the change of the food item for the food row (identified by num)
function change_food(num) {
	var food = $('food_' + num);
	// Make sure the food drop down is actually visible before processing a change
	if (food.style.display != 'none') {
		if (food.value.strip() != 'Choose a food item') {
			// Get the value for servings from the server
			var category = $('category_' + num); 
			fillSelections(num, category.value, food.value);
		} else {
			$('serving_' + num).style.display = 'none';
		}
		$('orac_div_' + num).style.display = 'none';
		// Show the total ORAC value
		displayOracTotal();
	}
}

// Handle the change of the serving size for the food row (identified by num)
function change_serving(num) {
	var serving = $('serving_' + num);
	// Make sure the serving drop down is actually visible before processing a change
	if (serving.style.display != 'none') {
		if (serving.value.strip() != 0) {
			// Get the ORAC value from the server
			var category = $('category_' + num); 
			var food = $('food_' + num);
			fillSelections(num, category.value, food.value, serving.value);
		} else {
			// Hide the ORAC
			$('orac_div_' + num).style.display = 'none';
			// Show the total ORAC value
			displayOracTotal();
		}
	}
}

// AJAX request to the server with whatever values the user has filled in for the food row (identified by num)
function fillSelections(num, category, food, serving) {
	// Build up a URL with whatever items the user has selected already for this row (identified by num)
	var url = "chain.php?category=" + escape(category);
	if (food != undefined) {
		url += "&food=" + escape(food);
		if (serving != undefined) {
			url += "&serving=" + escape(serving);
		}
	}
	// Go to the server to get the data
	toggleSpinner('on');
	new Ajax.Request(url, {onSuccess: function(response) {
		 if ((response.getHeader('Server') || '').match(/Apache/)) {
		 	// Deal with the server's response
		 	parseServerResponse(num, response);
		 } else {
		 	// Header is null, No love
		 	serverResponseError(response);
		 }
		toggleSpinner('off');
	}, onFailure: function(response) {	toggleSpinner('off');serverResponseError(response);}});
}

function serverResponseError(response) {
	alert('Problem connecting to the Nutritious Life server. Please try again later.');
}

function toggleSpinner(onOff) {
	if (onOff == 'on') {
		$('spinner').style.display = 'inline';
	} else {
		$('spinner').style.display = 'none';
	}
}

// Process the text coming back from the AJAX request (served by PHP)
function parseServerResponse(num, response) {
	
	var response = response.responseText;

	// Get the UI elements for this food row (identified by num)
	var foodList = $('food_' + num);
	var servingList = $('serving_' + num);
	var oracDiv = $('orac_div_' + num);
	var oracSpan = $$('#orac_div_' + num + ' .orac_span')[0];
	
	// Parse the PHP response into its 3 parts (food, servings, orac)
	// These are 1 based arrays with blank first values
	var parts = response.split('^');
	var foods = parts[0].split('|');
	var servings = parts[1].split('|');
	var orac = parts[2].split('|');

	// Populate the appropriate item
	if (orac != "") {
		displayORACValue(num, orac[1]);	
	} else if (servings != "") {
		// Add each serving to the list
		addItemsToList(servings, servingList, true);
		$('serving_' + num).style.display = 'inline';
	} else if (foods != "") {
		// Add the choose instruction if it's not included
		if (foods[1].strip() != 'Choose a food item') {
			foods.splice(1,0,'Choose a food item');
		}
		// Add each food to the list
		addItemsToList(foods, foodList, false);
		$('food_' + num).style.display = 'inline';
  	}

}

function addItemsToList(items, list, split_values) {

	// First remove all the prior items
	while(list.hasChildNodes()) { 
		list.removeChild(list.lastChild);
	} 
	for (i = 1; i < items.length; i++) {
		var item_value = items[i];
		var item_name = item_value;
		// Some lists may have slit values where the name and value are separated by a ;
		if (split_values) {
			var parts = item_value.split(';');
			item_value = parts[0];
			item_name = parts[1];
		}
		// Add the new option to the list
		list.options[list.options.length] = 
            new Option(item_name, item_value, false, false);
   	}
   	list[0].selected = true;	
	
}

function displayORACValue(num, orac) {
	// Get the UI Elements
	var oracDiv = $('orac_div_' + num);
	var oracSpan = $$('#orac_div_' + num + ' .orac_span')[0];
	// First remove any prior value
	while(oracSpan.hasChildNodes()) { 
		oracSpan.removeChild(oracSpan.lastChild);
	}	
	// Add the ORAC value
	var value = document.createTextNode(parseFloat(orac).toFixed(0));
	oracSpan.appendChild(value);
	oracSpan.setAttribute('orac', orac);
	// Show the ORAC value
	oracDiv.style.display = 'inline';
	// Show the total ORAC value
	displayOracTotal();
	// Show the add another food button
	$('add_another_food').style.display = 'block';
}

function displayOracTotal() {
	
	var total = 0.0;
	var oracsTotaled = 0;
	
	// Get all the orac spans
	var oracs = $$('.orac_span')
	// Add up the totals of the visible ones
	for (i=0;i < oracs.length; i++) {
		var orac = oracs[i];
		// Total up the orac value if it's being displayed to the user
		if (orac.parentNode.style.display == 'inline') {
			try {
				var orac_value = parseFloat(orac.getAttribute('orac'));
				total += orac_value;
				oracsTotaled++;
			} catch (e) {}
		}
	}

	// If more than one orac was visible, show the total, otherwise hide it
	if (oracsTotaled >= 2) {
		var oracTotal = $('orac_total');
		// First remove any prior value
		while(oracTotal.hasChildNodes()) { 
			oracTotal.removeChild(oracTotal.lastChild);
		}
		// Add the ORAC total
		var value = document.createTextNode(total.toFixed(0));
		oracTotal.appendChild(value);
		$('orac_total_label').style.display = 'inline';
	} else {
		$('orac_total_label').style.display = 'none';
	}
}
