var	http_request = false;

// CATEGORIAS

function categoryPOSTRequest(url, parameters) {
  http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
	http_request = new XMLHttpRequest();
	if (http_request.overrideMimeType) {
	  http_request.overrideMimeType('text/html');
	}
  }	else if	(window.ActiveXObject) { //	IE
	try	{
	  http_request = new ActiveXObject("Msxml2.XMLHTTP");
	} catch	(e)	{
	  try {
		http_request = new ActiveXObject("Microsoft.XMLHTTP");
	  }	catch (e) {}
	}
  }
  if (!http_request) {
	alert('Não foi possível	criar objeto XMLHTTP');
	return false;
  }
  http_request.onreadystatechange =	catAlertContents;
  http_request.open('POST',	url, true);
  http_request.setRequestHeader("Content-type",	"application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", parameters.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(parameters);
}

function catAlertContents()	{

  // Limpa o formulario
  campo_select = document.forms[0].alimento;
  
  // Esvazia o select  
  campo_select.options.length =	0;
  var i	= 0;
  while	(i <= campo_select.childNodes.length - 1)
			{
			var	child =	campo_select.childNodes.item(i);
			campo_select.removeChild(child);
  i++;
			}
  
  document.forms[0].amount.value = "";
  document.forms[0].part.selectedIndex = -1;
  document.forms[0].unit.options.length	= 0;
  document.forms[0].comp.value="";

  if (http_request.readyState == 4)	{
	if (http_request.status	== 200)	{
	  results =	http_request.responseText.split(",");
	  trade	= "0";
	  j	= 0;
	  var opt;
	  for( i = 0; i	< results.length; i++ )	   { 
		string = results[i].split( "|" );
		if (string[2] != trade)	{
			// Caso	mude para marcas, cria um subgrupo
			opt	= document.createElement( "optgroup" );
			opt.label =	"Marcas";
			campo_select.appendChild(opt);
			j++;
			trade =	string[2];
		}
		
		// Se existir um opt não seta no select	e sim no subgrupo
		if (typeof opt != "undefined") {
			var	oOption	= document.createElement('option');
			oOption.value =	string[1];
			oOption.text = unescape(string[0]);
            oOption.innerHTML = unescape(string[0]);
			opt.appendChild(oOption);
		} else {
			campo_select.options[i+j] =	new	Option(	unescape(string[0]), string[1] );
		}

	  }
		document.getElementById('loading1').style.visibility = 'hidden';
	}
  }
}

function categorySend(obj) {
  document.getElementById('loading1').style.visibility = 'visible';
  document.getElementById('selTitle').innerHTML	= 'Agora selecione um alimento ou altere a categoria já	selecionada';

  var poststr =	"id=" +	obj.options[obj.selectedIndex].value;
  categoryPOSTRequest('./category.php',	poststr);
}

// UNIDADE

function unitPOSTRequest(url, parameters) {
  http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
	http_request = new XMLHttpRequest();
	if (http_request.overrideMimeType) {
	  http_request.overrideMimeType('text/html');
	}
  }	else if	(window.ActiveXObject) { //	IE
	try	{
	  http_request = new ActiveXObject("Msxml2.XMLHTTP");
	} catch	(e)	{
	  try {
		http_request = new ActiveXObject("Microsoft.XMLHTTP");
	  }	catch (e) {}
	}
  }
  if (!http_request) {
	alert('Não foi possível	criar objeto XMLHTTP');
	return false;
  }
  http_request.onreadystatechange =	unitAlertContents;
  http_request.open('POST',	url, true);
  http_request.setRequestHeader("Content-type",	"application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", parameters.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(parameters);
}

function unitAlertContents() {

  document.forms[0].amount.value = "";
  document.forms[0].part.selectedIndex = -1;
  document.forms[0].comp.value="";
  
  campo_select = document.forms[0].unit;
  campo_select.options.length =	0;
  if (http_request.readyState == 4)	{
	if (http_request.status	== 200)	{
	  results =	http_request.responseText.split(",");
	  
	  for( i = 0; i	< results.length; i++ )	   { 
		string = results[i].split( "|" );
		campo_select.options[i]	= new Option( unescape(string[0]), string[1] );
	  }
	  
	  document.getElementById('loading2').style.visibility = 'hidden';
	}
  }
}

function unitSend(obj) {
  document.getElementById('loading2').style.visibility = 'visible';
  document.getElementById('selTitle').innerHTML	= 'Agora selecione a quantidade	que	esta receita vai ter deste alimento	ou altere o	alimento selecionado ou	altere a categoria selecionada';
  var poststr =	"id=" +	obj.options[obj.selectedIndex].value;
  unitPOSTRequest('./food.php',	poststr);
}

// ADICIONAR

function addPOSTRequest(url, parameters) {
  http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
	http_request = new XMLHttpRequest();
	if (http_request.overrideMimeType) {
	  http_request.overrideMimeType('text/html');
	}
  }	else if	(window.ActiveXObject) { //	IE
	try	{
	  http_request = new ActiveXObject("Msxml2.XMLHTTP");
	} catch	(e)	{
	  try {
		http_request = new ActiveXObject("Microsoft.XMLHTTP");
	  }	catch (e) {}
	}
  }
  if (!http_request) {
	alert('Não foi possível	criar objeto XMLHTTP');
	return false;
  }
  http_request.onreadystatechange =	addAlertContents;
  http_request.open('POST',	url, true);
  http_request.setRequestHeader("Content-type",	"application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", parameters.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(parameters);
}

function addAlertContents()	{

  if (http_request.readyState == 4)	{
	if (http_request.status	== 200)	{
	results	= http_request.responseText.split(",");

	// Variáveis de	totalização
	var	hdCal =	document.forms[0].hCal;
	var	hdFat =	document.forms[0].hFat;
	var	hdProt = document.forms[0].hProt;
	var	hdFib =	document.forms[0].hFib;
	var	idProd = results[6];
	var	tdCal =	document.getElementById('tdCal');
	var	tdFat =	document.getElementById('tdFat');
	var	tdProt = document.getElementById('tdProt');
	var	tdFib =	document.getElementById('tdFib');

	var	tb = document.getElementById('ings');

	var	oldTr =	document.getElementById('tr' + idProd);
	
	if (oldTr != null) { //	Já existe o	ingrediente	na lista
	
		// ALTERA A	LINHA
		
		// Quantidade
		var	oldTd1 = document.getElementById('td1' + idProd);
		oldTd1.innerHTML = unescape(results[1]);
		
		var	diff;
		var	val;
		var	old;
		// Caloria
		var	old	= document.getElementById('td2'	+ idProd);
		val	= (old.innerHTML.split(" kcal"))[0];
		diff = parseFloat(results[2]) -	parseFloat(val);
		hdCal.value	= parseFloat(hdCal.value) +	diff;
		old.innerHTML =	results[2] + " kcal";
		
		// Gordura
		var	old	= document.getElementById('td3'	+ idProd);
		val	= (old.innerHTML.split(" g"))[0];
		diff = parseFloat(results[3]) -	parseFloat(val);
		hdFat.value	= parseFloat(hdFat.value) +	diff;
		old.innerHTML =	results[3] + " g";
		
		// Proteina
		var	old	= document.getElementById('td4'	+ idProd);
		val	= (old.innerHTML.split(" g"))[0];
		diff = parseFloat(results[4]) -	parseFloat(val);
		hdProt.value = parseFloat(hdProt.value)	+ diff;
		old.innerHTML =	results[4] + " g";
		
		// Fibra
		var	old	= document.getElementById('td5'	+ idProd);
		val	= (old.innerHTML.split(" g"))[0];
		diff = parseFloat(results[5]) -	parseFloat(val);
		hdFib.value	= parseFloat(hdFib.value) +	diff;
		old.innerHTML =	results[5] + " g";

	} else { //	Não	existe o ingrediente na	lista
	
	// CRIA	UMA	NOVA LINHA

	var	tr = document.createElement('TR');
	tr.className = "menuCell";
	
	var	tbody =	document.createElement('TBODY');
	tbody.id = 'tb'	+ idProd;
	tbody.appendChild(tr);
	//testi++;
	tr.id= 'tr'	+ idProd;
	tb.appendChild(tbody);

	// Ingrediente
	var	td0	= document.createElement('TD');
	tr.appendChild(td0);
	var	del;
	del	= "<input type=\"image\" width=\"12\" height=\"12\"	 src=\"http://www.nutricentral.com.br/images/del.gif\" onclick=\"return	del('" + tbody.id +	"')\" /> ";
	td0.innerHTML= del + unescape(results[0]);
	// Cria	um hidden input	para armazenar a informações
	// de cadastro da receita.
	var	oText =	document.createElement('input');
	oText.type = 'hidden';
	oText.name = 'hdDB'	+ idProd;
	oText.value	= idProd + "#" + results[7]	+ "#" +	results[8] + "#" + results[9];
	tr.appendChild(oText);
	
	// Quantidade
	var	td1	= document.createElement('TD');
	tr.appendChild(td1);
	td1.innerHTML= unescape(results[1]);
	td1.id = "td1" + idProd;

	// Calorias
	var	td2	= document.createElement('TD');
	tr.appendChild(td2);
	td2.innerHTML= results[2]  + " kcal";
	td2.className =	"algRight";
	td2.id = "td2" + idProd;

	hdCal.value	= parseFloat(hdCal.value) +	parseFloat(results[2]);
	
	// Gordura
	var	td3	= document.createElement('TD');
	tr.appendChild(td3);
	td3.innerHTML= results[3] +	" g";
	td3.className =	"algRight";
	td3.id = "td3" + idProd;
	
	hdFat.value	= parseFloat(hdFat.value) +	parseFloat(results[3]);

	// Proteina
	var	td4	= document.createElement('TD');
	tr.appendChild(td4);
	td4.innerHTML= results[4]  + " g";
	td4.className =	"algRight";
	td4.id = "td4" + idProd;
	
	hdProt.value = parseFloat(hdProt.value)	+ parseFloat(results[4]);
	
	// Fibra
	var	td5	= document.createElement('TD');
	tr.appendChild(td5);
	td5.innerHTML= results[5]  + " g";
	td5.className =	"algRight";
	td5.id = "td5" + idProd;
	
	hdFib.value	= parseFloat(hdFib.value) +	parseFloat(results[5]);
	
	}
	
	tdCal.innerHTML	= Math.round(hdCal.value*100)/100  + " kcal";
	tdFat.innerHTML	= Math.round(hdFat.value*100)/100  + " g";
	tdProt.innerHTML = Math.round(hdProt.value*100)/100	 + " g";
	tdFib.innerHTML	= Math.round(hdFib.value*100)/100  + " g";
	
	document.getElementById('loading3').style.visibility = 'hidden';	

	}
  }
}

function addSend() {

  document.getElementById('selTitle').innerHTML	= 'Você	pode selecionar	outra categoria	ou outro ingrediente para sua receita, ou pode preencher os	dados restantes	e enviar sua receita.';

  var unit = document.forms[0].unit;
  var amount = document.forms[0].amount;
  var part = document.forms[0].part;
  var alimento = document.forms[0].alimento;
  var cat =	document.forms[0].cat;
  var comp = document.forms[0].comp;

  if (cat.selectedIndex	== -1
	   || cat.options[cat.selectedIndex].text == ""
	   || cat.options[cat.selectedIndex].text == "...")	{
	  alert("É necessário escolher uma categoria!");
	  return false;
  }	 
  
  if (alimento.selectedIndex ==	-1
	   || alimento.options[alimento.selectedIndex].text	== ""
	   || alimento.options[alimento.selectedIndex].text	== "...") {
	  alert("É necessário escolher um alimento!");
	  return false;
  }
  
  if (amount.value == "" &&	part.value == "") {
	  alert("É necessário escolher a quantidade!");
	  amount.focus();
	  return false;
  }
  
  if (isNaN(amount.value)) {
	  alert("A quantidade precissa ser uma valor numérico!");
	  amount.focus();
	  return false;
  }
  
  document.getElementById('loading3').style.visibility = 'visible';
		  document.getElementById('ing1').style.visibility = 'hidden';
		document.getElementById('ing2').style.visibility = 'hidden';

  var poststr =	"id=" +	unit.options[unit.selectedIndex].value
  +	"&amount=" + amount.value +	"&part=" + part.value +	"&comp=" + comp.value;
  addPOSTRequest('./measure.php', poststr);
  return false;
}


function clean() {
document.forms[0].amount.value = "";
document.forms[0].title.value =	"";
document.forms[0].how_to.value = "";
document.forms[0].hCal = "0";
document.forms[0].hFat = "0";
document.forms[0].hProt	= "0";
document.forms[0].hFib = "0";
document.forms[0].part.selectedIndex = -1;
document.forms[0].select.selectedIndex = -1;
document.forms[0].alimento.selectedIndex = -1;
document.forms[0].unit.selectedIndex = -1;
document.forms[0].comp.value="";
  }
  
function del (body)	{
 var tb	= document.getElementById('ings');
 var tbody = document.getElementById(body);
 var idProd	= body.substring(2);
	 var tdCal = document.getElementById('tdCal');
	var	tdFat =	document.getElementById('tdFat');
	var	tdProt = document.getElementById('tdProt');
	var	tdFib =	document.getElementById('tdFib');

	// Variáveis de	totalização
	var	hdCal =	document.forms[0].hCal;
	var	hdFat =	document.forms[0].hFat;
	var	hdProt = document.forms[0].hProt;
	var	hdFib =	document.forms[0].hFib;

 
 //	Caloria
 
 
		var	old	= document.getElementById('td2'	+ idProd);
		val	= (old.innerHTML.split(" kcal"))[0];
		diff = parseFloat(val);
		hdCal.value	= parseFloat(hdCal.value) -	diff;
		old.innerHTML =	results[2] + " kcal";
		
		// Gordura
		var	old	= document.getElementById('td3'	+ idProd);
		val	= (old.innerHTML.split(" g"))[0];
		diff = parseFloat(val);
		hdFat.value	= parseFloat(hdFat.value) -	diff;
		old.innerHTML =	results[3] + " g";
		
		// Proteina
		var	old	= document.getElementById('td4'	+ idProd);
		val	= (old.innerHTML.split(" g"))[0];
		diff = parseFloat(val);
		hdProt.value = parseFloat(hdProt.value)	- diff;
		old.innerHTML =	results[4] + " g";
		
		// Fibra
		var	old	= document.getElementById('td5'	+ idProd);
		val	= (old.innerHTML.split(" g"))[0];
		diff = parseFloat(val);
		hdFib.value	= parseFloat(hdFib.value) -	diff;
		old.innerHTML =	results[5] + " g";
 
 tb.removeChild(tbody);
 
	tdCal.innerHTML	= Math.round(hdCal.value*100)/100  + " kcal";
	tdFat.innerHTML	= Math.round(hdFat.value*100)/100  + " g";
	tdProt.innerHTML = Math.round(hdProt.value*100)/100	 + " g";
	tdFib.innerHTML	= Math.round(hdFib.value*100)/100  + " g";
 
 return	false;
}

function verify() {

	var	title =	document.forms[0].title;
	if (title.value	== "") {
		alert("É necessário	escolher o título da receita!");
		title.focus();
		return false;
	}

	var	catRecipe =	document.forms[0].catRecipe;
	if (catRecipe.selectedIndex	== -1
		|| catRecipe.options[catRecipe.selectedIndex].text == "...") {
		alert("É necessário	escolher a categoria da	receita!");
		title.focus();
		return false;
	}

	var	hdCal =	document.forms[0].hCal;
	if (parseFloat(hdCal.value)	<= 0) {
		alert("É necessário	escolher pelo menos	um ingrediente!");
		return false;
	}
	
	var	howTo =	document.forms[0].how_to;
	if (howTo.value	== "") {
		alert("É necessário	escrever o modo	de fazer!");
		return false;
	}

	return true;
}

function txtBlur(obj) {
	var	img	= window.document.images[obj.imgName];
	
	if (obj.value == "") {
		img.src	= "http://nutricentral.com.br/pass/img/attention.gif";
	} else {
		img.src	= "http://nutricentral.com.br/pass/img/valid.gif";
	}
}

function txtType(obj) {
	var	img	= window.document.images[obj.imgName];
	
	if (obj.value == "") {
		img.src	= "http://nutricentral.com.br/pass/img/fail.gif";
	} else {
		img.src	= "http://nutricentral.com.br/pass/img/valid.gif";
	}
}

function txtFocus(obj) {
	var	img	= window.document.images[obj.imgName];
	
	if (obj.value == "") {
		img.src	= "http://nutricentral.com.br/pass/img/fail.gif";
	}
}

function comboBlur(obj)	{
	var	img	= window.document.images[obj.imgName];
	
	if (obj.selectedIndex <= 0)	{
		img.src	= "http://nutricentral.com.br/pass/img/attention.gif";
	} else {
		img.src	= "http://nutricentral.com.br/pass/img/valid.gif";
	}
}

function comboFocus(obj) {
	var	img	= window.document.images[obj.imgName];
	
	if (obj.selectedIndex <= 0)	{
		img.src	= "http://nutricentral.com.br/pass/img/fail.gif";
	}
}

function comboChange(obj) {
	var	img	= window.document.images[obj.imgName];
	
	if (obj.selectedIndex <= 0)	{
		img.src	= "http://nutricentral.com.br/pass/img/fail.gif";
	} else {
		img.src	= "http://nutricentral.com.br/pass/img/valid.gif";
	}
}

function comboVisible(obj) {
	
	var	img1 = window.document.images['imgalimento'];
	img1.src = "http://nutricentral.com.br/pass/img/attention.gif";
	var	img2 = window.document.images['imgamount'];
	img2.src = "http://nutricentral.com.br/pass/img/attention.gif";

	if (obj.selectedIndex >	0) {
		img1.style.visibility =	'visible';
		img2.style.visibility =	'visible';
	} else {
		img1.style.visibility =	'hidden';
		img2.style.visibility =	'hidden';
	}
}

function mixFocus(obj) {
	var	img	= window.document.images[obj.imgName];
 
	if (obj.name ==	'amount') {
		var	part = document.getElementById('part');
		var	amount = obj;
	} else {
		var	amount = document.getElementById('amount');
		var	part = obj;
	}
	
	if ((part.selectedIndex	<= 0 &&	amount.value ==	'')	|| isNaN(amount.value))	{
		img.src	= "http://nutricentral.com.br/pass/img/fail.gif";
	}
}

function mixChange(obj)	{

	var	img	= window.document.images[obj.imgName];
	
		if (obj.name ==	'amount') {
		var	part = document.getElementById('part');
		var	amount = obj;
	} else {
		var	amount = document.getElementById('amount');
		var	part = obj;
	}
	
	if ((part.selectedIndex	<= 0 &&	amount.value ==	'')	|| isNaN(amount.value))	{
		img.src	= "http://nutricentral.com.br/pass/img/fail.gif";
	} else {
		img.src	= "http://nutricentral.com.br/pass/img/valid.gif";
	}
}

function mixBlur(obj) {

document.getElementById('selTitle').innerHTML =	'Se	a quantidade estiver de	acordo,	já pode	adicionar o	ingrediente	e escolher outro para receita.';

	var	img	= window.document.images[obj.imgName];
	
		if (obj.name ==	'amount') {
		var	part = document.getElementById('part');
		var	amount = obj;
	} else {
		var	amount = document.getElementById('amount');
		var	part = obj;
	}
	if ((part.selectedIndex	<= 0 &&	amount.value ==	'')	|| isNaN(amount.value))	{
		img.src	= "http://nutricentral.com.br/pass/img/attention.gif";
	} else {
		img.src	= "http://nutricentral.com.br/pass/img/valid.gif";
	}
}
