var numOfCat = 30;
var startOfMealsCat = 25;
var fastFoodCat = 8;
var numExercise = 64;
var Totals = new Array();
Totals[1]=0;
var numNutrients = 32;
var Cal;
var rows=8;
var NumList=0;

var IncludeMealInFullLabel = true;
var FullLabelWidth=300;
if (IncludeMealInFullLabel) FullLabelWidth=580;

var maxSecondWindow = 6;
var secondWindow = new Array();
for (var j=0; j<=maxSecondWindow; j++) 
{
	secondWindow[j] = null;
}

var labelHeight;
if (screen.height <= 600)
{
	labelHeight=520;
} 
else 
{
	labelHeight=620;
}

function ClearList(combo)
{
	var x = combo.options.length;
	for (var i = 0; i<=x; i++)
	{		
		combo.remove(0);
	}
}

function FillFirstBoxes()
{	
	var combo = document.getElementById("Categories1");
	var exercise;
	var j = 0;
	for (var i = StartPrepareMealCat; i<=numOfCat; i++)
	{
		combo[j++] = new Option(FoodCategory[i]);
	}
	combo[j++] = new Option(FoodCategory[fastFoodCat]);
	for (var i = 0; i<StartPrepareMealCat; i++)
	{
		if (i != fastFoodCat) combo[j++] = new Option(FoodCategory[i]);
	}

	exercise = document.getElementById("Exercise1");
	for (var k=0; k<=numExercise; k++)
	{
		exercise[k] = new Option(Exercise[k]);
	}
	document.getElementById("Label4").style.display="none";
	CalcNutrients();
	document.getElementById("PrintRow").style.display="none";
	if (screen.width > 800)
	{
		document.getElementById("Column3").width="270px";
	}
	document.getElementById("NutrFacts2").style.display="none";
}

function FillSecondBox(combo1, combo2, servnum, servdes)
{
	var j;	
	ClearList(combo2);
	servdes.value = "";
	var Selection = combo1[combo1.selectedIndex].text;
	var k = 1;
	for (j = 1; j<=numOfCat; j++)
	{	
		if (Selection == FoodCategory[j])
		{
			combo2[0] = new Option("Select Food");
			for (var i = numCat[j-1]+1; i<=numCat[j]; i++)
			{
				combo2[k] = new Option(N[0][i]);
				k ++; 
			}
			break;
		}
	}

	ClearList(servnum);
	if (j>=startOfMealsCat)
	{	
		servnum[0] = new Option("1");
		servnum.selectedIndex = 0;
	}
	else
	{
		servnum[0] = new Option(".25");
		servnum[1] = new Option(".5");
		servnum[2] = new Option("1");
		servnum[3] = new Option("1.5");
		servnum[4] = new Option("2");
		servnum[5] = new Option("2.5");
		servnum[6] = new Option("3");
		servnum.selectedIndex = 2;
	}
	if (combo2.options.length == 1)
	{
		alert("Please select an individual food item or a prepared meal.");
		document.getElementById("Categories1").selectedIndex=0;
	}
}

function GetServingandCals(combo1, combo2, servdes)
{
	combo2.selectedIndex = Math.min(2,combo2.options.length-1);
	var index = Get_Food_Index(combo1[combo1.selectedIndex].text);
	servdes.value = N[2][index];
}	

function GetCals(Selection)
{
	var index = Get_Food_Index(combo1[combo1.selectedIndex].text);
	var Cal = N[1][index];
	if (isNaN(Cal))
	{
		Cal = 0;
	}
	Cal=Math.round(Cal);
	return Cal; 
}	

function CalcTime()
{
	var exercise = document.getElementById("Exercise1");
	var Selection = exercise[exercise.selectedIndex].text;
	var EnteredWeight = document.getElementById("Weight").value;
	var ExerciseBurn;
	var Time;
	var Hours;
	Calories();
	for (var i=1; i<=numExercise; i++)
	{
		if (Selection == Exercise[i])
		{
			ExerciseBurn=CalBurn[i];
		}
	}
	Time = Totals[28]/(EnteredWeight*ExerciseBurn);
	Time = Math.round(Time);
	Hours = Time/60;
	Hours=Math.floor(Hours);
	Time = Time - (Hours*60)
	if (isNaN(Time))
	{	
		Time = 0;
		Hours = 0;
	}
	if (Hours==0)
	{
		if (Time==0)
		{
			document.getElementById("Time").value="";
		}
		else
		{
			document.getElementById("Time").value=Time+"min";
		}
	}
	else
	{
		document.getElementById("Time").value=Hours+"hr "+Time+"min";
	}
}

function CalcNutrients()
{
	var Selection=new String();
	var index;
	var Serving;
	var Combos2;
	var Percent;
	var RoundedTotal;
	var List = document.getElementById("MealList");
	var pos;
	var pos2;
	for (x=3; x<=numNutrients; x++)
	{
		Totals[x]=0;
	}
	
	for (k=0; k <List.length; k++)
	{
		Selection = List[k].text;
		pos = Selection.lastIndexOf("(");
		index = Get_Food_Index(Selection.slice(0,pos-1));		
		pos2 = Selection.lastIndexOf(")");
		Serving=parseFloat(Selection.slice(pos+1,pos2));
		Totals[28]=Totals[28]+(N[1][index]*Serving);
		for(j=3; j<numNutrients-4; j++)
		{	
			Totals[j]=Totals[j]+(N[j][index]*Serving);
		}
		Totals[30] = Totals[30]+(N[28][index]*Serving);
		Totals[31] = Totals[31]+(N[29][index]*Serving);
	}
	Totals[1]=Totals[28];
	Totals[29]=Totals[27]*(8.8);
	for(y=1; y<=(numNutrients-1);y++)
	{
		if (ShowGrams[y] == "First")
		{
			RoundedTotal=Math.round(Totals[y+2]);
			if (y==26 || y==27)
			{
				document.getElementById("Amount"+y).innerHTML=RoundedTotal;
			}
			else
			{
				document.getElementById("Amount"+y).innerHTML=NutritionLabel[y+2]+" "+RoundedTotal+Units[y];
			}
		}
	}
	for(x=1; x<=(numNutrients-3);x++)
	{
		if (DailyValue[x]!=0)
		{
			Percent=(Totals[x+2]/DailyValue[x]);
			Percent=Percent*100;
			Percent=Math.round(Percent);
			document.getElementById("Percent"+x).innerHTML=Percent+"%";
		}
	}		
}

function Calories()
{
	var Selection=new String();
	var index;
	var Serving;
	var List = document.getElementById("MealList");
	var pos;
	var pos2;
	for (x=3; x<=numNutrients; x++)
	{
		Totals[x]=0;
	}
	for (k=0; k <List.length; k++)
	{
		Selection = List[k].text;
		pos = Selection.lastIndexOf("(");
		index = Get_Food_Index(Selection.slice(0,pos-1));
		pos2 = Selection.lastIndexOf(")");
		Serving=parseFloat(Selection.slice(pos+1,pos2));
		Totals[28]=Totals[28]+(N[1][index]*Serving);
	}
}
function Add_To_Meal(Food, Servings, List,  ServingSize)
{
	if (Food.length != 0)
	{
		var Selection=Food[Food.selectedIndex].text;
		if (Selection == "Select Food")
		{
			alert("Please Select A Food");
		}
		else
		{
			var index=Get_Food_Index(Selection); 
			if (index >= CompleteMealStartingIndex)
			{
				var mealItems = new String;
				mealItems = N[30][index];
				var s;
				var itemNum=1;
				do
				{
					s = Get_Meal_Item(mealItems,itemNum++);	
					if (s != "")
					{
						List[NumList]=new Option(s);
						NumList++;
					}
				}
				while (s != "");
			}
			else
			{
				var Number=Servings[Servings.selectedIndex].text;
				List[NumList]=new Option(Selection+" ("+ServingSize.value/*+" X "+Number*/+")");
				NumList++;
			}
			//document.getElementById("Food1").selectedIndex=0;
			//document.getElementById("ServingDesc1").value="";
			//document.getElementById("ServingNumber1").selectedIndex=Math.min(2,document.getElementById("ServingNumber1").options.length-1);
		}
	}
	CalcNutrients();
	CalcTime();
}	
function Remove_From_List()
{
	var count = 0;
	var list = document.getElementById("MealList");
	if (list.length != 0)
	{
		var selection=list.selectedIndex;
		if (selection != -1)
		{
			list.remove(selection);
			NumList--;
			count++;
		}
	}
	if (count == 0)
	{
		alert("SELECT FOOD FROM BOX");
	}
	CalcNutrients();
	CalcTime();
}
function Clear_All()
{
	var list = document.getElementById("MealList");
	for (var j=list.length-1;j>=0;j--)
	{
		list.remove(j);
		NumList--;
	}
	CalcNutrients();
	CalcTime();
}
function secondWindowIndex()
{
	for (var index=0; index <= maxSecondWindow; index++)
	{
		if (secondWindow[index] == null || secondWindow[index].closed) 
		{
			return index;
		}
	}
	return maxSecondWindow;
}
function Show_Label()
{	
	var index = secondWindowIndex();
	if (secondWindow[index] != null && !secondWindow[index].closed)
	{
		secondWindow[index].close();
		secondWindow[index] = null;
	}
	if (secondWindow[index] == null || secondWindow[index].closed) 
	{
		secondWindow[index] = window.open('report.php','mypopup'+index,'height='+labelHeight+',width='+FullLabelWidth+',scrollbars=no');
		secondWindow[index].focus();
	}
}
function FullNutritionLabel()
{
	window.document.body.innerHTML = window.opener.document.body.innerHTML;
	Set_Label(window.document);
}
function Set_Label(doc)
{
	doc.getElementById("Label4").style.display="block";
	doc.getElementById("ButtonShow").style.display="none";
	doc.getElementById("Column1").style.display="none";
	doc.getElementById("Column3").style.background="";
	doc.getElementById("Exercise01").style.display="none";
	doc.getElementById("Exercise02").style.display="none";
	doc.getElementById("Exercise03").style.display="none";
	doc.getElementById("Exercise04").style.display="none";
	doc.getElementById("BlankRow").style.display="none";
	doc.getElementById("PrintRow").style.display="block";

	if (IncludeMealInFullLabel)
	{
		doc.getElementById("RemoveFromMeal").style.display="none";
		doc.getElementById("ClearAll").style.display="none";
		doc.getElementById("email").style.display="none";
		doc.getElementById("MealTable").style.background="";
		doc.getElementById("MealTable").height=labelHeight-65 + "px";
		doc.getElementById("MealList").size=20;
	}
	else
	{
		doc.getElementById("Column2").style.display="none";
		doc.getElementById("NutrFacts").style.display="none";
		doc.getElementById("NutrFacts2").style.display="block";
		doc.getElementById("MealList").size=12;
	}	
}

function Get_Food_Index(Food)
{
	for(i=0; i<=numFoods; i++)
	{
		if (Food == N[0][i])
		{
			return i;
		}
	}
	var pos = Food.lastIndexOf("(");
	if (pos <= 0)
	{
		return 0;
	}
	Food = Food.slice(0,pos-1);
	return Get_Food_Index(Food);
}

function Get_Meal_Item(items, itemNum)
{
	var startPos = Position(items, itemNum);
	var pos = items.indexOf(",",startPos);
	if (pos <= 0)
	{
		return "";
	}
	var index = items.slice(startPos,pos);
	items.text = items.slice(pos+1);
	var s = N[0][index];
	var pos2 = items.indexOf(",",pos+1);
	s = s + " (" + items.slice(pos+1,pos2) + ")";
	var pos3 = items.indexOf("|",pos2+1);
	s = s + "                                                          " +  " (" + items.slice(pos2+1,pos3) + ")";
	return s;
}

function Position(s, count)
{
	var pos=0;
	for (var j = 1; j <= count; j++)
	{	
		pos = s.indexOf("|",pos)+1;
	}
	return pos;
}

function IsMatch(searchElement, foodItemIndex)
{
	var ItemToBeFound = new RegExp(searchElement,"i");
	return (N[0][foodItemIndex].search(ItemToBeFound) >= 0);
}

function Search(SearchItem, ItemsFoundCombo)
{
	if (SearchItem.value == "")
	{
		alert("Please enter a food item.");
		return;
	}

	s = new String;
	s = SearchItem.value; 
	//replace comma with space
	s = s.replace(/,/g," ");
	//replace double spaces with single space
	while (s.search(/  /) >= 0)
	{
		s = s.replace(/  /g," ");
	}

	var ItemArray = new Array;
	ItemArray = s.split(" ");

	var ItemToBeFound = new RegExp(SearchItem.value,"i");
	var ItemFoundCount = 0;
	ClearList(ItemsFoundCombo);
	ItemsFoundCombo[ItemFoundCount++] = new Option("Select Food");		
	for (var j=1; j<=numFoods; j++)
	{	
		var MatchCount = 0;
		for (k=0; k<ItemArray.length; k++)
		{
			if (IsMatch(ItemArray[k],j)) 
			{
				MatchCount++;
			}
		}
		//if only one item and it matches or 2 or more matches
		if (MatchCount == ItemArray.length || MatchCount >= 2)
		{
			ItemsFoundCombo[ItemFoundCount++] = new Option(N[0][j]);		
		}
	}
	if (ItemFoundCount <= 1)
	{
		ClearList(ItemsFoundCombo);
		alert("No food item matched your search request.");
	}
}

function FillSearch(SearchCombo, CategoryCombo, FoodCombo, servnum, servdes)
{
	var foodItem = SearchCombo[SearchCombo.selectedIndex].text;
	var foodIndex = Get_Food_Index(foodItem);
	var category="";
	for (var j=numOfCat; j>=0; j--)
	{
		if (foodIndex > numCat[j])
		{
			category = FoodCategory[j+1];
			break;
		}
	}

	for (var j=0; j<=CategoryCombo.options.length-1; j++)
	{
		if (category == CategoryCombo[j].text)
		{
			CategoryCombo.selectedIndex = j;
			break;
		}
	}

	FillSecondBox(CategoryCombo, FoodCombo, servnum, servdes);
	for (var j=0; j<=FoodCombo.options.length-1; j++)
	{
		if (foodItem == FoodCombo[j].text)
		{
			FoodCombo.selectedIndex = j;
			break;
		}
	}
	GetServingandCals(FoodCombo, servnum, servdes);
}
