var sendReq = getXmlHttpRequestObject();
var food;
var category;
var page;

// open the modal popup
$(document).ready(function () {
	$('#basicModal input:eq(0)').click(function (e) {
		e.preventDefault();
		$('#modal').modal();
	});
});

function hideModal ()
{
    $("#modal").close();
}

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		document.getElementById('p_status').innerHTML = 'Status: Cound not create XmlHttpRequest Object.  Consider upgrading your browser.';
	}
}

// validate??? and 
// post a new request to the server when user hits enter
function blockSubmit(page) {
  doSearch(page);
  return false;
}

function blockAddSubmit(page) {
  doAddSearch(page);
  return false;
}

function showAddManualFood() {
    vista = (document.getElementById('divAddFood').style.visibility == 'hidden') ? 'visible' : 'hidden';
    document.getElementById('divAddFood').style.visibility = vista;
    vista = (document.getElementById('divAddFood').style.display == 'none') ? 'block' : 'none';
    document.getElementById('divAddFood').style.display = vista;
}


// post a request to the server (when user hits search button)
function doSearch(page) {
var selCategory = document.frmSearch.FOOD_CATEGORY_ID;

//alert(document.frmSearch.FOOD_SEARCH.value + ' - ' + selCategory.options[selCategory. selectedIndex].value);

	if(document.frmSearch.FOOD_SEARCH.value == '') {
		alert("Please enter a search term");
		return;
	}
	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
		sendReq.open("POST", 'modal/nutritioninfo/searchFoods.php?' + Math.random(), true);
		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		sendReq.onreadystatechange = function () {

			if (sendReq.readyState == 4) {
				document.getElementById('result').innerHTML = sendReq.responseText;
			}
		} 
		var param = 'food=' + document.frmSearch.FOOD_SEARCH.value;
		param += '&category=' + document.frmSearch.FOOD_CATEGORY_ID.options[document.frmSearch.FOOD_CATEGORY_ID. selectedIndex].value;
		sendReq.send(param);
	}							
  
}

// Search food for the ADD FOOD - Food My Meals
function doAddSearch(page) {
var selCategory = document.frmSearch.FOOD_CATEGORY_ID;

//alert(document.frmSearch.FOOD_SEARCH.value + ' - ' + selCategory.options[selCategory. selectedIndex].value);
 if(document.frmSearch.FOOD_SEARCH.value.length < 3) {
		alert("Please enter at least three letters");
		return;
	}
	if(document.frmSearch.FOOD_SEARCH.value == '') {
		alert("Please enter a search term");
		return;
	}
	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
		sendReq.open("POST", 'modal/nutritioninfo/searchAddFoods.php?' + Math.random(), true);
		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		sendReq.onreadystatechange = function () {

			if (sendReq.readyState == 4) {
				document.getElementById('result').innerHTML = sendReq.responseText;
			}
		} 
		var param = 'food=' + document.frmSearch.FOOD_SEARCH.value;
		param += '&category=' + document.frmSearch.FOOD_CATEGORY_ID.options[document.frmSearch.FOOD_CATEGORY_ID. selectedIndex].value;
		sendReq.send(param);
	}							  
}

// post a request to the server - display available weights
function doWeight(page) {
	var selectedID;
	// in case of only one result there is no array and only one value
	if (document.frmSearch.FOOD_ID.checked){
	  selectedID = document.frmSearch.FOOD_ID.value;
	}
	else // more options returned by search => we have an array
	{
		var myOption = -1;
		for (i=document.frmSearch.FOOD_ID.length-1; i > -1; i--) 
		{
			if (document.frmSearch.FOOD_ID[i].checked) {
				myOption = i; i = -1;
			}
		}
		if (myOption == -1) {
		alert("Please select a food from the list.");
		return false;
		} 	
		selectedID = document.frmSearch.FOOD_ID[myOption].value;
	}
	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
		sendReq.open("POST", 'modal/nutritioninfo/searchFoods.php?' + Math.random(), true);
		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		sendReq.onreadystatechange = function () {

			if (sendReq.readyState == 4) {
				document.getElementById('result').innerHTML = sendReq.responseText;
			}
		} 
		var param = 'weight_food_id=' + selectedID;
		sendReq.send(param);
	}							  
}

// post a request to the server - display available weights
function doSearchAddWeight(cat, srch) {
	var selectedID;
    var myOption = -1;

    if (document.forms[1].FOOD_ID.checked == true) {
        myOption = 0;
        selectedID = document.forms[1].FOOD_ID.value;
    } else {
        
        for (i = 0; i < document.forms[1].FOOD_ID.length; i++){
            if (document.forms[1].FOOD_ID[i].checked == true) {
                myOption = i;
                selectedID = document.forms[1].FOOD_ID[myOption].value;
            }
        }
    }
	if (myOption == -1) {
		alert("Please select a food from the list.");
		//return false;
	} else {
        urlAction = "fd_search_measure.php?cat=" + cat + "&srch=" + srch;
        urlAction = urlAction + "&fid=" + selectedID;
        document.forms[1].action = urlAction;
        //document.forms[1].submit();
    }
}

// post a request to the server - display available weights
function doAddWeight(date, mt, cat, srch, mtid) {
	var selectedID;
    var myOption = -1;

    if (document.forms[1].FOOD_ID.checked == true) {
        myOption = 0;
        selectedID = document.forms[1].FOOD_ID.value;
    } else {
        
        for (i = 0; i < document.forms[1].FOOD_ID.length; i++){
            if (document.forms[1].FOOD_ID[i].checked == true) {
                myOption = i;
                selectedID = document.forms[1].FOOD_ID[myOption].value;
            }
        }
    }
	if (myOption == -1) {
		alert("Please select a food from the list.");
		//return false;
	} else {
        urlAction = "addfood_measure.php?mtid=" + mtid + "&date=" + date + "&mt=" + mt + "&cat=" + cat + "&srch=" + srch;
        urlAction = urlAction + "&fid=" + selectedID;
        document.forms[1].action = urlAction;
        //document.forms[1].submit();
    }
}

// post a request to the server (when user hits view nutrition facts button)
// Uses: modal/nutritioninfo/searchFoods.php
function doNutritionOLD(page) {

	var selectedID;
	var amount;
	// in case of only one result there is no array and only one value
	if (document.frmSearch.SEQ.checked){
	  selectedID = document.frmSearch.SEQ.value;
	}
	else // more options returned => we have an array
	{
		var myOption = -1;
		for (i=document.frmSearch.SEQ.length-1; i > -1; i--) 
		{
			if (document.frmSearch.SEQ[i].checked) {
				myOption = i; i = -1;
			}
		}
		if (myOption == -1) {
		alert("You must select a radio button");
		return false;
		} 	
		selectedID = document.frmSearch.SEQ[myOption].value;
	}	
	if (selectedID == 'GRAMS_100'){
	  amount = 	document.frmSearch.AMOUNT.value;
	}
	else{
		var URLVarName = 'AMOUNT'+selectedID;
		amount = eval("document.frmSearch." + URLVarName + ".value;");
	}	
	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
		sendReq.open("POST", 'modal/nutritioninfo/searchFoods.php?' + Math.random(), true);
		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		sendReq.onreadystatechange = function () {

			if (sendReq.readyState == 4) {
				document.getElementById('modal').innerHTML = sendReq.responseText;
			}
		} 
		var param = 'food_id=' + document.getElementById('FOOD_ID').value;
		param += '&seq_id=' + selectedID;
		param += '&amount=' + amount;
		sendReq.send(param);
	}							
	
}

//  Now pops out a new window with nutrition label generated from 
//  'fd_addviewnutrition_popup.php'
function doNutrition(page) {
	var selectedID;
	var amount;
	
	alert("hello");
	// in case of only one result there is no array and only one value
	if (document.frmSearch.SEQ.checked){
	  selectedID = document.frmSearch.SEQ.value;
	}
	else // more options returned => we have an array
	{
		var myOption = -1;
		for (i=document.frmSearch.SEQ.length-1; i > -1; i--) 
		{
			if (document.frmSearch.SEQ[i].checked) {
				myOption = i; i = -1;
			}
		}
		if (myOption == -1) {
		alert("You must select a radio button");
		return false;
		} 	
		selectedID = document.frmSearch.SEQ[myOption].value;
	}	
	if (selectedID == 'GRAMS_100'){
	  amount = 	document.frmSearch.AMOUNT.value;
	}
	else{
		var URLVarName = 'AMOUNT'+selectedID;
		amount = eval("document.frmSearch." + URLVarName + ".value;");
	}	

	var param = 'food_id=' + document.getElementById('FOOD_ID').value;
	param += '&seq_id=' + selectedID;
	param += '&amount=' + amount;
	
	var name = 'AMOUNT'+selectedID;

	var url  = 'fd_addviewnutrition_popup.php?' + param;
	window.open(url,  name, 'width=340,height=650,scrollbars=yes,toolbars=no,resizable=no,top=50,left=0'); 
	if (window.focus) {newwindow.focus()}
}


// post a request to the server (when user hits view nutrition facts button)
function doAddNutrition(weight_id) {

  var selectedID = weight_id;
	var amount;
	var URLVarName = 'AMOUNT'+selectedID;
	amount = eval("document.frmSearch." + URLVarName + ".value;");
	
	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
		sendReq.open("POST", 'modal/nutritioninfo/searchAddFoods.php?' + Math.random(), true);
		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		sendReq.onreadystatechange = function () {

			if (sendReq.readyState == 4) {
				document.getElementById('modal').innerHTML = sendReq.responseText;
				
				//window.open( 'fd_addviewnutrition_popup.php?seq_id='selectedID, 'nutrition', 'height = 620, width = 598, resizeable = 0, top = 100, left = 300' );

			}
		} 
		var param = 'food_id=' + document.getElementById('FOOD_ID').value;
		param += '&seq_id=' + selectedID;
		param += '&amount=' + amount;
		sendReq.send(param);
	}				
}



    //addfood_addtomeal.php?date=".$date."&fid=".$meal['food_id']."&wid=".$meal['weight_id']."&mt=".$mt."

function addUserFood(date, mt, index, food_id, weight_id, mtid) {

    var amount;
    if ( document.forms[0].SERVING_AMOUNT.length > 1 ) {
        amount = document.forms[0].SERVING_AMOUNT[index-1].value;
    } else {
        amount = document.forms[0].SERVING_AMOUNT.value;
    }

	if (amount == "") {
		alert("Please enter the number of servings that you ate.");
	} else {
        var param = 'fid=' + food_id;
    		param += '&wid=' + weight_id;
    		param += '&amt=' + amount;

        urlAction = "addfood_addtomeal.php?date=" + date + "&mtid=" + mtid + "&mt=" + mt;
        urlAction = urlAction + "&" + param;
        window.location.href = urlAction;
    }
}

function addFood(date, mt, cat, srch, mtid) {
	var selectedID;
	var amount;
    var myOption = -1;

    if (!(document.forms[1].SEQ.value != "undefined") || document.forms[1].SEQ.value > 0) {
        myOption = 0;
        selectedID = document.forms[1].SEQ.value;
    } else {
        for (i = 0; i < document.forms[1].SEQ.length; i++){
            if (document.forms[1].SEQ[i].checked == true) {
                myOption = i;
                selectedID = document.forms[1].SEQ[myOption].value;
            }
        }
    }
    
	if (myOption == -1) {
		alert("Please select a food from the list.");
		//return false;
	} else {

        var URLVarName = 'AMOUNT'+selectedID;
        amount = eval("document.forms[1]." + URLVarName + ".value;");

        var param = 'food_id=' + document.getElementById('FOOD_ID').value;
            param += '&weight id=' + selectedID;
            param += '&amount=' + amount;

        urlAction = "addfood_insertfood.php?date=" + date + "&mtid=" + mtid + "&mt=" + mt + "&cat=" + cat + "&srch=" + srch;
        urlAction = urlAction.replace("#", "");
        urlAction = urlAction + "&" + param;
        document.frmSearch.action = urlAction;
        //document.frmSearch.submit();
    }
/*
	else // more options returned => we have an array
	{
		var myOption = -1;
		for (i=document.frmSearch.SEQ.length-1; i > -1; i--) 
		{
			if (document.frmSearch.SEQ[i].checked) {
				myOption = i; i = -1;
			}
		}
		if (myOption == -1) {
		alert("You must select a radio button");
		return false;
		} 	
		selectedID = document.frmSearch.SEQ[myOption].value;
	}	
	if (selectedID == 'GRAMS_100'){
	  amount = 	document.frmSearch.AMOUNT.value;
	}
	else{
		var URLVarName = 'AMOUNT'+selectedID;
		amount = eval("document.frmSearch." + URLVarName + ".value;");
	}	
	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
		sendReq.open("POST", 'modal/nutritioninfo/searchAddFoods.php?' + Math.random(), true);
		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		sendReq.onreadystatechange = function () {

			if (sendReq.readyState == 4) {
				document.getElementById('modal').innerHTML = sendReq.responseText;
				//alert('something');
                                window.close();
                                return true;
                                
			}
		} 
		var param = 'food_id=' + document.getElementById('FOOD_ID').value;
		param += '&weight id=' + selectedID;
		param += '&amount=' + amount;
		sendReq.send(param);
        
	}

    if (window.opener && !window.opener.closed) {
        //document.getElementById(form).submit();
        //window.opener.location.reload();
        //window.opener.document.location.href=url;
        //setTimeout('window.opener.document.location.href='+url,5000);
        window.opener.parent.document.location.href = url + '&page=modalrefresh';
    }
	return true;
//    window.close();
*/

}

/* Search food on Swap pages */
function doSwapSearch(page) {
var selCategory = document.frmSearch.FOOD_CATEGORY_ID;

//alert(document.frmSearch.FOOD_SEARCH.value + ' - ' + selCategory.options[selCategory. selectedIndex].value);

	if(document.frmSearch.FOOD_SEARCH.value == '') {
		alert("Please enter a search term");
		return;
	}
	if (sendReq.readyState == 4 || sendReq.readyState == 0) {
		sendReq.open("POST", 'modal/swap/searchByo.php?' + Math.random(), true);
		sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		sendReq.onreadystatechange = function () {

			if (sendReq.readyState == 4) {
				document.getElementById('result').innerHTML = sendReq.responseText;
			}
		} 
		var param = 'food=' + document.frmSearch.FOOD_SEARCH.value;
		param += '&category=' + document.frmSearch.FOOD_CATEGORY_ID.options[document.frmSearch.FOOD_CATEGORY_ID. selectedIndex].value;
		sendReq.send(param);
	}							
  
}