function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0){
			return c.substring(nameEQ.length,c.length);
		}
	}
	return false;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
// At 0.05 we round DOWN not UP
// To Achieve that, we change 0.05 to 0.04!
function customRound(number) {
   var newNumber = number;
   newNumber = Math.round(number*100) / 100;

   if ( newNumber <= 0.49 ) {
     return 0;
   }
   
   if ( /\.\d5/.test(newNumber) ) {
      newNumber -= 0.01;
   }
   
   newNumber = Math.round(newNumber*10) / 10;
   
   // Now change the 10th place to 5 if x.3 - x.7.
   // Round the rest to nearest whole number.
   var dot5 = /^(\d+)\.[3-7]$/;
   
   if ( dot5.test(newNumber) ) {
      var tmp = newNumber.toString();
      newNumber = tmp.replace(dot5, "$1.5");
   } else {
      newNumber = Math.round(newNumber);
   }
   
   return newNumber;
}

		// Number of table columns
		var tableCols = 22;

		// HTML Cell positions (zero-based) - we reference these directly in the code
		// Quantity cell in the total rows in the selections menu
		var menuSelectionsQtyCellPosition = 3;
		// Add/Remove link cell in the total rows in the selections menu
		var menuSelectionsAddRemoveCellPosition = 0;
		// Arrow image in the row's image array
		var arrowImgPosition = 0;
		// Checkbox image cell in a row cells array
		var checkboxImgCellPosition = 2;

		// Pre-cache images
		var arrowRight = new Image();
		arrowRight.src = '/images/nutrition/arrow_right.gif';
		var arrowDown = new Image();
		arrowDown.src = '/images/nutrition/arrow_down.gif';

		var checkboxChecked = new Image();
		checkboxChecked.src = '/images/nutrition/checkbox_checked.gif';
		var checkboxUnchecked = new Image();
		checkboxUnchecked.src = '/images/nutrition/checkbox_unchecked.gif';

		var selectionX = new Image();
		selectionX.src = '/images/nutrition/included_dot.gif';
		var selectionNoX = new Image();
		selectionNoX.src = '/images/nutrition/included_no_dot.gif';
		var selectionPartX = new Image();
		selectionPartX.src = '/images/nutrition/included_dot_empty.gif';

		var selectNutritionOn = new Image();
		selectNutritionOn.src = '/images/nutrition/nutrition_on.gif';
		var selectNutritionOff = new Image();"less than 5mg"
		selectNutritionOff.src = '/images/nutrition/nutrition_off.gif';

		//var //selectAllergensOn = new Image();
		//selectAllergensOn.src = '/images/nutrition/allergens_on.gif';
		//var //selectAllergensOff = new Image();
		//selectAllergensOff.src = '/images/nutrition/allergens_off.gif';

		var printNutritionOn = new Image();
		printNutritionOn.src = '/images/nutrition/print_nutrition_on.gif';
		var printAllergensOn = new Image();
		printAllergensOn.src = '/images/nutrition/print_allergens_on.gif';
		var printNutritionOff = new Image();
		printNutritionOff.src = '/images/nutrition/print_nutrition_off.gif';
		var printAllergensOff = new Image();
		printAllergensOff.src = '/images/nutrition/print_allergens_off.gif';

		// Get base url
		var pageurl = document.location.href;
		var xend = pageurl.lastIndexOf("/") + 1;
		var base_url = pageurl.substring(0, xend);

///////////////////////////

		// Strip the row id down to the base id
		function getItemId(rowId) {
			var thisItemId = rowId.replace(/_total/,'');
			thisItemId = thisItemId.replace(/selected_/,'');
			thisItemId = thisItemId.replace(/nutrition_/,'');
			thisItemId = thisItemId.replace(/allergens_/,'');
			return thisItemId;
		}

		// Show detail rows for the given item
  	function openCloseRow(anchorObj) {

			// Derive the IDs
			if (typeof anchorObj == 'object') {
				var thisRowId = anchorObj.parentNode.parentNode.id;
			} else if (typeof anchorObj == 'string') {
				var thisRowId = anchorObj;
			} else {
				return;
			}
			var thisItemId = getItemId(thisRowId);

			// Determine which section we're searching
			if (thisRowId.indexOf('selected') >= 0) {
				var bodyObj = document.getElementById('selections_body');
				var refDrawer = open_selections_drawer;
			} else {
				var bodyObj = document.getElementById('menus_body');
				var refDrawer = open_menu_drawer;
			}

			// Determine which data type we're viewing
			if (thisRowId.indexOf('nutrition_') >= 0) {
				var thisDataType = 'nutrition';
			} else {
				var thisDataType = 'allergens';
			}

			// Get rows
  		var bodyRows = bodyObj.getElementsByTagName('tr');

			// For each row, looping backwards
  		for (var i=(bodyRows.length-1); i>=0; i--) {
  			if (bodyRows[i].id) {

					// If we match thisItemId but NOT thisRowId...
					// it also must be this datatype because we don't want allergen detail
					// rows appearing while viewing nutrition data
					if (bodyRows[i].id.indexOf(thisItemId) >= 0 &&
							bodyRows[i].id.indexOf(thisRowId) < 0 &&
							bodyRows[i].id.indexOf(thisDataType) >= 0) {

						// If the request is to open the drawer that is already open
						// then we want to close it
						if (refDrawer == thisItemId) {
							bodyRows[i].style.display = 'none';
						// Otherwise, display the row
						} else {
							bodyRows[i].style.display = '';
						}

					// If we didn't match yet and this is a detail row, then close it
					} else if (bodyRows[i].id.indexOf('_detail_') >= 0) {

							bodyRows[i].style.display = 'none';

					// For the total row that called this function, rotate the image
					} else if (bodyRows[i].id.indexOf('_total') >= 0) {

						// Get images from the row
						var rowImages = bodyRows[i].getElementsByTagName('img');

						// If this is the row that was clicked on and we're not
						// closing the row, tip the arrow down
						if (bodyRows[i].id.indexOf(thisRowId) >= 0 &&
								refDrawer != thisItemId) {
							rowImages[arrowImgPosition].src = arrowDown.src;
						// Otherwise tip it back
						} else {
							rowImages[arrowImgPosition].src = arrowRight.src;
						}

					}

  			}

  		}

			// Track which drawer is open so we can support
			// closing that drawer by clicking it again
			if (refDrawer == thisItemId) {
				// If we closed the row, clear the stored id
				if (thisRowId.indexOf('selected') >= 0) {
					open_selections_drawer = '';
				} else {
					open_menu_drawer = '';
				}
			} else {
				// Store this id for next time this function is called
				if (thisRowId.indexOf('selected') >= 0) {
					open_selections_drawer = thisItemId;
				} else {
					open_menu_drawer = thisItemId;
				}
			}

  	}

		// Add item to selections menu
		function addToMenu(anchorObj,qty) {

			// Derive the IDs
			var thisRowId;
			var thisItemId;
			var tempArray = new Array();
			var itemQty = qty;

			if(typeof(anchorObj) == 'object'){
				
				thisRowId = anchorObj.parentNode.parentNode.id;
				//createCookie(thisRowId,thisRowId,7);
				// Set the open selections drawer to this item
				openCloseRow(anchorObj);
				
			}else{
				
				thisRowId = anchorObj;
				 
			}
			
			thisItemId = getItemId(thisRowId);
			
			// Determine which data type we're viewing
			if (thisRowId.indexOf('nutrition_') >= 0) {
				var thisDataType = 'nutrition';
			} else {
				var thisDataType = 'allergens';
			}
			
			
			
			// Get menuSelections tbody element
			// This is where the rows will be copied to
			var menuSelectionsObj = document.getElementById('selections_body');

			// If this entry already exists in our tracking array, just update it
			// Remember, if we removed the item, it will be in the array with a value of zero
			if ((menuSelectionsItems[thisItemId] > 0)) {

				// Increment the qty for this item
				menuSelectionsItems[thisItemId] += 1;
				if(typeof(anchorObj) == 'object'){
					
					createCookie(thisRowId,menuSelectionsItems[thisItemId],7);

				}
				// Get row and row cells
				
					var menuSelectionsRowObj = document.getElementById('selected_'+thisRowId);
					var menuSelectionsRowCells = menuSelectionsRowObj.getElementsByTagName('td');
				
					// Update the qty cell
					var menuSelectionsRowQtyCell = menuSelectionsRowCells[menuSelectionsQtyCellPosition];
					menuSelectionsRowQtyCell.replaceChild(document.createTextNode(menuSelectionsItems[thisItemId]), menuSelectionsRowQtyCell.firstChild);
				
					// Since we changed the qty, we need to update the item totals for this section
					calculateItemTotals('selections');
				

			// If this entry didn't already exist in the menu selections, we need to add it
			} else {
				
				// Record this item in the tracking list
				//if(itemQty > 1){
				
				//	menuSelectionsItems[thisItemId] = itemQty;
					
				//}else{
					menuSelectionsItems[thisItemId] = 1;
				//}
				
				if(typeof(anchorObj) == 'object'){
					if(!readCookie('nutrition_'+thisItemId+'_total')){
						createCookie(thisRowId,menuSelectionsItems[thisItemId],7);
					}
				}
				// Get the reference to the menu and its rows
				// This is where the rows we're copying will come from
				var menuItemsObj = document.getElementById('menus_body');
	  		var menuItemsRows = menuItemsObj.getElementsByTagName('tr');
			
				// Find the rows we're copying
	  		for (var i=0; i<menuItemsRows.length; i++) {
					if (menuItemsRows[i].id) {
//alert(i);
						// See if this row belongs to the item
	  				if (menuItemsRows[i].id.indexOf(thisItemId) >= 0) {

	  					// Get the row reference
	  					var menuItemRowObj = document.getElementById(menuItemsRows[i].id);

	  					// Clone the row or it will get removed from this section when added above
	  					var menuSelectionsRowObj = menuItemRowObj.cloneNode(true);

	  					// Rename the key as there can only be one unique id per page
	  					menuSelectionsRowObj.id = 'selected_'+menuSelectionsRowObj.id;
						
	  					// If this is the totals row, setup the quantity and "remove item" fields
	  					if (menuSelectionsRowObj.id.indexOf('_total') >= 0) {

	  						// Get the cells in this row
								var menuSelectionsRowCells = menuSelectionsRowObj.getElementsByTagName('td');

								// Configure the quantity column
								menuSelectionsRowCells[menuSelectionsQtyCellPosition].className='border_left';
								menuSelectionsRowCells[menuSelectionsQtyCellPosition].replaceChild(document.createTextNode(menuSelectionsItems[thisItemId]), menuSelectionsRowCells[menuSelectionsQtyCellPosition].firstChild);
								//alert(menuSelectionsItems[thisItemId]);
								// Also change the link in the add/remove link cell
								var menuSelectionsRowFirstCell = menuSelectionsRowCells[menuSelectionsAddRemoveCellPosition];

								var removeLink = document.createElement("a");
								removeLink.href = '#';
								removeLink.onclick = function() { removeFromMenu(this);addVarsForType(this);return false; }
								menuSelectionsRowFirstCell.replaceChild(removeLink, menuSelectionsRowFirstCell.firstChild);
								var removeText = document.createTextNode('remove');
								removeLink.appendChild(removeText);

							}

							// Add this row to selections menu
							menuSelectionsObj.appendChild(menuSelectionsRowObj);

						}

					}
				}
				
				// If the incoming menu item was open, record it as open in the selections menu,
				if (open_menu_drawer == thisItemId) {
					
					// if menu selections already has an open drawer, we need to close it
					if (open_selections_drawer.length > 0) {

						// Get rows from the menu selections section
						var menuSelectionsRows = menuSelectionsObj.getElementsByTagName('tr');

						// Find the rows we're closing
		  			for (var i=0; i<menuSelectionsRows.length; i++) {
							if (menuSelectionsRows[i].id) {

								// If this is a Detail row and it's open in the menu,
								// mark it open in the selections menu
		    				if (menuSelectionsRows[i].id.indexOf(open_selections_drawer) >= 0) {

									// If this is a detail row, hide it
		    					if (menuSelectionsRows[i].id.indexOf('_detail') >= 0) {
										menuSelectionsRows[i].style.display = 'none';
									// If it's the total row, tip the arrow back
									} else {
										var menuSelectionsRowImages = menuSelectionsRows[i].getElementsByTagName('img');
										menuSelectionsRowImages[arrowImgPosition].src = arrowRight.src;
									}

								}

							}
						}

					}

					// Set the open selections drawer to this item
					open_selections_drawer = thisItemId;

				}
				

			}

			// If this was the first item to be added, we need to hide the placeholder row
			showHidePlaceholder();
			// We also need to calculate the meal totals
			calculateMealTotals();
			//click_showDatatype();
			
			// display personalised list when an menu item is added
			document.getElementById('selections').style.display = '';
			
			// force focus when menu item is added to personalised list
			var menuSelectionAnchor = document.getElementById('selection_anchor');
			menuSelectionAnchor.focus();
			
			

		}

		// Remove item from selections menu
		function removeFromMenu(anchorObj) {
			//remove cookie if it exists
			
			
			
			// Derive the IDs
			var thisRowId = anchorObj.parentNode.parentNode.id;
			var thisItemId = getItemId(thisRowId);
			
			if(readCookie('nutrition_'+thisItemId+'_total')){
				eraseCookie('nutrition_'+thisItemId+'_total');
				}
			
			// If this entry has a qty greater than one, just update it
			if (menuSelectionsItems[thisItemId] > 1) {

				// Decrement the qty for this item
				menuSelectionsItems[thisItemId] -= 1;

				// Get row references (because both types might exist, we need to
				// check for and update both)
				var menuSelectionsNutritionRowObj = document.getElementById('selected_nutrition_'+thisItemId+'_total');
				var menuSelectionsAllergensRowObj = document.getElementById('selected_allergens_'+thisItemId+'_total');

				// If the nutrition row exists
				if (menuSelectionsNutritionRowObj && menuSelectionsNutritionRowObj.id) {

					// Get cells in the row
					var menuSelectionsNutritionRowCells = menuSelectionsNutritionRowObj.getElementsByTagName('td');

					// Update the qty cell
					var menuSelectionsNutritionRowQtyCell = menuSelectionsNutritionRowCells[menuSelectionsQtyCellPosition];
					menuSelectionsNutritionRowQtyCell.replaceChild(document.createTextNode(menuSelectionsItems[thisItemId]), menuSelectionsNutritionRowQtyCell.firstChild);

				}

				// If the allergens row exists
				if (menuSelectionsAllergensRowObj && menuSelectionsAllergensRowObj.id) {

					// Get cells in the row
					var menuSelectionsAllergensRowCells = menuSelectionsAllergensRowObj.getElementsByTagName('td');

					// Update the qty cell
					var menuSelectionsAllergensRowQtyCell = menuSelectionsAllergensRowCells[menuSelectionsQtyCellPosition];
					menuSelectionsAllergensRowQtyCell.replaceChild(document.createTextNode(menuSelectionsItems[thisItemId]), menuSelectionsAllergensRowQtyCell.firstChild);

				}

				// Since we changed the qty, we need to update the item totals for this section
				calculateItemTotals('selections');

			// If this row has a qty of 1, we need to remove it
			} else {

				// Set the qty for this item to zero so we know it has been removed
				menuSelectionsItems[thisItemId] = 0;

				// Get menuselections tbody element and rows
				// This is where we are removing from
				var menuSelectionsObj = document.getElementById('selections_body');
				var menuSelectionsRows = menuSelectionsObj.getElementsByTagName('tr');

				// Search the rows backwards so the keys don't renumber as we remove rows
				for (i=(menuSelectionsRows.length-1); i>=0; i--) {
					if (menuSelectionsRows[i].id) {

						// If we find thisItemId remove it regardless of dataType or row type
						if (menuSelectionsRows[i].id.indexOf(thisItemId) >= 0) {
							menuSelectionsObj.removeChild(menuSelectionsRows[i]);
						}

					}
				}

			}

			// If we removed the last item, show the placeholder again
			showHidePlaceholder();
			// Update the meal total
			calculateMealTotals();
			//click_showDatatype();

		}

		// Show or hide the placeholder row for the selections list depending on
		// whether real content exists or not
		function showHidePlaceholder() {

			// Get placeholder row
			var menuSelectionsPlaceholderRow = document.getElementById('selections_placeholder');

			// Get a body element to see if any entries exist
			var menuSelectionsBody = document.getElementById('selections_body');

			// If there are rows in the body, hide the placeholders
			if (menuSelectionsBody.getElementsByTagName('tr').length > 0) {
				menuSelectionsPlaceholderRow.style.display = 'none';
			// Otherwise, show the placeholder
			} else {
				menuSelectionsPlaceholderRow.style.display = '';
			}

		}

		// Handle display of nutrition and allergen content
		// this is complicated because we have only loaded what was necessary so we
		// need to account for not only what is there and hidden but what might not be there
		function showDataType(dataType) {

			current_dataType = dataType;
			
			// First, audit our content, and see if we're missing any data
			// Since the selections list is a mix of categories we need to look throug
			// and load them individually
			for (var selectionsItemId in menuSelectionsItems) {
//alert(selectionsItemId);
				var item_qty = readCookie('nutrition_'+selectionsItemId+'_total');
				//alert(item_qty);
				if(!item_qty){ item_qty = 1;}
				itemIdParts = selectionsItemId.split('_');
				sid = itemIdParts[0];
				itemId = itemIdParts[1];

				// Test to see if the total row for this dataType exists in the selections list
				var testTotalLine = document.getElementById('selected_'+dataType+'_'+selectionsItemId+'_total');
				// If not, load it
				if (!testTotalLine || !testTotalLine.id) {
					getData (current_mid, sid, itemId, dataType, 'selections',item_qty);
				}

			}

			// Make sure content is loaded for the regular menu too
			getData(current_mid, current_sid, '', dataType, 'menus');

			// Only search table rows associated with nutrition/allergen content
			var mainTable = document.getElementById('main');
			mainTableRows = mainTable.getElementsByTagName('tr');

			// Next, display and hide the content based on data type
			for (i=0; i<mainTableRows.length; i++) {
				if (mainTableRows[i].id) {

					// If this row id contains 'nutrition' or 'allergens'
					if ((mainTableRows[i].id.indexOf('nutrition') >= 0 ||
							 mainTableRows[i].id.indexOf('allergens') >= 0) &&
							(mainTableRows[i].id.indexOf('_detail_') >= 0 ||
							 mainTableRows[i].id.indexOf('_total') >= 0 ||
							 mainTableRows[i].id.indexOf('_head') >= 0 ||
							 mainTableRows[i].id.indexOf('_sum') >= 0)) {

						// Display the specified type and hide the others	- See >>>>>>>>>>>>>>>>>>> below:
						if (mainTableRows[i].id.indexOf(dataType) >= 0 && 									 // If this is the right dataType
								(mainTableRows[i].id.indexOf('_total') >= 0 || 									 // AND it's a total row
								 mainTableRows[i].id.indexOf('_head') >= 0 ||										 // OR it's a header row
								 mainTableRows[i].id.indexOf('_sum') >= 0 ||										 // OR it's a sum row
								 (mainTableRows[i].id.indexOf('_detail_') >= 0 && 							 // OR it's a detail row AND
								  ((mainTableRows[i].id.indexOf('selected_') >= 0 && 						 // it's in selections AND
								    open_selections_drawer.length > 0 && 												 // a drawer is open AND
								    mainTableRows[i].id.indexOf(open_selections_drawer) >= 0) || // this drawer is open
								   (mainTableRows[i].id.indexOf('selected_') < 0 && 						 // OR it's in the main menu AND
								    open_menu_drawer.length > 0 && 															 // a drawer is open AND
								    mainTableRows[i].id.indexOf(open_menu_drawer) >= 0) 				 // this drawer is open
								  )
								 )
								)
							 ) {
							mainTableRows[i].style.display = '';
						} else {
							mainTableRows[i].style.display = 'none';
						}

					}

				}
			}

			// Last, swap the images to indicate which section we're in
			var selectNutrition = document.getElementById('selectNutrition');
			//var //selectAllergens = document.getElementById('//selectAllergens');

			if (dataType == 'nutrition') {

				selectNutrition.src = selectNutritionOn.src;
				////selectAllergens.src = //selectAllergensOff.src;

				// Selectively display legend details
				document.getElementById('allergenLegend').style.display = 'none';
				document.getElementById('nutritionLegend').style.display = '';

			} else if (dataType == 'allergens') {

				selectNutrition.src = selectNutritionOff.src;
				//selectAllergens.src = //selectAllergensOn.src;

				// Selectively display legend details
				document.getElementById('allergenLegend').style.display = '';
				document.getElementById('nutritionLegend').style.display = 'none';

			}

			correctRowDisplay();
			calculateItemTotals('selections');
			calculateItemTotals('menus');

		}

		// Load menu section data for both nutrition and allergen sections
		function getData (mid, sid, itemid, dataType, dest, item_qty) {

			// Put up progress bar
			showProgressBar();

			// Update the currently selected values unless we're
			// calling single items for the selections menu
			if (dest == 'menus') {
				current_mid = mid;
				current_sid = sid;
				current_itemid = itemid;
				current_dataType = dataType;
				current_dest = dest;
			}

			// Strip off leading letters so we can replace them later (to avoid
			// double letters since this is called from multiple places)
			mid = mid.replace(/M/, '');
			sid = sid.replace(/S/, '');
			itemid = itemid.replace(/I/, '');

			// See if the requested category content is already loaded in the menu
			var menuObj = document.getElementById('menus_body');
			var menuRows = menuObj.getElementsByTagName('tr');

			// We have to search to find if the content exists, so we need a flag
			// to track whether we found it or not.
			var menuContentExists = false;

			for (i=0; i<menuRows.length; i++) {
				if (menuRows[i].id) {

					// Only show the current data type and section, and only total rows unless
					// this section is open
					if (menuRows[i].id.indexOf(dataType+'_S'+sid) >= 0 &&	// If it's in this section
							(menuRows[i].id.indexOf('_total') >= 0 ||					// and it's a total row
							 (menuRows[i].id.indexOf('_detail_') >= 0 &&			// or it's a detail row AND
							  open_menu_drawer.length > 0 &&									// there is an open drawer AND
							  menuRows[i].id.indexOf(open_menu_drawer) >= 0)	//
							)
						 ) {

						// Set the flag
						menuContentExists = true;

						// Set the display flag to view
						menuRows[i].style.display = '';

					} else {

						// Set the display flag to hide
						menuRows[i].style.display = 'none';

					}

				}
			}

			// If the content wasn't found, load it
			if (menuContentExists == false) {

        // Create new JS element
        var newScript = document.createElement('SCRIPT');
        newScript.type = 'text/javascript';
				// Close the progress bar when the script is finished
        if (itemid == '') {
//        	newScript.addEventListener('load', hideProgressBar, false);
//        	newScript.attachEvent('load', hideProgressBar);
        	newScript.onload = function () { hideProgressBar(); document.getElementById('menuSectionsSelector').blur(); }
				}
        newScript.src = base_url + 'importScript.php?mid=M'+mid+'&sid=S'+sid+'&id=I'+itemid+'&type='+dataType+'&dest='+dest+'&item_qty='+item_qty;

        // Append JS element (therefore executing the data call)
        document.body.appendChild (newScript);

      } else {
        if (itemid == '') {
					hideProgressBar();
					document.getElementById('menuSectionsSelector').blur();
				}
      }

			calculateItemTotals('menus')
			calculateMealTotals();
			//click_showDatatype();
		}

		function showProgressBar() {

			var objLoadingImage = document.getElementById('loadingImage');
			var objOverlay = document.getElementById('overlay');

			var arrayPageSize = getPageSize();
			var arrayPageScroll = getPageScroll();

			var selectElements = document.getElementsByTagName('select');
			for (i=0; i<selectElements.length; i++) {
				if (selectElements[i].style) {
					selectElements[i].style.display='none';
				}
			}

			// center loadingImage if it exists
			if (objLoadingImage) {
				objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
				objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
				objLoadingImage.style.display = 'block';
			}

			// set height of Overlay to take up whole page and show
			objOverlay.style.height = (arrayPageSize[1] + 'px');
			objOverlay.style.display = 'block';
			objOverlay.style.display = '';
		}

		function hideProgressBar() {
			var selectElements = document.getElementsByTagName('select');
			for (i=0; i<selectElements.length; i++) {
				if (selectElements[i].style) {
					selectElements[i].style.display='';
				}
			}
			document.getElementById('overlay').style.display = 'none';
		}

		function calculateItemTotals(section) {
//alert('calcItemTotals - '+section);
			// (selected_)nutrition_S176_I2523_total
			// (selected_)nutrition_S176_I2523_detail_D2191

			// nutrition_selections_sum
			// allergens_selections_sum

			//=============================================================
			// CALCULATE NUMBERS FOR EACH ITEM IN THE SELECTIONS SECTION
			// Loop through table rows backwards since that way the detail rows will come first
			if (section == 'selections') {

				var selectionsObj = document.getElementById('selections_body');
				var selectionsRows = selectionsObj.getElementsByTagName('tr');
				
				var resetTotals = true;

				// Loop through the rows backwards so the detail rows come first
				for (j=(selectionsRows.length-1); j>=0; j--) {
					if (selectionsRows[j].id) {
						
						/////////////////////
						// DETAIL ROW
						// If we find a detail row
						if (selectionsRows[j].id.indexOf('_detail_') >= 0) {
							
							// Check if we need to reset the totals
							if (resetTotals == true) {

								// We need the itemId to identify the related totals row
								var itemId = selectionsRows[j].id.split('_detail_')[0];

								// Create an array to store the totals,
								// use the totals row to determine which columns we're using
								var selectionsTotals = new Array();
								var selectionsTotalsRow = document.getElementById(itemId+'_total');
								var selectionsTotalsRowCells = selectionsTotalsRow.getElementsByTagName('td');
								var m = 0;
								for (k=4; k<selectionsTotalsRowCells.length; k++) {
									// Identify cells expecting to receive a total
									if (isNumeric(parseFloat(selectionsTotalsRowCells[k].firstChild.nodeValue)) ||
											(selectionsTotalsRowCells[k].firstChild.nodeName.toLowerCase() == 'img' &&
												selectionsTotalsRowCells[k].firstChild.src.indexOf('dot') >= 0)) {
										selectionsTotals[m] = 0;
										m++;
									}
								}

								resetTotals = false;

							}

							// Get detail row cells
							var selectionsDetailRowCells = selectionsRows[j].getElementsByTagName('td');
							
                            var type = selectionsRows[j].getAttribute('type'); // oz or g

							// Find out if we should add this row
							if (selectionsDetailRowCells[checkboxImgCellPosition].firstChild.firstChild.nodeName.toLowerCase() == 'img') {
								var imageSrc = selectionsDetailRowCells[checkboxImgCellPosition].firstChild.firstChild.src;
							}

							// If the checkbox is checked, add this row
							if (imageSrc.indexOf('_checked') >= 0) {
								if(readCookie(selectionsRows[j].id) <= 0){
									createCookie(selectionsRows[j].id,1,7);
								}
								// Add the numbers in this row
								var shiftAmt = 5;
								// Add the values
								for (k=0; k<selectionsTotals.length; k++) {

									if (selectionsDetailRowCells[k+shiftAmt].firstChild.nodeName.toLowerCase() == 'img') {
										if (selectionsDetailRowCells[k+shiftAmt].firstChild.src.indexOf(selectionX.src) >= 0) {
											selectionsTotals[k] += 1;
										} else {
											selectionsTotals[k] += 0;
										}
//								} else if (selectionsDetailRowCells[k+shiftAmt].firstChild.nodeValue == '&lt; 1') {
//									selectionsTotals[k] += 0.01;
									} else if (selectionsDetailRowCells[k+shiftAmt].lastChild.innerHTML == '*') {
										selectionsTotals[k] += 0;
									} else if (isNumeric(parseFloat(selectionsDetailRowCells[k+shiftAmt].lastChild.innerHTML))) {
										selectionsTotals[k] += parseFloat(selectionsDetailRowCells[k+shiftAmt].lastChild.innerHTML);
									}
								}

							}

						/////////////////////
						// TOTAL ROW
						// See if this is the totals row for the detail rows we've been summing
						} else if (selectionsRows[j].id.indexOf(itemId+'_total') >= 0) {

							// Output the totals
							var selectionsTotalRowCells = selectionsRows[j].getElementsByTagName('td');
                            var type = selectionsRows[j].getAttribute('type'); // oz or g

							var shiftAmt = 4;

							// Insert the values
							for (k=0; k<selectionsTotals.length; k++) {

								// Nutrition Display
								if (selectionsRows[j].id.indexOf('nutrition_') >= 0) {

									// Account for item quantity
									selectionsTotals[k] = selectionsTotals[k] * parseInt(selectionsTotalRowCells[menuSelectionsQtyCellPosition].firstChild.nodeValue);
									if((k+shiftAmt)>=5 && (k+shiftAmt)<=6)
										{
											if(selectionsTotals[k]<5)
											{
												roundedTotal=0;
											}
											else if(selectionsTotals[k]<=50)
											{
												var remainder=selectionsTotals[k]%5;
												if(remainder>2.5)
												{
													roundedTotal=parseInt(selectionsTotals[k]-remainder)+5;
												}
												else
												{
													roundedTotal=parseInt(selectionsTotals[k]-remainder);
												}
											}
											else
											{
												var remainder=selectionsTotals[k]%10;
												if(remainder>=5)
												{
													roundedTotal=parseInt(selectionsTotals[k]-remainder+10);
												}
												else
												{
													roundedTotal=parseInt(selectionsTotals[k]-remainder);
												}
											}
										}
										else if((k+shiftAmt)>=7 && (k+shiftAmt)<=9)
										{
											if(selectionsTotals[k]<0.5)
											{
												roundedTotal=0;
											}
											else if(selectionsTotals[k]<5)
											{
												var poor=selectionsTotals[k]-parseInt(selectionsTotals[k]);
												if(poor>=0.5)
												{
													if((poor-0.5-0.25)>=0)
													{
														roundedTotal=parseInt(selectionsTotals[k]+1);
													}
													else
													{
														roundedTotal=parseInt(selectionsTotals[k])+0.5;
													}
												}
												else
												{
													if((poor-0.25)>=0)
													{
														roundedTotal=parseInt(selectionsTotals[k])+0.5;	
													}
													else
													{
														roundedTotal=parseInt(selectionsTotals[k]);
													}
												}
											}
											else
											{
												roundedTotal=Math.round(selectionsTotals[k]);
											}
										}
										else if((k+shiftAmt)==10)
										{
											if(selectionsTotals[k]<2)
											{
												roundedTotal=0;
											}
											else if(selectionsTotals[k]>=2 && selectionsTotals[k]<5)
											{
												roundedTotal=5;
											}
											else
											{
												var remainder=selectionsTotals[k]%5;
												var numstring=selectionsTotals[k]+".";
												var poor=numstring.substr(numstring.indexOf(".")-1,1);

												if(remainder>=2.5)
												{
													if(poor<5)
													{
														roundedTotal=parseInt(selectionsTotals[k]-poor+5);
													}
													else
													{
														roundedTotal=parseInt(selectionsTotals[k]-poor+10);
													}
												}
												else
												{
													if(remainder<1)
													{
														roundedTotal=parseInt(selectionsTotals[k]);
													}
													else
													{
														roundedTotal=parseInt(selectionsTotals[k]-remainder);
													}
													
												}
											}
										}
										else if((k+shiftAmt)==11)
										{
											if(selectionsTotals[k]<5)
											{
												roundedTotal=0;
											}
											else if(selectionsTotals[k]<140)
											{
												var remainder=selectionsTotals[k]%5;
												var numstring=selectionsTotals[k]+".";
												var poor=numstring.substr(numstring.indexOf(".")-1,1);

												if(remainder>=2.5)
												{
													if(poor>5)
													{
														roundedTotal=parseInt(selectionsTotals[k]-poor+10);
													}
													else
													{
														roundedTotal=parseInt(selectionsTotals[k]-poor+5);
													}
												}
												else
												{
													roundedTotal=parseInt(selectionsTotals[k]-remainder);
												}
											}
											else
											{
												var remainder=selectionsTotals[k]%10;
												if(remainder>=5)
												{
													roundedTotal=parseInt(selectionsTotals[k]-remainder+10);
												}
												else
												{
													roundedTotal=parseInt(selectionsTotals[k]-remainder);
												}
											}
										}
										else if((k+shiftAmt)>=12 && (k+shiftAmt)<=15)
										{
											if(selectionsTotals[k]<0.5)
											{
												roundedTotal=0;
											}
											else if(selectionsTotals[k]<1)
											{
												roundedTotal=1;
											}
											else
											{
												roundedTotal=Math.round(selectionsTotals[k]);
											}
										}
										else if((k+shiftAmt)>=16 && (k+shiftAmt)<=19) {
											switch(k+shiftAmt){
												case 16:
													selectionsTotals[k] = (selectionsTotals[k]/5000)*100;
													break;
												case 17:
													selectionsTotals[k] = (selectionsTotals[k]/60)*100;
													break;
												case 18:
													selectionsTotals[k] = (selectionsTotals[k]/1000)*100;
													break;
												case 19:
													selectionsTotals[k] = (selectionsTotals[k]/18)*100;
													break;
											}
											
											if(selectionsTotals[k]<2)
											{
												roundedTotal='*';
											}
											else if(selectionsTotals[k]>=2 && selectionsTotals[k]<=10)
											{
												var remainder=parseInt(selectionsTotals[k]%2);
												if(remainder==1)
												{
													roundedTotal=parseInt(selectionsTotals[k]+1);
												}
												else
												{
													roundedTotal=parseInt(selectionsTotals[k]);
												}
											}
											else if(selectionsTotals[k]>10 && selectionsTotals[k]<50)
											{
												//selectionsTotals[k]=selectionsTotals[k].toFixed(1);
											 	//alert(selectionsTotals[k]);
												var remainder=selectionsTotals[k]%5;
												var numstring=selectionsTotals[k]+".";
												var poor=numstring.substr(numstring.indexOf(".")-1,1);

												//alert(poor);
												if(remainder>=2.5)
												{
													if(poor>5)
													{
														roundedTotal=parseInt(selectionsTotals[k]-poor)+10;
													}
													else
													{
														roundedTotal=parseInt(selectionsTotals[k]-poor)+5;
													}
												}
												else if(remainder<2.5 && remainder>0)
												{
													var poor=numstring.substr(numstring.indexOf(".")-1,1);

													if(poor>=5)
													{
														roundedTotal=(parseInt(selectionsTotals[k]-poor))+5;
													}
													else
													{
														roundedTotal=parseInt(selectionsTotals[k]-poor);
													}
												}
												else if(parseInt(remainder)==0)
												{
													roundedTotal=parseInt(selectionsTotals[k]);
												}
											}
											else if(selectionsTotals[k]>=50)
											{
												var remainder=parseInt(selectionsTotals[k]%10);
												if(remainder>=5)
												{
													roundedTotal=(parseInt(selectionsTotals[k])-remainder)+10;
												}
												else
												{
													roundedTotal=parseInt(selectionsTotals[k])-remainder;
												}
											}
										}
										else
										{
											roundedTotal=Math.round(selectionsTotals[k]);
										}
										
										var _span_b=document.createElement('span');
										//_span.setAttribute("class","hiddenspan");
										_span_b.style.display="none";
										_span_b.style.fontSize="4px";
										_txt=document.createTextNode(selectionsTotals[k]);
										_span_b.appendChild(_txt);
										var _roundedTotal_b=document.createTextNode(roundedTotal);
										selectionsTotalRowCells[k+shiftAmt].replaceChild(_roundedTotal_b, selectionsTotalRowCells[k+shiftAmt].firstChild);
										//alert(menuTotalRowCells[k+shiftAmt].lastChild.nodeName);
										if(selectionsTotalRowCells[k+shiftAmt].lastChild.nodeName.toLowerCase()=="#text")
										{
											selectionsTotalRowCells[k+shiftAmt].appendChild(_span_b);
										}
										else
										{
											selectionsTotalRowCells[k+shiftAmt].replaceChild(_span_b, selectionsTotalRowCells[k+shiftAmt].lastChild);
										}
									//selectionsTotalRowCells[k+shiftAmt].replaceChild(document.createTextNode(roundedTotal), selectionsTotalRowCells[k+shiftAmt].firstChild);

								// Allergens Display
								} else {

									if (selectionsTotalRowCells[k+shiftAmt].firstChild.nodeName.toLowerCase() == 'img') {
										if (selectionsTotals[k] > 0) {
											selectionsTotalRowCells[k+shiftAmt].firstChild.src = selectionX.src;
										} else {
											selectionsTotalRowCells[k+shiftAmt].firstChild.src = selectionNoX.src;
										}
									}

								}

							}

							// Since we output the totals, we're done, so we need to start over
							resetTotals = true;

						}

					}
				}
			}

			//=============================================================
			// CALCULATE NUMBERS FOR EACH ITEM IN THE MENU SECTION
			// Loop through table rows backwards since that way the detail rows will come first
			if (section == 'menus') {

				var menuRows = document.getElementById('menus_body').getElementsByTagName('tr');

				var resetTotals = true;

				// Loop through the rows backwards so the detail rows come first
				for (j=(menuRows.length-1); j>=0; j--) {
					if (menuRows[j].id) {

						/////////////////////
						// DETAIL ROW
						// If we find a detail row
						if (menuRows[j].id.indexOf('_detail_') >= 0) {

							// Check if we need to reset the totals
							if (resetTotals == true) {

								// We need the itemId to identify the related totals row
								var itemId = menuRows[j].id.split('_detail_')[0];

								// Create an array to store the totals,
								// use the totals row to determine which columns we're using
								var menuTotals = new Array();
                                var menuOunce = 0;
								var menuTotalsRow = document.getElementById(itemId+'_total');
								var menuTotalsRowCells = menuTotalsRow.getElementsByTagName('td');
								var m = 0;
								for (k=4; k<menuTotalsRowCells.length; k++) {
									// Identify cells expecting to receive a total
									if (isNumeric(parseFloat(menuTotalsRowCells[k].firstChild.nodeValue)) ||
											(menuTotalsRowCells[k].firstChild.nodeName.toLowerCase() == 'img' &&
												menuTotalsRowCells[k].firstChild.src.indexOf('dot') >= 0)) {
										menuTotals[m] = 0;
										m++;
									}
								}

								resetTotals = false;

							}

							// Get detail row cells
							var menuDetailRowCells = menuRows[j].getElementsByTagName('td');

							// Find out if we should add this row
							if (menuDetailRowCells[2].firstChild.firstChild.nodeName.toLowerCase() == 'img') {
								var imageSrc = menuDetailRowCells[2].firstChild.firstChild.src;
							}

							// If the checkbox is checked, add this row
							if (imageSrc.indexOf('_checked') >= 0) {

								// Add the numbers in this row
								var shiftAmt = 5;
								// Add the values
								
								for (k=0; k<menuTotals.length; k++) {
									if (menuDetailRowCells[k+shiftAmt].firstChild.nodeName.toLowerCase() == 'img') {
										if (menuDetailRowCells[k+shiftAmt].firstChild.src.indexOf(selectionX.src) >= 0) {
											menuTotals[k] += 1;
										} else {
											menuTotals[k] += 0;
										}
//								} else if (menuDetailRowCells[k+shiftAmt].firstChild.nodeValue == '&lt; 1') {
//									menuTotals[k] += 0.01;
									} else if (menuDetailRowCells[k+shiftAmt].lastChild.innerHTML == '*') {
										menuTotals[k] += 0;
									} else if (isNumeric(parseFloat(menuDetailRowCells[k+shiftAmt].lastChild.innerHTML))) {
                                        menuTotals[k] += parseFloat(menuDetailRowCells[k+shiftAmt].lastChild.innerHTML);
									}
								}
								

							}

						/////////////////////
						// TOTAL ROW
						// See if this is the totals row for the detail rows we've been summing
						} else if (menuRows[j].id.indexOf(itemId+'_total') >= 0) {
							// Output the totals
							var menuTotalRowCells = menuRows[j].getElementsByTagName('td');

							var shiftAmt = 4;
							// Insert the values
							for (k=0; k<menuTotals.length; k++) {

								// Nutrition Display
								if (menuRows[j].id.indexOf('nutrition_') >= 0) {

									if ((k + shiftAmt) >= 5 && (k + shiftAmt) <= 6) {
											if (menuTotals[k]<5) {
											
											roundedTotal=0;
											}
											else if (menuTotals[k] <= 50) {
												var remainder=menuTotals[k]%5;
												if(remainder>2.5)
												{
													roundedTotal=parseInt(menuTotals[k]-remainder)+5;
												}
												else
												{
													roundedTotal=parseInt(menuTotals[k]-remainder);
												}
											}
											else
											{
												var remainder=menuTotals[k]%10;
												if(remainder>=5)
												{
													roundedTotal=parseInt(menuTotals[k]-remainder+10);
												}
												else
												{
													roundedTotal=parseInt(menuTotals[k]-remainder);
												}
											}
										}
										else if((k+shiftAmt)>=7 && (k+shiftAmt)<=9)
										{
											if(menuTotals[k]<0.5)
											{
												roundedTotal=0;
											}
											else if(menuTotals[k]<5)
											{
												var poor=menuTotals[k]-parseInt(menuTotals[k]);
												if(poor>=0.5)
												{
													if((poor-0.5-0.25)>=0)
													{
														roundedTotal=parseInt(menuTotals[k]+1);
													}
													else
													{
														roundedTotal=parseInt(menuTotals[k])+0.5;
													}
												}
												else
												{
													if((poor-0.25)>=0)
													{
														roundedTotal=parseInt(menuTotals[k])+0.5;	
													}
													else
													{
														roundedTotal=parseInt(menuTotals[k]);
													}
												}
											}
											else
											{
												roundedTotal=Math.round(menuTotals[k]);
											}
										}
										else if((k+shiftAmt)==10)
										{
											if(menuTotals[k]<2)
											{
												roundedTotal=0;
											}
											else if(menuTotals[k]>=2 && menuTotals[k]<5)
											{
												roundedTotal=5;
											}
											else
											{
												var remainder=menuTotals[k]%5;
												var numstring=menuTotals[k]+".";
												var poor=numstring.substr(numstring.indexOf(".")-1,1);

												if(remainder>=2.5)
												{
													if(poor<5)
													{
														roundedTotal=parseInt(menuTotals[k]-poor+5);
													}
													else
													{
														roundedTotal=parseInt(menuTotals[k]-poor+10);
													}
												}
												else
												{
													if(remainder<1)
													{
														roundedTotal=parseInt(menuTotals[k]);
													}
													else
													{
														roundedTotal=parseInt(menuTotals[k]-remainder);
													}
													
												}
											}
										}
										else if((k+shiftAmt)==11)
										{
											if(menuTotals[k]<5)
											{
												roundedTotal=0;
											}
											else if(menuTotals[k]<140)
											{
												var remainder=menuTotals[k]%5;
												var numstring=menuTotals[k]+".";
												var poor=numstring.substr(numstring.indexOf(".")-1,1);

												if(remainder>=2.5)
												{
													if(poor>5)
													{
														roundedTotal=parseInt(menuTotals[k]-poor+10);
													}
													else
													{
														roundedTotal=parseInt(menuTotals[k]-poor+5);
													}
												}
												else
												{
													roundedTotal=parseInt(menuTotals[k]-remainder);
												}
											}
											else
											{
												var remainder=menuTotals[k]%10;
												if(remainder>=5)
												{
													roundedTotal=parseInt(menuTotals[k]-remainder+10);
												}
												else
												{
													roundedTotal=parseInt(menuTotals[k]-remainder);
												}
											}
										}
										else if((k+shiftAmt)>=12 && (k+shiftAmt)<=15)
										{
											if(menuTotals[k]<0.5)
											{
												roundedTotal=0;
											}
											else if(menuTotals[k]<1)
											{
												roundedTotal=1;
											}
											else
											{
												roundedTotal=Math.round(menuTotals[k]);
											}
										}
										else if((k+shiftAmt)>=16 && (k+shiftAmt)<=19)
										{
											switch(k+shiftAmt)
											{
												case 16:
													menuTotals[k] = (menuTotals[k]/5000)*100;
													break;
												case 17:
													menuTotals[k] = (menuTotals[k]/60)*100;
													break;
												case 18:
													menuTotals[k] = (menuTotals[k]/1000)*100;
													break;
												case 19:
													menuTotals[k] = (menuTotals[k]/18)*100;
													break;
											}
											
											if(menuTotals[k]<2)
											{
												roundedTotal='*';
											}
											else if(menuTotals[k]>=2 && menuTotals[k]<=10)
											{
												var remainder=parseInt(menuTotals[k]%2);
												if(remainder==1)
												{
													roundedTotal=parseInt(menuTotals[k]+1);
												}
												else
												{
													roundedTotal=parseInt(menuTotals[k]);
												}
											}
											else if(menuTotals[k]>10 && menuTotals[k]<50)
											{
												//menuTotals[k]=menuTotals[k].toFixed(1);
											 	//alert(menuTotals[k]);
												var remainder=menuTotals[k]%5;
												var numstring=menuTotals[k]+".";
												var poor=numstring.substr(numstring.indexOf(".")-1,1);
												if(remainder>=2.5)
												{
													if(poor>5)
													{
														roundedTotal=parseInt(menuTotals[k]-poor)+10;
													}
													else
													{
														roundedTotal=parseInt(menuTotals[k]-poor)+5;
													}
												}
												else if(remainder<2.5 && remainder>0)
												{
													var poor=numstring.substr(numstring.indexOf(".")-1,1);

													if(poor>=5)
													{
														roundedTotal=(parseInt(menuTotals[k]-poor))+5;
													}
													else
													{
														roundedTotal=parseInt(menuTotals[k]-poor);
													}
												}
												else if(parseInt(remainder)==0)
												{
													roundedTotal=parseInt(menuTotals[k]);
												}
											}
											else if(menuTotals[k]>=50)
											{
												var remainder=parseInt(menuTotals[k]%10);
												if(remainder>=5)
												{
													roundedTotal=(parseInt(menuTotals[k])-remainder)+10;
												}
												else
												{
													roundedTotal=parseInt(menuTotals[k])-remainder;
												}
											}
										}
										else
										{
											roundedTotal=Math.round(menuTotals[k]);
										}

									// Main menu item group totals
									menuTotalRowCells[k+shiftAmt].replaceChild(document.createTextNode(roundedTotal), menuTotalRowCells[k+shiftAmt].firstChild);
									var _span=document.createElement('span');
									_span.style.display="none";
									_span.style.fontSize="4px";
									_txt=document.createTextNode(menuTotals[k]);
									_span.appendChild(_txt);
									if(menuTotalRowCells[k+shiftAmt].lastChild.nodeName.toLowerCase()=="#text")
									{
										menuTotalRowCells[k+shiftAmt].appendChild(_span);
									}
									else
									{
										menuTotalRowCells[k+shiftAmt].replaceChild(_span, menuTotalRowCells[k+shiftAmt].lastChild);
									}
								// Allergens Display
								} else {

									if (menuTotalRowCells[k+shiftAmt].firstChild.nodeName.toLowerCase() == 'img') {
										if (menuTotals[k] > 0) {
											menuTotalRowCells[k+shiftAmt].firstChild.src = selectionX.src;
										} else {
											menuTotalRowCells[k+shiftAmt].firstChild.src = selectionNoX.src;
										}
									}

								}

							}

							// Since we output the totals, we're done, so we need to start over
							resetTotals = true;
						}
					}
				}
			}
		}

		function calculateMealTotals() {
//alert('calcMealTotals');
			// Get selections object and rows
			var selectionsObj = document.getElementById('selections_body');
			var selectionsRows = selectionsObj.getElementsByTagName('tr');

			if (current_dataType == 'nutrition') {
				var mealTotalsRow = document.getElementById('nutrition_selections_sum');
			} else {
				var mealTotalsRow = document.getElementById('allergens_selections_sum');
			}

			// Create an array to store the totals,
			// use the totals row to determine which columns we're using
			var mealTotals = new Array();
            var mealOunceTotals = 0;
			var mealTotalsRowCells = mealTotalsRow.getElementsByTagName('td');
			var m = 0;

			for (k=5; k<mealTotalsRowCells.length; k++) {
				// Identify cells expecting to receive a total
				if (isNumeric(parseFloat(mealTotalsRowCells[k].firstChild.nodeValue)) ||
					  mealTotalsRowCells[k].firstChild.nodeValue == '*' ||
						(mealTotalsRowCells[k].firstChild.nodeName.toLowerCase() == 'img' &&
							mealTotalsRowCells[k].firstChild.src.indexOf('dot') >= 0)) {
					mealTotals[m] = 0;
					m++;
				}
			}

			var shiftAmt = 4;

			// Sum the total rows
			for (i=0; i<selectionsRows.length; i++) {
				if (selectionsRows[i].id) {

					if (selectionsRows[i].id.indexOf(current_dataType) >= 0 &&
							selectionsRows[i].id.indexOf('_total') >= 0) {

						var selectionsRowCells = selectionsRows[i].getElementsByTagName('td');
                        var type = selectionsRows[i].getAttribute('type'); // oz or g

						// Add the values
						for (k=0; k<mealTotals.length; k++) {

							if (selectionsRowCells[k+shiftAmt].firstChild.nodeName.toLowerCase() == 'img') {
								if (selectionsRowCells[k+shiftAmt].firstChild.src.indexOf(selectionX.src) >= 0) {
									mealTotals[k] += 1;
								} else {
									mealTotals[k] += 0;
								}
//						} else if (selectionsRowCells[k+shiftAmt].firstChild.nodeValue == '&lt; 1') {
//							mealTotals[k] += 0.01;
							} else if (selectionsRowCells[k+shiftAmt].lastChild.innerHTML == '*') {
								mealTotals[k] += 0;
							} else if (isNumeric(parseFloat(selectionsRowCells[k+shiftAmt].lastChild.innerHTML))) {
                                if ( k+shiftAmt == 4 && type == "oz") {
                                    mealOunceTotals += parseFloat(selectionsRowCells[k+shiftAmt].lastChild.innerHTML);
                                } else {
                                    mealTotals[k] += parseFloat(selectionsRowCells[k+shiftAmt].lastChild.innerHTML);
                                }
							}
						}
					}
				}
			}

			var shiftAmt = 5;

			// Display the result
			for (k=0; k<mealTotals.length; k++) {

				// Nutrition Display
				if (current_dataType == 'nutrition') {

					/*if (mealTotals[k] == 0 && mealOunceTotals == 0 ) {
						if (k+shiftAmt >= 17) {
							roundedTotal = '*';
						} else {
							roundedTotal = 0;
						}
//					} else if (mealTotals[k] < 1) {
//						roundedTotal = '&lt; 1';
					} else if (k+shiftAmt == 10) { // Bottom Menu ( 8 - 10 == Fat columns.
                        //roundedTotal = customRound(mealTotals[k]);
						roundedTotal = Math.round(mealTotals[k]*10)/10;
                    } else {
                        roundedTotal = Math.round(mealTotals[k]);
                        if ( k+shiftAmt == 5 ) {
                            roundedTotal = roundedTotal + "g";
                            if ( mealOunceTotals > 0 ) {
                                roundedTotal = roundedTotal + "\n" + mealOunceTotals + "oz";
                            }
                        }
                        
                    }*/
					if((k+shiftAmt)>=6 && (k+shiftAmt)<=7)
										{
											if(mealTotals[k]<5)
											{
												roundedTotal=0;
											}
											else if(mealTotals[k]<=50)
											{
												var remainder=mealTotals[k]%5;
												if(remainder>2.5)
												{
													roundedTotal=parseInt(mealTotals[k]-remainder)+5;
												}
												else
												{
													roundedTotal=parseInt(mealTotals[k]-remainder);
												}
											}
											else
											{
												var remainder=mealTotals[k]%10;
												if(remainder>=5)
												{
													roundedTotal=parseInt(mealTotals[k]-remainder+10);
												}
												else
												{
													roundedTotal=parseInt(mealTotals[k]-remainder);
												}
											}
										}
										else if((k+shiftAmt)>=8 && (k+shiftAmt)<=10)
										{
											if(mealTotals[k]<0.5)
											{
												roundedTotal=0;
											}
											else if(mealTotals[k]<5)
											{
												var poor=mealTotals[k]-parseInt(mealTotals[k]);
												if(poor>=0.5)
												{
													if((poor-0.5-0.25)>=0)
													{
														roundedTotal=parseInt(mealTotals[k]+1);
													}
													else
													{
														roundedTotal=parseInt(mealTotals[k])+0.5;
													}
												}
												else
												{
													if((poor-0.25)>=0)
													{
														roundedTotal=parseInt(mealTotals[k])+0.5;	
													}
													else
													{
														roundedTotal=parseInt(mealTotals[k]);
													}
												}
											}
											else
											{
												roundedTotal=Math.round(mealTotals[k]);
											}
										}
										else if((k+shiftAmt)==11)
										{
											if(mealTotals[k]<2)
											{
												roundedTotal=0;
											}
											else if(mealTotals[k]>=2 && mealTotals[k]<5)
											{
												roundedTotal=5;
											}
											else
											{
												var remainder=mealTotals[k]%5;
												var numstring=mealTotals[k]+".";
												var poor=numstring.substr(numstring.indexOf(".")-1,1);

												if(remainder>=2.5)
												{
													if(poor<5)
													{
														roundedTotal=parseInt(mealTotals[k]-poor+5);
													}
													else
													{
														roundedTotal=parseInt(mealTotals[k]-poor+10);
													}
												}
												else
												{
													if(remainder<1)
													{
														roundedTotal=parseInt(mealTotals[k]);
													}
													else
													{
														roundedTotal=parseInt(mealTotals[k]-remainder);
													}
													
												}
											}
										}
										else if((k+shiftAmt)==12)
										{
											if(mealTotals[k]<5)
											{
												roundedTotal=0;
											}
											else if(mealTotals[k]<140)
											{
												var remainder=mealTotals[k]%5;
												var numstring=mealTotals[k]+".";
												var poor=numstring.substr(numstring.indexOf(".")-1,1);

												if(remainder>=2.5)
												{
													if(poor>5)
													{
														roundedTotal=parseInt(mealTotals[k]-poor+10);
													}
													else
													{
														roundedTotal=parseInt(mealTotals[k]-poor+5);
													}
												}
												else
												{
													roundedTotal=parseInt(mealTotals[k]-remainder);
												}
											}
											else
											{
												var remainder=mealTotals[k]%10;
												if(remainder>=5)
												{
													roundedTotal=parseInt(mealTotals[k]-remainder+10);
												}
												else
												{
													roundedTotal=parseInt(mealTotals[k]-remainder);
												}
											}
										}
										else if((k+shiftAmt)>=13 && (k+shiftAmt)<=16)
										{
											if(mealTotals[k]<0.5)
											{
												roundedTotal=0;
											}
											else if(mealTotals[k]<1)
											{
												roundedTotal=1;
											}
											else
											{
												roundedTotal=Math.round(mealTotals[k]);
											}
										}
										else if((k+shiftAmt)>=17 && (k+shiftAmt)<=20)
										{
											if(mealTotals[k]<2)
											{
												roundedTotal=0;
											}
											else if(mealTotals[k]>=2 && mealTotals[k]<=10)
											{
												var remainder=parseInt(mealTotals[k]%2);
												if(remainder==1) {
													roundedTotal=parseInt(mealTotals[k]+1);
												}
												else {
													roundedTotal=parseInt(mealTotals[k]);
												}
											}
											else if(mealTotals[k]>10 && mealTotals[k]<50) {
												
												var remainder=mealTotals[k]%5;
												var numstring=mealTotals[k]+".";
												var poor=numstring.substr(numstring.indexOf(".")-1,1);

												//alert(poor);
												if(remainder>=2.5)
												{
													if(poor>5)
													{
														roundedTotal=parseInt(mealTotals[k]-poor)+10;
													}
													else
													{
														roundedTotal=parseInt(mealTotals[k]-poor)+5;
													}
												}
												else if(remainder<2.5 && remainder>0)
												{
													var poor=numstring.substr(numstring.indexOf(".")-1,1);

													if(poor>=5)
													{
														roundedTotal=(parseInt(mealTotals[k]-poor))+5;
													}
													else
													{
														roundedTotal=parseInt(mealTotals[k]-poor);
													}
												}
												else if(parseInt(remainder)==0)
												{
													roundedTotal=parseInt(mealTotals[k]);
												}
											}
											else if(mealTotals[k]>=50)
											{
												var remainder=parseInt(mealTotals[k]%10);
												if(remainder>=5)
												{
													roundedTotal=(parseInt(mealTotals[k])-remainder)+10;
												}
												else
												{
													roundedTotal=parseInt(mealTotals[k])-remainder;
												}
											}
										}
										else
										{
											roundedTotal=Math.round(mealTotals[k]);
										}

                    // Personalized Meal Total
					mealTotalsRowCells[k+shiftAmt].replaceChild(document.createTextNode(roundedTotal), mealTotalsRowCells[k+shiftAmt].firstChild);

				// Allergens Display
				} else {

					if (mealTotalsRowCells[k+shiftAmt].firstChild.nodeName.toLowerCase() == 'img') {
						if (mealTotals[k] > 0) {
							mealTotalsRowCells[k+shiftAmt].firstChild.src = selectionX.src;
						} else {
							mealTotalsRowCells[k+shiftAmt].firstChild.src = selectionNoX.src;
						}
					}

				}

			}

		}

		function toggleCheckbox(imageObj) {

			// Derive row id
			var thisRowId = imageObj.parentNode.parentNode.id;
			var thisItemId = getItemId(thisRowId);

			if (thisRowId.indexOf('nutrition') >= 0) {
				rowType = 'nutrition';
			} else {
				rowType = 'allergens';
			}

			// Get row references (because both types might exist, we need to
			// check for and update both)
			var thisRowObj = document.getElementById(thisRowId);

			if (rowType == 'nutrition') {
				var otherRowObj = document.getElementById(thisRowId.replace(/nutrition/, 'allergens'));
			} else {
				var otherRowObj = document.getElementById(thisRowId.replace(/nutrition/, 'allergens'));
			}

			// We know this object exists
			// Get the row cells
			var thisRowCells = thisRowObj.getElementsByTagName('td');

			// Get the checkbox image for this row
			var thisRowCheckboxImage = thisRowCells[checkboxImgCellPosition].firstChild.firstChild;

			// We need to test for this one
			if (otherRowObj && otherRowObj.id) {
				// Get the row cells
				var otherRowCells = otherRowObj.getElementsByTagName('td');
				// Get the checkbox image for this row
				var otherRowCheckboxImage = thisRowCells[checkboxImgCellPosition].firstChild.firstChild;
			} else {
				var otherRowCells = false;
				var otherRowCheckboxImage = false;
			}

			for (i=checkboxImgCellPosition+1; i<thisRowCells.length; i++) {

/*
 * Not the most efficient method of handling both scenarios... but it should work for now
 */
				// If it's checked, it's going to be unchecked
				if (thisRowCheckboxImage.src.indexOf('_checked') >= 0) {
				
					if(readCookie(thisRowId) !== false){
						
						eraseCookie(thisRowId);
					}
					if (thisRowCells[i].firstChild.nodeName.toLowerCase() == 'img' ||
					    (otherRowCells && otherRowCells[i].firstChild.nodeName.toLowerCase() == 'img')) {
						// If the image is NOT the no X image, then show the part X image
						// (we can't just replace it with the no X image or we can't tell which had
						// an image to begin with and which didn't later on)
						if (thisRowCells[i].firstChild.src.indexOf(selectionNoX.src) < 0) {
							thisRowCells[i].firstChild.src = selectionPartX.src;
						}
						if (otherRowCells && otherRowCells[i].firstChild.src.indexOf(selectionNoX.src) < 0) {
							otherRowCells[i].firstChild.src = selectionPartX.src;
						}
					} else if (thisRowCells[i].firstChild.nodeName.toLowerCase() == '#text' ||
										 otherRowCells && otherRowCells[i].firstChild.nodeName.toLowerCase() == '#text') {
						if (thisRowCells[i].firstChild.nodeValue.replace(/\s/,'').length > 0) {
							// Grey out to show it's not included
							thisRowCells[i].style.color = '#999';
							thisRowCells[i].style.textDecoration = 'line-through';
						}
						if (otherRowCells && otherRowCells[i].firstChild.nodeValue.replace(/\s/,'').length > 0) {
							// Grey out to show it's not included
							otherRowCells[i].style.color = '#999';
							otherRowCells[i].style.textDecoration = 'line-through';
						}
					}
				// If it's unchecked, it's going to be checked
				} else if (thisRowCheckboxImage.src.indexOf('_unchecked') >= 0) {
					
					if(readCookie(thisRowId) <=0){
						
						createCookie(thisRowId,1,7);
					}
					if (thisRowCells[i].firstChild.nodeName.toLowerCase() == 'img' ||
					    (otherRowCells && otherRowCells[i].firstChild.nodeName.toLowerCase() == 'img')) {
						// If the image is NOT the no X image, then show the part X image
						// (we can't just replace it with the no X image or we can't tell which had
						// an image to begin with and which didn't later on)
						if (thisRowCells[i].firstChild.src.indexOf(selectionNoX.src) < 0) {
							thisRowCells[i].firstChild.src = selectionX.src;
						}
						if (otherRowCells && otherRowCells[i].firstChild.src.indexOf(selectionNoX.src) < 0) {
							otherRowCells[i].firstChild.src = selectionX.src;
						}
					} else if (thisRowCells[i].firstChild.nodeName.toLowerCase() == '#text' ||
										 otherRowCells && otherRowCells[i].firstChild.nodeName.toLowerCase() == '#text') {
						if (thisRowCells[i].firstChild.nodeValue.replace(/\s/,'').length > 0) {
							// Return to defaults
							thisRowCells[i].style.color = '';
							thisRowCells[i].style.textDecoration = '';
						}
						if (otherRowCells && otherRowCells[i].firstChild.nodeValue.replace(/\s/,'').length > 0) {
							// Return to defaults
							thisRowCells[i].style.color = '';
							thisRowCells[i].style.textDecoration = '';
						}
					}
				}

			}

			// Swap the image
			if (thisRowCheckboxImage.src.indexOf('_checked') >= 0) {
				thisRowCheckboxImage.src = checkboxUnchecked.src;
				if (otherRowCheckboxImage) {
					otherRowCheckboxImage.src = checkboxUnchecked.src;
				}
			} else if (thisRowCheckboxImage.src.indexOf('_unchecked') >= 0) {
				thisRowCheckboxImage.src = checkboxChecked.src;
				if (otherRowCheckboxImage) {
					otherRowCheckboxImage.src = checkboxChecked.src;
				}
			}

			if (thisRowId.indexOf('selected_') >= 0) {
				calculateItemTotals('selections');
				calculateMealTotals();
				////click_showDatatype();
			} else {
				calculateItemTotals('menus');
			}


		}

		function setSectionTitle(theTitle) {

			document.getElementById('menu_nutrition_head_title').replaceChild(document.createTextNode(theTitle), document.getElementById('menu_nutrition_head_title').firstChild);
			document.getElementById('menu_allergens_head_title').replaceChild(document.createTextNode(theTitle), document.getElementById('menu_allergens_head_title').firstChild);

		}

		// There are still cases when drawers are open when they shouldn't be
		// or arrows are tipped when the drawer is closed. So in the interest of making
		// this work... I'm resorting to this... :-(
		function correctRowDisplay() {

			// Get selections object and rows
			var selectionsObj = document.getElementById('selections_body');
			var selectionsRows = selectionsObj.getElementsByTagName('tr');

			for (i=0; i<selectionsRows.length; i++) {
				if (selectionsRows[i].id) {

					// If this isn't the drawer that is open
					if (getItemId(selectionsRows[i].id) != open_selections_drawer) {
						// hide the detail rows
						if (selectionsRows[i].id.indexOf('_detail_') >= 0) {
							selectionsRows[i].style.display = 'none';
						}
						// tip the arrow to the right
						if (selectionsRows[i].id.indexOf('_total') >= 0) {
							// Get images from the row
							var rowImages = selectionsRows[i].getElementsByTagName('img');
							if (rowImages[arrowImgPosition].src.indexOf('arrow') >= 0) {
								rowImages[arrowImgPosition].src = arrowRight.src;
							}
						}
					// If this is the drawer that is supposed to be open
					} else if (getItemId(selectionsRows[i].id) == open_selections_drawer) {
						// show the detail rows
						if (selectionsRows[i].id.indexOf('_detail_') >= 0) {
							selectionsRows[i].style.display = '';
						}
						// tip the arrow down
						if (selectionsRows[i].id.indexOf('_total') >= 0) {
							// Get images from the row
							var rowImages = selectionsRows[i].getElementsByTagName('img');
							if (rowImages[arrowImgPosition].src.indexOf('arrow') >= 0) {
								rowImages[arrowImgPosition].src = arrowDown.src;
							}
						}
					}

				}
			}
            
			// Get menus object and rows
			var menusObj = document.getElementById('menus_body');
			var menusRows = menusObj.getElementsByTagName('tr');

			for (i=0; i<menusRows.length; i++) {
				if (menusRows[i].id) {

					// If this isn't the drawer that is open
					if (getItemId(menusRows[i].id) != open_menu_drawer) {
						// hide the detail rows
						if (menusRows[i].id.indexOf('_detail_') >= 0) {
							menusRows[i].style.display = 'none';
						}
						// tip the arrows to the right
						if (menusRows[i].id.indexOf('_detail_') >= 0) {
							// Get images from the row
							var rowImages = menusRows[i].getElementsByTagName('img');
							if (rowImages[arrowImgPosition].src.indexOf('arrow') >= 0) {
								rowImages[arrowImgPosition].src = arrowRight.src;
							}
						}
					// If this is the drawer that is supposed to be open
					} else if (getItemId(menusRows[i].id) == open_menu_drawer) {
						// hide the detail rows
						if (menusRows[i].id.indexOf('_detail_') >= 0) {
							menusRows[i].style.display = '';
						}
						// tip the arrows to the right
						if (menusRows[i].id.indexOf('_detail_') >= 0) {
							// Get images from the row
							var rowImages = menusRows[i].getElementsByTagName('img');
							if (rowImages[arrowImgPosition].src.indexOf('arrow') >= 0) {
								rowImages[arrowImgPosition].src = arrowDown.src;
							}
						}
					}

				}
			}


		}

		//-------------------------------------------------------------------
		// isNumeric(value)
		//   Returns true if value contains a positive float value
		//-------------------------------------------------------------------
		function isNumeric(val){return(parseFloat(val,10)==(val*1));}

		//
		// getPageScroll()
		// Returns array with x,y page scroll values.
		// Core code from - quirksmode.org
		//
		function getPageScroll(){

			var yScroll;

			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
			} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
			} else if (document.body) {// all other Explorers
				yScroll = document.body.scrollTop;
			}

			arrayPageScroll = new Array('',yScroll)
			return arrayPageScroll;
		}


		//
		// getPageSize()
		// Returns array with page width, height and window width, height
		// Core code from - quirksmode.org
		// Edit for Firefox by pHaez
		//
		function getPageSize(){

			var xScroll, yScroll;

			if (window.innerHeight && window.scrollMaxY) {
				xScroll = document.body.scrollWidth;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}

			var windowWidth, windowHeight;
			if (self.innerHeight) {	// all except Explorer
				windowWidth = self.innerWidth;
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}

			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else {
				pageHeight = yScroll;
			}

			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){
				pageWidth = windowWidth;
			} else {
				pageWidth = xScroll;
			}


			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
			return arrayPageSize;
		}
	
	function expandPersonalItems(){
		var bodyObj = document.getElementById('selections_body');
		var bodyRows = bodyObj.getElementsByTagName('tr');

			// For each row, looping backwards
  		for (var i=(bodyRows.length-1); i>=0; i--) {
  			if (bodyRows[i].id) {

				bodyRows[i].style.display = '';

			// For the total row that called this function, rotate the image
			} else if (bodyRows[i].id.indexOf('_total') >= 0) {

				// Get images from the row
				var rowImages = bodyRows[i].getElementsByTagName('img');
				rowImages[arrowImgPosition].src = arrowDown.src;
				

			}

  			

  		}
	}
	function click_showDatatype()
	{
		//document.getElementById("show_datatype").value=click;
		var os=getOs();
		if(os==1)
		{
			document.getElementById("show_datatype").click();
		}
		else
		{
			var evt = document.createEvent("MouseEvents"); 
			evt.initEvent("click", true, true); 
			document.getElementById("show_datatype").dispatchEvent(evt); 
		}
	}
	function getOs()
	{
	   if(navigator.userAgent.indexOf("MSIE")>0)return 1;
	   if(isFirefox=navigator.userAgent.indexOf("Firefox")>0)return 2;
	   if(isSafari=navigator.userAgent.indexOf("Safari")>0)return 3;   
	   if(isCamino=navigator.userAgent.indexOf("Camino")>0)return 4;
	   if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0)return 5;
	   return 0;
	}