/*
 * Created on Dec 25, 2006 by Anthony Rabaa (arabaa@rs-d.ca),
 * Rabaa Solutions & Designs - http://www.rs-d.ca
 */

var debug = false;

function submitForm(formId)
{
	document.getElementById(formId + "Form").submit();
}

/**
 * This function will blur the element if the keycode received is equivalent to
 * to having pressed the ENTER key.
 * @param event The action event object.
 * @param element The element which is invoking this method, possibly wanting a
 * subsequent blur event.
 */
function onEnter(event, element)
{
	if(event.keyCode == 13)
		element.blur();
}

/**
 * This function will perform a query against the meal database using the search
 * value specified by the user.
 * @param element The element where the query string resides.
 */
function lookup(element)
{
	Element.extend(element);
	
	if(element.getValue().indexOf("Search for a ") >= 0 || element.getValue().blank())
	{
		if(debug)
			alert("Lookup is returning without action.");
			
		return;
	}
	
	new Ajax.Request('scripts/lookup.php',
	{
		method:'get',
		parameters: {searchString: element.getValue()},

		onSuccess: function(transport)
		{
			var response = transport.responseText || null;
			
			if(response != null)
			{
				if(response == "<null/>")
					alert("Your search returned no results.");
				else
					element.up().update(response);
			}
		},

		onFailure: function(){ alert('Something went wrong...') }
	});
}

function onChange(element, index)
{
	Element.extend(element);
	
	if(debug)
		alert("onChange fired with " + element + ", " + index);

	if(parseInt(index) == -1)
		new Ajax.Request('scripts/inputElement.php',
		{
			method:'get',
			
			onSuccess: function(transport)
			{
				var response = transport.responseText || null;
				
				if(response != null)
					element.up().update(response);
			},
			
			onFailure: function(){}
		});

	populateRow(element);
}

function populateRow(element)
{
	Element.extend(element);
	var ancestors = element.ancestors();
	
	// Search for the elements parent 'tr'.
	for(var i = 0; i < ancestors.length; i++)
		if(ancestors[i].tagName == 'TR')
		{
			element = Element.extend(ancestors[i]);
			break;
		}
	
	// Kick out if it couldn't be found.
	if(element.tagName != 'TR')
		return;
		
	// There must be two select statements to populate a row. The first one will
	// contain the user search results.  The second will be the portion size.
	var selects = element.getElementsByTagName('select');
	
	if(selects.length != 2)
		return;
	
	var selectedItem = selects[0].options[selects[0].selectedIndex];
	
	if(debug)	
		alert(selectedItem.value);
	
	// Initialized to zero to clear cells by default.
	var calories = 0;
	var protein  = 0;
	var carbs    = 0;
	var fat      = 0;
	
	// Download meal data if one is selected.
	if(selectedItem.value != '' & selectedItem.value != '-1')
		new Ajax.Request('scripts/mealData.php',
		{
			method: 'get',
			parameters: {id: selectedItem.value},
			
			onSuccess: function(transport)
			{
				var response = transport.responseText || null;
				
				if(response != null)
				{
					response = response.split(',');
					populateRowDetails(element, response[1], response[2], response[3], response[0]);
				}
			},
			
			onFailure: function() { populateRowDetails(element, 0, 0, 0, 0); }
		});
	else
		populateRowDetails(element, protein, fat, carbs, calories);
}

function populateRowDetails(row, protein, fat, carbs, calories)
{
	var tds     = row.getElementsByTagName('td');
	var portion = tds[1].getElementsByTagName('select')[0];
	var rowId   = tds[0].id.substring(8, tds[0].id.indexOf('_'));

	tds[2].getElementsByTagName('input')[0].value = r2(protein * portion.options[portion.selectedIndex].value);
	tds[3].getElementsByTagName('input')[0].value = r2(fat * portion.options[portion.selectedIndex].value);
	tds[4].getElementsByTagName('input')[0].value = r2(carbs * portion.options[portion.selectedIndex].value);
	tds[5].getElementsByTagName('input')[0].value = r2(calories * portion.options[portion.selectedIndex].value);
	
	recalculateTotals(rowId);
}