// INTLv4
var foodlist_dont_foodinfo;

$("a.option").live('click',function(){
	$(".scroll > a").removeClass("selected");
	$(this).addClass("selected");
	$("#inputfield").focus();
	$("#foodinfo_static, #foodinfo_static_container").hide();

	var food_id = $(this).attr('id').substring(2);
	var type = $(this).attr('id').substring(0,2); // fo OR ex OR fc OR fa

	if(type == 'fo') {
		if (foodlist_dont_foodinfo != 1) { // click from mouse
			foodinfo_show(food_id);
		} 
		else { // selected via keyboard
			$("#suggestlist").show();
			foodinfo_show_delayed(food_id);
			$("#loader_gfx").css("visibility","visible");
		}
		if(food_id > 0) {
			foodlist_amountbox_delayed(food_id);
		}
		else {
			foodlist_amountbox_recipe_delayed(food_id);
		}
	}
	if (type == 'ex') {
		xajax_show_exercise_details(food_id);
	}
	if (type == 'fa') {
		xajax_show_favorite_details(food_id);
	}
	if (type == 'fc') {
		xajax_show_foodcalc_details(food_id);
	}
});

$("#amount_gram").live("keyup",function() {
	if($(this).val().length > 0){ $("#amount").attr("disabled",true); }
	else{ $("#amount").attr("disabled", false); }
});

$(".suggestoption").live("click",function(e){
	suggestlist_pick(e);
});

function clear_input(){
	if(document.getElementById('gram')){
		document.getElementById('gram').value='';
	}
  if(document.getElementById('save') ){
		document.getElementById('save').disabled=1;
		document.getElementById('save').checked=false;
	}
}

function input_set(value){
	if(value == 1)
	{
		if(document.getElementById('amount')){
			document.getElementById('times_sign').style.visibility = 'hidden';
			document.getElementById('amount').value = ""
		}
		if(document.getElementById('save_measure'))
		{
			document.getElementById('save_measure_txt').style.color = '#000';
			document.getElementById('save_measure').disabled = false; 
		}
	}
	else{
		if(document.getElementById('amount'))
		{
			document.getElementById('times_sign').style.visibility = 'visible';
			if(document.getElementById('amount').value <= "0")
				document.getElementById('amount').value = "1"
		}
		if(document.getElementById('save_measure_txt'))
		{
			document.getElementById('save_measure_txt').style.color = '#ccc';
			document.getElementById('save_measure').checked = false;
			document.getElementById('save_measure').disabled = true; 
		}
	}
}

var OnKeyRequestBuffer =
{
		bufferText: false,
		bufferTime: 200,

		modified : function(strId, algorithm)
		{
			if (document.getElementById('foodinfo_static'))
			{
				document.getElementById("foodinfo_static").style.display = "none";
			}
				// foodinfo_static_container belongs to public calorie table on 101
				if(document.getElementById('foodinfo_static_container'))
				{
					document.getElementById('foodinfo_static_container').style.display = 'none';
				}
				$("#suggestlist").show();
				setTimeout('OnKeyRequestBuffer.compareBuffer("'+strId.replace('"', '')+'","'+xajax.$(strId).value.replace('"', '')+'", "'+algorithm+'");', this.bufferTime);
				if(document.getElementById('sys_msg'))
				{
					if (document.getElementById(strId).value.length > 0)
						document.getElementById('sys_msg').style.display = 'none';
				}
		},

		compareBuffer : function(strId, strText, algorithm)
		{
				var evalStr;
				if (strText == xajax.$(strId).value && strText != this.bufferText)
				{
					foodinfo_show_cancel();
					$("#suggestlist").show();
					this.bufferText = strText;
					evalStr = "xajax_foodlist_search(xajax.$(strId).value,"+algorithm+","+$("#FoodlogData").data("owner_id")+")";
					eval(evalStr);
				}
		}
}

function suggestlist_back(str, algorithm) {
	var resultt;
	result = str.split(" ");
	result.pop();
	for (var i in result){
		if(resultt)
			resultt += " " + result[i];
		else
			resultt = result[i];
	}
	document.getElementById('inputfield').value = resultt;
	OnKeyRequestBuffer.modified('inputfield', algorithm);
	document.getElementById('inputfield').focus();
}

function suggestlist_pick(e) {
	if (!e)
		var e = window.event;
	if (!e)
		return;
	var elem;
	if (e.target)
		elem = e.target;
	if (e.srcElement)
		elem = e.srcElement;
	if (!elem)
		return;
	var str = elem.id.substring(4);
	var algorithm = elem.name;
	document.getElementById('inputfield').value = document.getElementById('inputfield').value + " " + str;
	OnKeyRequestBuffer.modified('inputfield', algorithm);
	document.getElementById('inputfield').focus();
}

// Cursor keys on foodlist
function cursorkeys_foodlist(e)
{
  var curSelected = $("#scroll > a.selected:first");

  if( e.keyCode == 13){ // Enter/return
    if(curSelected.length == 0){return false;}
    $("#amount").focus();
    return false;
  }

  if(e.keyCode != 33 && e.keyCode != 34 && e.keyCode != 38 && e.keyCode != 40 ){
    return; }

  $("#scroll > a.selected").removeClass("selected");
  $("#amountbox").html('');
  foodlist_dont_foodinfo = 1;

	switch (e.keyCode) {
		case 38: // Up
			if($("a.option:first").length == 0){return false;}
			curSelected.prevAll("a.option:first").addClass("selected");
			if($("#scroll > a.selected").length > 0){
				if($("#scroll").height() < $("#scroll").height() - $("#scroll > a.selected").position().top){
					$("#scroll").scrollTop($("#scroll").scrollTop() - $("#scroll > a.selected").outerHeight(true));
				}
				if(curSelected.prev("a").hasClass("option_disabled")){$("#scroll").scrollTop($("#scroll").scrollTop() - $("#scroll > a.selected").outerHeight(true));}
				$("#scroll > a.selected").trigger("click");
			}
			else{
				$("#scroll").scrollTop(0);
			}
			break;
		case 40: // Down
			if($("a.option:first").length == 0){return false;}
			if(curSelected.length > 0 && curSelected.nextAll("a.option:first").length == 0) { curSelected.addClass("selected"); return;} // "down" on last selected
			if(curSelected.length == 0) { $("#scroll > a.option:first").addClass("selected");} // "down" on no selected yet
			else{curSelected.nextAll("a.option:first").addClass("selected");}
			if($("#scroll").height() < $("#scroll > a.selected").position().top + $("#scroll > a.selected").outerHeight(true)){
				$("#scroll").scrollTop($("#scroll").scrollTop() + $("#scroll > a.selected").outerHeight(true));
			}
			$("#scroll > a.selected").trigger("click");
			break;
		case 34: // PageDown
			if($("a.option:first").length == 0){return false;}
			if(curSelected.length > 0){ $("#scroll").scrollTop($("#scroll").scrollTop() + curSelected.position().top);}
			var scrollPos = $("#scroll").scrollTop();
			var i = 0;
			$("#scroll > a").each(function()
				{
					i = i + $(this).outerHeight(true);
					if(i > $("#scroll").height() + scrollPos - $(this).outerHeight(true)){
						$(this).addClass("selected").trigger("click");
						return false;
					}
				});
			// if we reach this, we didnt have enough elements to exceed the div height, because we're at the bottom. So just choose the last element.
			if($(".selected").length == 0){$("#scroll > a.option:last").addClass("selected");}
			break;
		case 33: // PageUp
			if($("a.option:first").length == 0){return false;}
			var i = 0;
			curSelected.prevAll("#scroll > a.option").each(function(){
				i = i + $(this).outerHeight(true);
				if(curSelected.position().top <= 0 && $(this).position().top - $(this).outerHeight(true) < -$("#scroll").height()){
					$(this).addClass("selected").trigger("click");
					$("#scroll").scrollTop($("#scroll").scrollTop() - -1*$(this).position().top);
					return false;
				}
				if(curSelected.position().top > 0 && $(this).position().top - $(this).outerHeight(true) < 0){
					$(this).addClass("selected").trigger("click");
					$("#scroll").scrollTop($("#scroll").scrollTop() + $(this).position().top);
					return false;
				}
				});
			// if we reach this, we didnt have enough elements to exceed the div height, because we're at the top. So just choose the first element.
			if($(".selected").length == 0){$("#scroll > a.option:first").addClass("selected");$("#scroll").scrollTop(0);}
			break;
	}
}

var foodlist_amountbox_timer;
function foodlist_amountbox_delayed(food_id)
{
	if (foodlist_amountbox_timer)
	{
		clearTimeout(foodlist_amountbox_timer);
		foodlist_amountbox_timer = false;
	}
	foodlist_amountbox_timer = setTimeout("foodlist_amountbox("+food_id+")", 60);
}

function foodlist_amountbox_recipe_delayed(recipe_id)
{
	if (foodlist_amountbox_timer)
	{
		clearTimeout(foodlist_amountbox_timer);
		foodlist_amountbox_timer = false;
	}
	foodlist_amountbox_timer = setTimeout("foodlist_amountbox_recipe("+recipe_id+")", 60);
}

function foodlist_amountbox(food_id)
{
	foodlist_amountbox_timer = false;
	xajax_foodlist_amountbox(food_id);
}

function foodlist_amountbox_recipe(recipe_id)
{
	foodlist_amountbox_timer = false;
	xajax_foodlist_amountbox_recipe(recipe_id);
}

$('#inputfield')
	.click(function(){
		foodinfo_show_cancel();
		$("#suggestlist").show();
	})
	.keydown(function(event){
			return cursorkeys_foodlist(event);
	})
	.keyup(function(){
			OnKeyRequestBuffer.modified('inputfield', $(this).data('algorithm'));
	});
$('#mealchooser').change(function(){
			window.location='/index.php?id=205&mealtype='+$(this).val()+'&dietplan_id='+$(this).data('dietplan_id');
	});
$('#input_type').change(function(){
			if($(this).val() == 'food_all'){var algorithm = 13;}
			if($(this).val() == 'recipe_all'){var algorithm = 2;}
			if($(this).val() == 'favorite'){var algorithm = 64;}
			if($(this).val() == 'foodcalc'){var algorithm = 128;}
			$('#inputfield').data('algorithm',algorithm).focus();
			xajax_foodlist_search($('#inputfield').val(), algorithm);
	});
$('#clear_input').click(function(){
		$("#amountbox").html('');
		$('.calculate').next('span').text(''); // this is for 209.php
		$("#inputfield").val('').focus();
		OnKeyRequestBuffer.modified('inputfield', $('#inputfield').data('algorithm'));
	});
$('#report_link').click(function(){
		if($("a.selected:first").length == 0) {return;}
		var food = $("a.selected:first").attr('id');
		var food_id = food.substring(2);
		if (food.substring(0,2) == 'fo' && food_id > 0){
			window.location = "/index.php?id=218&food_id="+food_id+$(this).data("url");
			return false;
		}
		alert('Vælg den madvare, som du vil rette, fra listen ovenfor og prøv igen.');
	});

$("#selectbox_type").live("change", function(){
	$("#amount").trigger("keyup");
});

// ONLY FOR EXERCISE
$("#amount, #energy").live("keyup", function(){
	if($("#bonus_amount").length > 0){ var energy_unit = $("#bonus_amount").data("unittype");}
	else {return;}
	if($("#selectbox_type option:selected").length > 0){ var energy_unit = $("#selectbox_type option:selected").text();}
	if(energy_unit.length == 0){ var energy_unit = 'kj';}

	$("#bonus_amount > option").each(function() {
		if($("a.selected").attr("id") != 'ex100') {
			var bonus = ( $("#bonus_amount").data("pr_hour") / 60) * $(this).val() * $("#amount").val();
		}
		else {
			var bonus = $("#energy").val() * $(this).val();
			if($("#selectbox_type").val() == 2) {
				bonus = bonus * 4.18;
			}
		}
		if(bonus > 0) {
			if(energy_unit == 'kcal') {
				bonus = bonus / 4.18;
			}
			$(this).text($(this).val()*100 +'% ('+ Math.round(bonus) +' '+energy_unit+')');
		}
		else {
			$(this).text($(this).val()*100 +'%');
		}
	});
});

