// global variables
var _xmlFilePath = './xml/Products.xml';    // relative path
var _xmlDoc = null;

// assigning of event handlers
window.onload = window_load;

function window_load(e)
{
	if (!loadXmlDocument()) return;
	fillCategoriesList();

	// assigning of event handlers
	document.getElementById('ddlCategories').onchange = ddlCategories_onChange;
	document.getElementById('btnAddToProducts').onclick = btnAddToProducts_onClick;
	document.getElementById('btnSelectNew').onclick = btnSelectNew_onClick;
	document.getElementById('btnClearCalculator').onclick = btnClearCalculator_onClick;
	document.getElementById('btnPrint').onclick = btnPrint_onClick;
}

function loadXmlDocument()
{
	_xmlDoc = null;

	var request;
	try
	{
		request = new XMLHttpRequest();
	}
	catch (e)
	{
		request = new ActiveXObject('Msxml2.XMLHTTP');
	}

	// the following block is necessary for Mozilla
	try
	{
		netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
	}
	catch (e)
	{
		// ignore
	}

	request.open('GET', _xmlFilePath, false);
	request.send(null);

	_xmlDoc = request.responseXML;
	if (_xmlDoc == null)
	{
		alert('Error. Cannot load the list of categories and products.');
		return false;
	}

	return true;
}

function fillCategoriesList()
{
	if (_xmlDoc == null)
	{
		alert('Error. The XML-document containing the list of categories and products is empty.');
		return false;
	}

	// clear the current list of categories except the first row ('Select a category')
	var ddlCategories = document.getElementById('ddlCategories');
	var rowsCount = ddlCategories.options.length;
	for (var i = rowsCount; i > 1; i--)
		ddlCategories.remove(i - 1);

	// fill the drop-down list with the values received from the xml-file
	var categories = _xmlDoc.documentElement.getElementsByTagName('category');
	for (var i = 0; i < categories.length; i++)
		ddlCategories.options[i + 1] = new Option(categories[i].getAttribute('name'), categories[i].getAttribute('id'));

	return true;
}

function ddlCategories_onChange(e)
{
	var ddlCategories = document.getElementById('ddlCategories');
	fillProductsList(parseInt(ddlCategories.value));
}

function fillProductsList(pCategoryID)
{
	// clear the current list of products
	var tblProducts = document.getElementById('tblProducts');
	var rowsCount = tblProducts.rows.length;
	for (var i = rowsCount; i > 0; i--)
		tblProducts.deleteRow(i - 1);

	// show or hide the list of products (and related buttons) depending on the category selected in the drop-down list
	// "0" means that the "Select a category" item was selected
	if (parseInt(pCategoryID) == 0)
	{
		// hide
		document.getElementById('trAvProd1').className = 'dnone';
		document.getElementById('trAvProd2').className = 'dnone';
		document.getElementById('trAvProd3').className = 'dnone';

		return;
	}
	else
	{
		// show
		document.getElementById('trAvProd1').className = '';
		document.getElementById('trAvProd2').className = '';
		document.getElementById('trAvProd3').className = '';
	}

	var category = getCategoryById(pCategoryID);
	if (category == null)
	{
		alert('Error. The XML-document containing the list of categories and products does not include requested category.');
		return false;
	}

	// fill the table with the list of products for selected category
	var products = category.getElementsByTagName('product');
	for (var i = 0; i < products.length; i++)
	{
		var tr = tblProducts.insertRow(i);
		tr.setAttribute('productid', parseInt(products[i].getAttribute('id')));
		var td = tr.insertCell(0);
		td.className = 'col1';
		var input = document.createElement('input');
		input.type = 'checkbox';
		input.className = 'checkbox';
		td.appendChild(input);
		// if a product is already present in the calculator table then mark it as selected
		if (isAddedToCalculator(pCategoryID, parseInt(products[i].getAttribute('id'))))
		{
			input.checked = true;
			input.setAttribute('addedtocalculator', 1);
		}
		else
		{
			input.checked = false;
			input.setAttribute('addedtocalculator', 0);
		}
		td = tr.insertCell(1);
		td.className = 'col2';
		td.appendChild(document.createTextNode(products[i].getAttribute('name')));
	}

	return true;
}

function getCategoryById(pCategoryID)
{
	var category = null;

	var categories = _xmlDoc.documentElement.getElementsByTagName('category');
	for (var i = 0; i < categories.length; i++)
	{
		if (parseInt(categories[i].getAttribute('id')) == pCategoryID)
		{
			category = categories[i];
			break;
		}
	}

	return category;
}

function btnAddToProducts_onClick(e)
{
	document.getElementById('pnl2').className = 'panel2';

	var tblProducts = document.getElementById('tblProducts');
	var categoryID = parseInt(document.getElementById('ddlCategories').value);
	var productIDs = new Array();

	// scan the list of products and check which items were selected and add those of them which is not present in the calculator yet
	for (var i = 0; i < tblProducts.rows.length; i++)
	{
		var input = tblProducts.rows[i].getElementsByTagName('input')[0];
		if (input.checked == true && input.getAttribute('addedtocalculator') == 0)
		{
			productIDs[productIDs.length] = parseInt(tblProducts.rows[i].getAttribute('productid'));
			input.setAttribute('addedtocalculator', 1);
		}
	}

	addProducts(categoryID, productIDs);
}

function addProducts(pCategoryID, pProductIDs)
{
	var category = getCategoryById(pCategoryID);
	var products = category.getElementsByTagName('product');

	var tblCalculator = document.getElementById('tblCalculator');
	// last 3 rows are used for displaying totals
	var rowsCount = tblCalculator.rows.length - 3;

	var currPos = 0;

	// find requested products in the xml-file and add rows to the calculator table
	for (var i = 0; i < products.length; i++)
	{
		if (parseInt(products[i].getAttribute('id')) != pProductIDs[currPos])
			continue;
		else
			currPos++;

		var tr = tblCalculator.insertRow(rowsCount);
		rowsCount++;
		tr.setAttribute('categoryid', pCategoryID);
		tr.setAttribute('productid', parseInt(products[i].getAttribute('id')));

		var td = tr.insertCell(0);
		var span = document.createElement('span');
		span.className = 'linkbtn';
		span.onclick = product_onRemove;
		span.appendChild(document.createTextNode('remove'));
		td.appendChild(span);

		td = tr.insertCell(1);
		var input = document.createElement('input');
		input.type = 'text';
		input.className = 'textbox';
		input.value = '1';
		input.size = '3';
		input.maxLength = '3';
		input.onchange = servingsCount_onChange;
		td.appendChild(input);

		td = tr.insertCell(2);
		td.className = 'left';
		td.appendChild(document.createTextNode(products[i].getAttribute('name')));

		td = tr.insertCell(3);
		td.appendChild(document.createTextNode(products[i].getAttribute('servingsize')));

		td = tr.insertCell(4);
		// the following attribute is used to store calorie savings per one serving
		td.setAttribute('caloriesavings', products[i].getAttribute('caloriesavings'));
		td.appendChild(document.createTextNode(products[i].getAttribute('caloriesavings')));
	}

	calculateTotal();
}

function btnSelectNew_onClick(e)
{
	document.getElementById('ddlCategories').options[0].selected = true;
	// like a user has selected "Select a category" item
	fillProductsList(0);
}

function product_onRemove(e)
{
	e = e ? e : window.event;
	var srcElement = e.srcElement ? e.srcElement : e.target;

	var tblCalculator = document.getElementById('tblCalculator');
	tblCalculator.deleteRow(srcElement.parentNode.parentNode.rowIndex);

	calculateTotal();
	// the following call will be made to re-check which of products from the list above is still present in the calculator
	// and unselect (checkbox) those of them which were removed
	fillProductsList(parseInt(document.getElementById('ddlCategories').value));
}

function servingsCount_onChange(e)
{
	e = e ? e : window.event;
	var srcElement = e.srcElement ? e.srcElement : e.target;

	// if a new value is:
	// a) not a number or is less than 1 - then we set it to 1;
	// b) floating point number - then we round it to an integer;
	// c) a positive integer - then we use it as is.
	var value = parseInt(srcElement.value);
	srcElement.value = (!isNaN(value) && value >= 1 ? value : '1');

	// having a textbox as a srcElement we are moving up in hierarchy (textbox -> td -> tr)
	// and then go to the last cell in this row where we store "calorie savings per one serving" as an attribute
	// then we calculate a new value for the last cell = "servings per week" * "calorie savings per one serving"
	var td = srcElement.parentNode.parentNode.cells[4];
	td.firstChild.nodeValue = parseInt(td.getAttribute('caloriesavings')) * parseInt(srcElement.value);

	calculateTotal();
}

function calculateTotal()
{
	var tblCalculator = document.getElementById('tblCalculator');
	var rowsCount = tblCalculator.rows.length - 3;
	var totalCalories = 0;

	for (var i = 1; i < rowsCount; i++)
	{
		var servingsCount = parseInt(tblCalculator.rows[i].getElementsByTagName('input')[0].value);
		var caloriesPerServing = parseInt(tblCalculator.rows[i].cells[4].getAttribute('caloriesavings'));
		totalCalories += servingsCount * caloriesPerServing;
	}

	document.getElementById('lblTotalCalorieSavings').innerHTML = totalCalories;
	document.getElementById('lblTotalWeightLoss').innerHTML = Math.round(totalCalories * 52 / 3500 * 100) / 100;
}

function isAddedToCalculator(pCategoryID, pProductID)
{
	var tblCalculator = document.getElementById('tblCalculator');
	var rowsCount = tblCalculator.rows.length - 3;

	// tries to find requested product (with some categoryID and productID) in the calculator table
	for (var i = 1; i < rowsCount; i++)
	{
		if (parseInt(tblCalculator.rows[i].getAttribute('categoryid')) == pCategoryID && parseInt(tblCalculator.rows[i].getAttribute('productid')) == pProductID)
			return true;
	}

	return false;
}

function btnClearCalculator_onClick(e)
{
	var tblCalculator = document.getElementById('tblCalculator');
	var rowsCount = tblCalculator.rows.length - 3;

	for (var i = 1; i < rowsCount; i++)
		tblCalculator.deleteRow(1);

	calculateTotal();
	// the following call will be made to re-check which of products from the list above is still present in the calculator
	// and unselect (checkbox) those of them which were removed
	fillProductsList(parseInt(document.getElementById('ddlCategories').value));
}

function btnPrint_onClick(e)
{
	var tblCalculator = document.getElementById('tblCalculator');
	var rowsCount = tblCalculator.rows.length - 3;
	var tblCalculatorForPrint = document.getElementById('tblCalculatorForPrint');

	// copy the data from the calculator table to the table optimized for printing
	for (var i = 1; i < rowsCount; i++)
	{
		var tr = tblCalculatorForPrint.insertRow(i);
		var td = tr.insertCell(0);
		td.appendChild(document.createTextNode(tblCalculator.rows[i].getElementsByTagName('input')[0].value));

		td = tr.insertCell(1);
		td.className = 'left';
		td.appendChild(document.createTextNode(tblCalculator.rows[i].cells[2].firstChild.nodeValue));

		td = tr.insertCell(2);
		td.appendChild(document.createTextNode(tblCalculator.rows[i].cells[3].firstChild.nodeValue));

		td = tr.insertCell(3);
		td.appendChild(document.createTextNode(tblCalculator.rows[i].cells[4].firstChild.nodeValue));
	}

	document.getElementById('lblTotalCalorieSavingsPrn').innerHTML = document.getElementById('lblTotalCalorieSavings').innerHTML;

	// hide the data which should not be printed
	document.getElementById('pnl1').className = 'panel1 dnone';
	tblCalculator.className = 'tblcalculator dnone';
	tblCalculatorForPrint.className = 'tblcalculator';
	document.getElementById('trCalcButtons').className = 'dnone';

	window.print();
}

