function nextSiblingElement(element) {
	do element = element.nextSibling;
	while (element && element.nodeType != 1);
	return element;
}
function previousSiblingElement(element) {
	do element = element.previousSibling;
	while (element && element.nodeType != 1);
	return element;
}

function SetUpNumberTotal(totalBoxId)
{
	var totalBox = document.getElementById(totalBoxId);
	var currentRow = FindParentRow(totalBox);
    if(!currentRow) return;
    
    var total = 0;
    
    do
    {
    	var numberBox = FindNumberBox(currentRow);
        if(!numberBox) break;
        if(!numberBox.className) continue;
        if(numberBox.className.indexOf('formInputNumber') == -1) continue;
        if(numberBox.className.indexOf('formInputNumberTotal') > -1)
        {
			$(numberBox).hide();
			$(numberBox).parent().append("<span id='ro-" + numberBox.id + "'>0</span>");
        }
        else
        {
			numberBox.onblur = function() { CalculateTotal(totalBox) };    
		}
    }
    while(currentRow = previousSiblingElement(currentRow))

    totalBox.value = total;
    CalculateTotal(totalBox);
}

function CalculateTotal(totalBox)
{
    var currentRow = FindParentRow(totalBox);
    if(!currentRow) return;

    var total = 0;
    if (typeof (CalculateCustomTotal) === 'function') {
        total = CalculateCustomTotal();
    }
    else {
        while (currentRow = previousSiblingElement(currentRow)) {
            var numberBox = FindNumberBox(currentRow);
            if (!numberBox) break;
            if (!numberBox.className) continue;
            if (numberBox.className.indexOf('formInputNumber') == -1) continue;
            if (numberBox.className.indexOf('formInputNumberTotal') > -1) break;
            var val = numberBox.value;
            if (isNaN(val)) continue;
            total += (val * 1);
        }
    }
    totalBox.value = total;
    
    $("#ro-" + totalBox.id).html(total);
    
    if(typeof(updateGiftAid) === 'function') {
		updateGiftAid();
	}
}


function FindParentRow(obj)
{
	var result = obj;
	while(result = result.parentNode)
	{
		if(result.tagName == 'TR') return result;		
	}
	return null;
}

function FindNumberBox(obj)
{
	var result = null;
	for(var i=0; i<obj.childNodes.length; i++)
	{
    	var child = obj.childNodes[i];
    	if(child.tagName == 'INPUT')
		{
    		result = child;
			break;
		}
		else
		{
    		result = FindNumberBox(child);
			if(result) break;
		}
	}
	return result;
}

