$(document).ready(function() {
	rebindlive_foodlog();

	$(".goto_top").click(function(){
		var div = $(this).next('div');
		if($(div).is(":visible")){ $(div).hide(); }
		else{ $(div).show(); }
	});

});
var xmlDoc;

$("#toggle_energy").click(function() {
	window.location = "/scripts/change_unit_public.php?url="+$(this).data("url");
});

function rebindlive_foodlog()
{
	$("img.expandFoodline")
		.unbind()
		.bind('click', function() {
			var str = $(this).attr('id').replace('img_','');
			if($(this).attr("src") == "/gfx/expand.gif") {
				$('#'+str).css({"display":"none"});
				$(this).attr({"src":"/gfx/expand2.gif"});
			}
			else {
				$('#'+str).css({"display":"block"});
				$(this).attr({"src":"/gfx/expand.gif"});
			}
			if(typeof xajax_selected_recipe_div == 'function') {
				xajax_selected_recipe_div(str);
			} 
		});

  // init dialog
	var dialog = $('#dialog1').dialog({ autoOpen: false, resizable: false, width: 320, minHeight: 0 });

	$(".foodline:not(.skipHover), .mealheader:not(.skipHover)")
		.unbind('.foodlog')
		.bind('mouseover.foodlog', function(e) {
				if (e.target.className == "mTooltip")
				{
					return;
				}
		if($(this).hasClass("mealheader"))
		{
			$(this).addClass('mealheader_hover');
		}
		else{
			$(this).addClass($(this).closest('.meal_container').attr('id')+'_hover');
		}
		})
		.bind('mouseout.foodlog', function() {
			if($(this).hasClass("mealheader"))
			{
				$(this).removeClass('mealheader_hover');
			}
			else{
				$(this).removeClass($(this).closest('.meal_container').attr('id')+'_hover');
			}
		})
		.bind('click.foodlog contextmenu.foodlog', function(e) {
			$(".mTooltipContent").remove();
			$("#dialog1").dialog('close');
			return foodline_click($(this).attr('id'), $(this).data('menu'), e);
	});

  $(".foodlog_weight:not(.skipHover),.foodlog_bonus:not(.skipHover)")
		.unbind()
		.bind('mouseover', function() { $(this).css({"text-decoration":"underline"}); })
		.bind('mouseout', function() { $(this).css({"text-decoration":"none"}); })
		.bind('click', function(e) {
			e.stopPropagation();
			var parent_div  = $(this).parents("div.foodline");
			var data        = parent_div.data('data').split(';');
			var line_id     = parent_div.attr('id');
			dialog.dialog({position: [e.clientX, e.clientY]}).text('Henter...');
			dialog.dialog('open');
			if($(this).hasClass("foodlog_weight"))
			{
				dialog.dialog({title: 'Ret mængde'});
				var dietplan_id = $("#FoodlogData").data("dietplan_id");
				var dietplan = '';
				if (dietplan_id > 0)
				{
					dietplan = '&dietplan='+dietplan_id;
				}
				if(line_id.match(/^id/g))
				{
					xajax_change_amount_food(data[0], 'dialog1', data[1], data[2], '/index.php?id=207'+dietplan);
				}
				if(line_id.match(/^cd/g))
				{
					var date = data[0];
					if ($("#FoodlogData").data("date_ref"))
					{
						date = $("#FoodlogData").data("date_ref");
					}
					xajax_change_consumption_details_amount(date, data[1], 'dialog1', '/index.php?id=207'+dietplan);
				}
				if(line_id.match(/^ex/g))
				{ xajax_show_exercise_details(data[0], data[1], 'dialog1', 12, '/index.php?id=207'); }
			}
			if($(this).hasClass("foodlog_bonus"))
			{
				dialog.dialog({title: 'Ret bonus'});
				xajax_change_bonus(data[0], data[1], 'dialog1', '/index.php?id=207');
			}
			$(".mTooltipContent").remove();
			return false;
  	});
}

function update_foodxml(owner)
{
	/*
  $.ajaxSetup({
    type: "GET",
    cache: false,
    scriptCharset: "utf-8",
    contentType: "text/xml; charset=utf-8",
    dataType: "xml",
    timeout: 10000
  });
  $.get("/scripts/foodxml.php", {'owner': owner, 'pagearea': pagearea, 'key': $("#calendar_20x").data("key"), 'dietplan_id': $("#FoodlogData").data("dietplan_id")}, function(data) { xmlDoc = data; });
	*/
	$.ajax({
		  url: "/scripts/foodxml.php",
		  success: function(data) { xmlDoc = data; },
			data: {'owner': owner, 'pagearea': pagearea, 'key': $("#calendar_20x").data("key"), 'dietplan_id': $("#FoodlogData").data("dietplan_id")},
			type: "GET",
			cache: false,
			scriptCharset: "utf-8",
			contentType: "text/xml; charset=utf-8",
			dataType: "xml",
			timeout: 10000
	});
}
update_foodxml($('#calendar_20x').data('uid'));

function cns_infobox(id)
{
	// Get type
	var pattern= /^[a-z]+/gi;
	var type = id.match(pattern);

	// Check which data we have, and insert hardcoded data if needed
	if(get_value(id,'amount_text') == '-')
	{
		var amount_text = 'I portionen';
	}
	else
	{
		var amount_text = get_value(id,'amount_text');
	}
	if(get_value(id,'name') == '-')
	{
		if(type == 'cd')
		{
			var name_text = get_value(id,'title');
		}
		if(type == 'm')
		{
			var name_text = get_value('meal_lang', id);
		}
	}
	else
	{
		var name_text = get_value(id,'name');
	}
	var pie = get_value(id,'cdnutrition_link');
	//.replace(/SLASH/g,'/');

	// Generate html
	var html = '<table style="width: 100%;">';
	html += '<tr><td style="font-weight: bold; padding: 0 5px;">'+name_text+'</td>';
	html += '<td style="vertical-align: top; text-align: right;"><img src="'+pie+'" height="19" width="19" /></td></tr>';
	html += '</table>';
	html += '<div style="padding: 5px;"><table class="infobox">';
	html += '<tr><td>'+amount_text+':</td><td class="ib_portion">'+get_value(id,'amount')+'</td><td class="ib_100g">Pr. 100 g</td></tr>';
	if (xmlDoc.getElementsByTagName('details_lang')[0])
	{
		y=xmlDoc.getElementsByTagName('details_lang')[0].childNodes; // Get food details
		for (i=0;i<y.length;i++)
		{ 
			if (y[i].nodeType==1)
			{
				html += '<tr><td>'+y[i].childNodes[0].nodeValue+':</td>';
				html += '<td class="ib_portion">'+get_value(id,y[i].nodeName)+'</td>';
				if(type == 'cd' || type == 'm')
				{
					html += '<td class="ib_100g">'+get_value(id+'_100',y[i].nodeName)+'</td></tr>';
				}
				else
				{
					html += '<td class="ib_100g">'+get_value('fo'+get_value(id,'food_id'),y[i].nodeName)+'</td></tr>';
				}
			} 
		}
	}
	html += '</table>';
	return html;
}

function get_value(id, element)
{
	if (xmlDoc.getElementsByTagName(id).length == 0)
	{
	//	return false;
		return false;
	}
	if (xmlDoc.getElementsByTagName(id)[0].getElementsByTagName(element).length == 0)
	{
	//	alert('fejl 2 - se 201.js!!');
		return '-';
	}
	var str = xmlDoc.getElementsByTagName(id)[0].getElementsByTagName(element)[0].childNodes[0].nodeValue;
	return str;
}

