// Selected foodline
var foodline_selected = false;
var foodline_selected_last_dm = false;
var foodline_selected_current_dm = false;
var foodline_selected_last = false;
var foodline_selected_current = false;

var pagearea = 201;

// Marked the line as selected, and popup menu
function foodline_click(id, menu_id, e)
{
	var menu = menu_id & 15;
	var submenu = menu_id & 240;
	if (!e)
		var e = window.event;
	// Check for legal id
	if (!document.getElementById(id))
		return;
	$('.bgYellow').removeClass('bgYellow');
	$('#'+id).addClass('bgYellow');
	switch (submenu)
	{
		case 16:
			var desc = '{{LANG_2554}}';
			break;
		case 32:
			var desc = '{{LANG_2555}}';
			break;
		case 64:
			var desc = '{{LANG_2556}}';
			break;
		case 128:
			var desc = '{{LANG_2557}}';
			break;
	}
	if (menu == 0 || menu == 4)
	{
		var context = $('#contextmenu_foodline');
		if (typeof(context) != 'undefined')
		{
	//		context.cutnpaste($('#calendar_cut'), $('#calendar_paste_foodline'));
			$('#a_goto').text(desc);
			$('#a_goto').data('sub_menu', submenu);
			$('#change_weight').show();
	//		dm_ext_changeItem(menu, 1, 3, [desc, "javascript:menu_goto("+submenu+");", "goto.png" , "goto2.png", , , , , ]);
		}
	}
	if (menu == 1)
	{
		var context = $('#contextmenu_exercise');
		if (typeof(context) != 'undefined')
		{
//			context.cutnpaste($('#calendar_cut'), $('#calendar_paste_exercise'));
		}
	}
	if (menu == 2)
	{
		var context = $('#contextmenu_mealheader');
		if (typeof(context) != 'undefined')
		{
//			context.cutnpaste($('#calendar_cut'), $('#calendar_paste_mealheader'));
		}
	}
	if (menu == 3)
	{
		var context = $('#contextmenu_exerciseheader');
		if (typeof(context) != 'undefined')
		{
//			context.cutnpaste($('#calendar_cut'), $('#calendar_paste_exerciseheader'));
		}
	}
	if (menu == 4)
	{
		$('#change_weight').hide();
	}
	if (menu == 5)
	{
		var context = $('#contextmenu_exercise_addbonus');
		if (typeof(context) != 'undefined')
		{
//			context.cutnpaste($('#calendar_cut'), $('#calendar_paste_exercise_addbonus'));
		}
	}
	context.trigger('popup_menu', e);
	return false;
}

function right(str, n)
{
	if (n <= 0)
		return "";
	else if (n > String(str).length)
		return str;
	else {
		var iLen = String(str).length;
		return String(str).substring(iLen, iLen - n);
	}
}

// Detect selected meal and redirect to id 205
// allows the user to add more food
function menu_add_food() // TODO remove when test is done
{
	var id=$('.bgYellow').attr('id');
	if (!id)
	{
		return;
	}
	if (id.substring(0,1) == 'm')
	{
		if($("#FoodlogData").data("dietplan_id") > 0)
		{
			window.location = "/index.php?id=205&mealtype="+id.substring(1,2)+"&dietplan_id="+$("#FoodlogData").data("dietplan_id");
		}
		else
		{
			window.location = "/index.php?id=205&mealtype="+id.substring(1,2);
		}
	}
}

function menu_add_food_new(meal, type) { // rename to menu_add() when test is done TODO
	if(!meal){
		var meal = $('.bgYellow').attr('id').substring(1,2);
	}
	if(meal < 1 || meal > 8){
		return;
	}
	if(meal == 5){
		$(".bgYellow").removeClass("bgYellow");
		$("div.add").not(".template").remove(); // cleanup old divs
		var add_box = $("div.add").clone().removeClass("template"); // spawn an add_box
		$("select[name='type']", add_box).hide().html('<option value="exercise" selected="selected" />');
		add_box.insertAfter($("#m5").next()).data("meal", 5).show();
		$("select[name='type']", add_box).trigger("change"); // need to be after add_box.show()
	}
	else{
		if(!type){
			var type = 'food';
		}
		$(".bgYellow").removeClass("bgYellow");
		$("div.add").not(".template").remove(); // cleanup old divs
		var add_box = $("div.add").clone().removeClass("template"); // spawn an add_box
		add_box.insertAfter($("#m"+meal).next()).data("meal", meal).show();
		$("select[name='type'] option[value='"+type+"']", add_box).prop("selected",true);
		$("select[name='type']", add_box).trigger("change");
	}
}

function menu_add_text(id_override)
{
	if(id_override){
		var id=id_override;
	}
	else{
		var id=$('.bgYellow').attr('id');
	}
	if (!id)
	{
		return;
	}
	if (id.substring(0,1) == 'm')
	{
		$(".meal_comment p").show();
		$(".meal_comment form").hide();
		$(".meal_comment."+id+" p").hide();
		$(".meal_comment."+id+" form").show();
		$("textarea", $(".meal_comment")).focus();
	}
}
// Detect selected meal and redirect to id 208
// allows the user to add favorite
function menu_add_favorite(f_id)
{
	var id=$('.bgYellow').attr('id');
	if (typeof id != "undefined" && id.substring(0,1) == 'm')
	{
		window.location = "/index.php?id=208&f_id="+f_id+"&mealtype="+id.substring(1,2)+"&dietplan_id="+$("#FoodlogData").data("dietplan_id");
	}
}

// Detect selected meal and redirect to id 210
// allows the user to add favorite
function menu_add_favorite_exercise(f_id)
{
	var id=$('.bgYellow').attr('id');
	if (id.substring(0,1) == 'm')
	{
		window.location = "/index.php?id=210&f_id="+f_id+"&mealtype="+id.substring(1,2);
	}
}

/*
 * obsolete lw, 2012-01-10
// Detect selected meal or foodline and move it
function menu_move(mealtype)
{
	var id=$('.bgYellow').attr('id');
	xajax_move_foodline(mealtype, id);
}

// Detect selected meal or foodline and it it
function menu_delete()
{
	var id=$('.bgYellow').attr('id');
	xajax_delete_foodline(id);
}
*/

// Detect selected meal or foodline and change it
function menu_change_amount()
{
	var id=$('.bgYellow').attr('id');
	window.location = "/index.php?id=207&foodline="+id;
}

// Go to food, recipe, favorite or foodcalc
function menu_goto(menu_id)
{
	var id=$('.bgYellow').attr('id');
	var client = "";
	var client_id = $("#FoodlogData").data("owner_id");
	if (client_id > 0)
	{
		client = "&client="+client_id;
	}
	window.location = "/index.php?id=240&menu_id="+$('#a_goto').data('sub_menu')+"&foodline="+id+client;
}

// Add bonus to exercise
function menu_addbonus()
{
	var id=$('.bgYellow').attr('id');
	xajax_addbonus(id);
}

function select_amount() { $("#amount").select();}

$(document).ready(function() {
	$("#img_wg").click(function(){
		var weight_graph = $("#div_wg");
		if(weight_graph.is(":visible")){
			weight_graph.hide();
			$(this).attr("src","/gfx/template/h1_arrow_r.png");
  		$.getJSON('/api/sec/misc/layout_set.php', { 'element': 'wg', 'status': '0'}, function(data) { });
		}
		else{
			weight_graph.show();
			$(this).attr("src","/gfx/template/h1_arrow_d.png");
  		$.getJSON('/api/sec/misc/layout_set.php', { 'element': 'wg', 'status': '1'}, function(data) { });
		}
	});

	$(".contextmenu_day")
	.bind("click", function(e) {
		$('#dialog1').dialog('close');
		$("#contextmenu_day")
		.trigger('popup_menu', e);
	});
	$("#contextmenu_foodline, #contextmenu_mealheader, #contextmenu_exerciseheader, #contextmenu_exercise, #contextmenu_foodline, #contextmenu_exercise_addbonus")
	.bind("hide_menu", function() {
		if ($(".mMenu:visible").length == 0)
			$('.bgYellow').removeClass('bgYellow');
	});
	$("#closeExpireNotice").click(function()
		{
			$("#expireNotice").hide();
			xajax_layout_set('expireHide',1,$("#expireNotice").data('curDay'));
		});
	$(".meal_comment > p").live("click",function(){
		$(".meal_comment p").show();
		$(".meal_comment form").hide();
		$("form", $(this).closest(".meal_comment")).show();
		$(this).hide();
	});
	$("button.cancel", $(".meal_comment")).live("click", function(e){
		e.preventDefault();
		var answer = confirm($(this).data("confirm_msg"));
		if (answer){
			var container = $(this).closest("div.meal_comment");
			$("textarea", container).val($("textarea", container).data("orig_text"));
			$("form", container).hide();
			$("p", container).show();
		}
	});

	/* NEW ADD_FOOD */
	var typingTimer;
	var doneTypingInterval = 250;  // same value as the old 205 timer

	var info_instant_interval = 500;
	var info_ajax_timer;
	var reset_info_instant_allowed_timer;
	var info_instant_allowed = 1;

	// pool ajax requests
	$.xhrPool_search = []; // search
	$.xhrPool_search.abortAll = function() {
		$(this).each(function(idx, jqXHR) {
			jqXHR.abort();
		});
	};
	$.xhrPool_info = []; // info
	$.xhrPool_info.abortAll = function() {
		$(this).each(function(idx, jqXHR) {
			jqXHR.abort();
		});
	};

	function info_ajax(_this){
		info_instant_allowed = 0;
		$.xhrPool_info.abortAll();
		clearTimeout(reset_info_instant_allowed_timer);
		reset_info_instant_allowed_timer = setTimeout(function(){ info_instant_allowed = 1;}, info_instant_interval);
		var _parent = _this.closest("div.add");
		var type = $("select[name='type']", _parent);
		$("div.suggestlist", _this.closest("div.add")).remove();
		$.ajax({
			url: "/api/sec/add_food/info.php",
			dataType: 'json',
			data: {'type': type.val(), 'id': _this.val()},
			beforeSend: function(jqXHR) {
				$.xhrPool_info.push(jqXHR);
			},
			complete: function(jqXHR) {
									var index = $.xhrPool_info.indexOf(jqXHR);
									if (index > -1) {
										$.xhrPool_info.splice(index, 1);
									}
								},
			success: function(data) {
								 // cache selectors we use often
								 var _div_info = $("div.info", _parent);
								 var _td_amount = $("td.amount", _parent);
								 // reset existing div.info
								 $("div.cdnutrition, table.nutrition", _div_info).add(_td_amount).html('');
								 $("div.additional_elements", _div_info).remove();
								 // td.amount
								 if(type.val() == 'favorite'){
									 _td_amount.append($('<p>'+type.find('option[value="favorite"]').data("str1")+'</p>'));
								 }
								 else if(type.val() == 'exercise'){
									 _td_amount.data("current_bonus_step", data.current_bonus_step).append($('<p>Varighed: <input type="text" size="3" name="amount" autocomplete="off" data-measure="1" data-g_pr_unit="1" /> minutter <span class="selected_nutrition_info"></span></p>'));
								 }
								 else{
									 _td_amount.append($('<p><input name="multiplier" type="radio" /><input type="text" size="3" name="amount" autocomplete="off" data-measure="1" data-g_pr_unit="1" /> gram <span class="selected_nutrition_info"></span></p>'));
								 }
								 if(type.val() == 'food'){
									 $("p", _td_amount).filter(":first").append(
											 "<span class='helpText save_measure' data-subject='save_measure'>Husk mængde</span>"+
											 "<div class='helpText_content' title='Husk mængde' id='help_save_measure'>"+
											 "<form method='POST' action='' id='save_measure'>"+
											 "<input type='hidden' name='id' value='"+_this.val()+"' />"+
											 "<input type='hidden' name='gram' value='' />"+
											 "<p>Husk mængden, så du fremover kan vælge den når du indtaster madvaren:</p>"+
											 "<p>Mængde: <input type='text' name='measure_text' autocomplete='off' /> fx. '3 stk'</p>"+
											 "<p><button type='submit'>Gem</button></p>"+
											 "</form>"+
											 "</div>"
											 );
								 }
								 if(data.measures){
									 $.each(data.measures, function() {
										 _td_amount.append($(
												 '<p class="disabled"><input name="multiplier" type="radio" /> '+this.label+' ('+u_unit(this.gram)+' g)'+
												 '<label> <input type="text" size="1" name="amount" value="1" autocomplete="off" data-measure="'+this.id+'" data-g_pr_unit="'+this.gram+'" /> stk</label>'+
												 ' <span class="selected_nutrition_info"></span></p>'));
									 });
								 }
								 if(data.measures_recipe){
									 _td_amount.append($(
												 '<p class="disabled"><input name="multiplier" type="radio" /> Delportion'+
												 '<label>: <select name="amount" data-g_pr_unit="1"></select> af den totale opskrift </label></p>'));
									 $.each(data.measures_recipe, function() {
										 $("select[name='amount']", _td_amount).append($('<option value="'+this.gram+'">'+this.label+'</option>'));
									 });
									 $("p.disabled:first label", _td_amount).append($('<span class="selected_nutrition_info"></span>'));
									 $("select[name='amount']", _td_amount).trigger("change");
								 }
								 if(type.val() == 'exercise'){
									 _td_amount.append($('<p>Bonus: <select name="bonus" /></p>'));
									 update_bonus_steps($("select[name='bonus']", _td_amount), 0, null);
								 }
								 $("input[name='multiplier']", _td_amount).attr("tabindex","-1"); // doesn't work in IE, due to a bug, where negative tabindex doesn't work on input[type='radio']
								 // div.info
								 $("p.name", _div_info).html(data.name);
								 if(data.img) {
									 $("div.cdnutrition", _div_info).html('<img src="'+data.img+'" />');
								 }
								 if(data.nutritions){
									 $.each(data.nutritions, function() {
										 $("table.nutrition", _div_info).append($("<tr class='"+this.nutrition+"' data-value='"+this.value+"' data-label='"+this.label+"'><td>"+this.infobox_label+"</td><td>"+this.infobox_value+"</td></tr>"));
									 });
								 }
								 if(data.additional_elements){
									 _div_info.append("<div class='additional_elements' />");
									 $.each(data.additional_elements, function() {
										 if(this.type == 'recipe_weight'){
											 $("#help_recipe_100g_info, #help_recipe_edit_weight").remove(); // http://forum.jquery.com/topic/dialog-will-move-its-div-tag-to-body
											 $("div.additional_elements", _div_info).append("<p class='additional_element'><span class='helpText' data-subject='recipe_100g_info'>"+this.text1a+"</span></p>"+
												 "<div class='helpText_content' id='help_recipe_100g_info' title='"+this.text1a+"'>"+this.text1b+"</div>");
											 $("div.additional_elements", _div_info).append("<div class='helpText_content' id='help_recipe_raw_weight' title='"+this.text2a+"'>"+this.text2b+"</div>");
											 $("div.additional_elements", _div_info).append("<div class='helpText_content' id='help_recipe_prepared_weight' title='"+this.text3a+"'>"+this.text3b+"</div>");
										 }
										 if(this.type == 'recipe_link'){
											 $("#help_recipe_link").remove(); // http://forum.jquery.com/topic/dialog-will-move-its-div-tag-to-body
											 $("div.additional_elements", _div_info).append("<p class='additional_element'><span data-iframe='/scripts/printpdf.php?recipe_id="+_this.val()+"&wide=1' class='helpText big' data-subject='recipe_link'>"+this.text+"</span></p><div class='helpText_content' id='help_recipe_link' title='"+data.name+"'></div>");
										 }
										 if(this.type == 'exercise_info'){
											 $("div.additional_elements", _div_info).append("<p class='additional_element'>"+this.text1a+"</p>");
										 }
									 });
								 }
								 $("tr."+data.selected_nutrition, _div_info).addClass("selected_nutrition");
								 if(type.val() == 'exercise'){
									 $("table.nutrition", _div_info).hide();
								 }
								 // show everything
								 $("div.info, button, tr.amount", _parent).show();
							 }
		});
	}

	$("#main_container")
	.on("click", "div.add .ui-dialog-titlebar-close", function(e){
		e.preventDefault();
		$(this).closest("div.add").remove();
	})
	.on("keyup", "div.add input[name='searchstring']", function(e){
		var _this = $(this);
		var _parent = $(this).closest("div.add");
		if(e.keyCode == 40){ // Down (execute before comparing old value)
			var _enabled_options = $("select[name='options'] option", _parent).not(":disabled");
			if(_enabled_options.length == 0){
				return;
			}
			_enabled_options.first().attr('selected','selected');
			$("select[name='options']", _parent).focus().trigger("change");
			return;
		}
		if(_this.data("old_value") == _this.val()) { // check before cancelling ajax, due to timing issues otherwise
			return false;
		}
		$(".overlay").remove();
		_this.data("old_value",_this.val());
		$.xhrPool_search.abortAll();
		clearTimeout(typingTimer);
		var options = $("select[name='options']", _parent);
		var type = $("select[name='type']", _parent);
		$("div.info, button", _parent).hide();
		$("td.amount", _parent).html('');
		options.html('');
		$("div.suggestlist", _parent).remove();
		if(_this.val().length < 2 && ( type.val() == 'food' || type.val() == 'recipe') ){
			options.append(
					$("<option>", {
						text: type.find('option:selected').data("str1")
					}).addClass("dimmed").attr("disabled",true));

			// the next 2 lines are due to an IE 9 bug
			// http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option
			if ($.browser.msie) {
				var width_tmp = options.outerWidth();
				options.width(width_tmp);
			}
			return false;
		}
		var _parent_width = options.width();
		var _parent_height = options.height() -1;
		var _overlay_container = $("<div style='position: relative;' />").prependTo(options.closest("td"));
		$("<div class='overlay' style='margin: 1px'><img src='/gfx/ajaxLoader.gif' /></div>").width(_parent_width).height(_parent_height).css("line-height",_parent_height+"px").prependTo(_overlay_container).show();
		typingTimer = setTimeout(function(){
			$.ajax({
				url: "/api/sec/add_food/search.php",
				dataType: 'json',
				data: {'type': type.val(), 'searchstring': _this.val()},
				beforeSend: function(jqXHR) {
					$.xhrPool_search.push(jqXHR);
				},
				complete: function(jqXHR) {
										var index = $.xhrPool_search.indexOf(jqXHR);
										if (index > -1) {
											$.xhrPool_search.splice(index, 1);
										}
									},
				success: function(data) {
									 if(data){
										 $.each(data.result, function() {
											 options.append(
												 $("<option>", {
													 text: this.name,
												 value: this.id 
												 }).addClass(this._class));
										 });
										 if(type.val() == 'food' && $("option", options).hasClass("entered_before")){
											 $("option.entered_before").filter(":first").before(
													 $("<option>", {
														 text: 'Mad du har indtastet før:',
														 value: 0
													 }).attr("disabled",true));
											 $("option.entered_before").prepend("&nbsp;&nbsp;");
										 }
										 if(type.val() == 'food' && data.suggestlist){
											 $("div.suggestlist", _parent).remove();
											 $("div.add div.info").before("<div class='suggestlist' />");
											 $.each(data.suggestlist, function(){
												 $("div.suggestlist", _parent).append("<p><a href='' class='suggestion'>"+this.text+"</a> ("+this.count+")</p>");
											 });
										 }
										 if(type.val() == 'exercise'){
											 var first = $("option:first", options);
											 $("option[value='100']", options).insertBefore(first);
										 }
									 }
									 else{
										 options.append($("<option class='dimmed' disabled='disabled'>"+type.data("str1")+"</option>"));
									 }
									 // the next 2 lines are due to an IE 9 bug
									 // http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option
									 if ($.browser.msie) {
										 var width_tmp = options.outerWidth();
										 options.width(width_tmp);
									 }
									 $(".overlay").remove();
								 }
			});
		}, doneTypingInterval);
	})
	.on("click", "div.add a.suggestion", function(e){
		e.preventDefault();
		var _parent = $(this).closest("div.add");
		var _this = $(this);
		$("input[name='searchstring']", _parent).val(function( index, value ) { return value + ' ' + _this.text(); }).trigger("keyup");
	})
	.on("change", "div.add select[name='type']", function(){
		var _parent = $(this).closest("div.add");
		$("input[name='searchstring']", _parent).removeData("old_value").focus().trigger("keyup");
	})
	.on("change", "td.amount select[name='bonus']", function(){
		$(this).closest("td.amount").data("current_bonus_step", $(this).val());
	})
	.on("change", "div.add select[name='options']", function(){
		var _this = $(this);
		if(!$(this).val()) { return false;}
		clearTimeout(info_ajax_timer);
		if(info_instant_allowed == 1){
			info_ajax($(this));
		}
		else{
			clearTimeout(reset_info_instant_allowed_timer);
			reset_info_instant_allowed_timer = setTimeout(function(){ info_instant_allowed = 1;}, info_instant_interval);
			info_ajax_timer = setTimeout(function(){info_ajax(_this);}, info_instant_interval);
		}
	})
	.on("click", "div.add td.amount input[type='radio']", function(){
		var _parent_td = $(this).closest("td");
		var _parent_p  = $(this).closest("p");
		var _amount = $("[name='amount']", _parent_p);
		// disable all
		$("p", _parent_td).addClass("disabled");
		$("input[type!='radio'],select", _parent_td).attr("disabled",true);
		// enable this
		_parent_p.removeClass("disabled");
		$("input,select", _parent_p).attr("disabled",false);
		_amount.trigger((_amount.is("input")?"keyup":"change"));
	})
	.on("click", "div.add td.amount input[type='text']", function(){
		$(this).select();
	})
	.on("focus", "div.add td.amount input[name='amount']", function(){
		$("input[type='radio']", $(this).closest("p")).prop("checked",true);
	})
	.on("keyup", "div.add td.amount input[name='amount']", function(e){
		if(e.keyCode == 38 || e.keyCode == 40){
			var _parent = $(this).closest("div.add");
			var _parent_p = $(this).closest("p");
			if(e.keyCode == 38){ // Up
				var _prev = _parent_p.prev();
				if(_prev.is("p")){
					$("input[type='radio']", _prev).trigger("click");
					$("input[type='text']", _prev).focus();
				}
				else{
					$("select[name='options']", _parent).focus();
				}
			}
			if(e.keyCode == 40){ // Down
				var _next = _parent_p.next();
				if(_next.is("p")){
					$("input[type='radio']", _next).trigger("click");
					$("input[type='text']", _next).focus();
				}
			}
		}
		else{
			update_selected_nutrition($(this));
		}
	})
	.on("change", "div.add td.amount select[name='amount']", function(){
		update_selected_nutrition($(this));
	})
	.on("blur", "div.add td.amount input[name='amount']", function(){
		var value = calculate_field($(this).val());
		if(value){
			$(this).val(value);
		}
	})
	.on("click", "div.add td.amount span.save_measure", function(){
		var _parent = $(this).closest("p");
		var gram = $("input[name='amount']", _parent).val();
		$("form#save_measure input[name='gram']").val(gram);
	})
	.on("submit", "div.add form", function(e){
		e.preventDefault();
		var _parent = $(this).closest("div.add");
		var _parent_width = _parent.outerWidth() - 2;
		var _parent_height = _parent.outerHeight() - 2;
		$("<div class='overlay' style='background: #fff;'><img src='/gfx/ajaxLoader.gif' /></div>").width(_parent_width).height(_parent_height).css("line-height",_parent_height+"px").prependTo(_parent).show();
		var _input = $("input[name='amount']:visible", _parent).not(":disabled");
		if(_input.length > 0){
			var amount = calculate_field(_input.val());
		}
		var type = $("select[name='type']", _parent).val();
		var id = $("select[name='options']", _parent).val();
		var measure = _input.data("measure");
		var meal = _parent.data("meal");
		var bonus = $("select[name='bonus']", _parent).val();
		$.getJSON("/api/sec/add_food/submit.php", {
			'type': type,
			'id': id,
			'amount': amount,
			'measure': measure,
			'meal' : meal,
			'bonus' : bonus
		}, function(data){
			if(data.html){
				// refresh foodlog html
				$("#foodlog").replaceWith(data.html.foodlog);
				$("#energyboxContainer").replaceWith(data.html.energybox);
				$("#energyboxDetailsContainer").replaceWith(data.html.energybox_details);
				$("#calendar_20x").html(data.html.calendar);
				eval(data.html.jq_assign_data);
				rebindlive_foodlog();
				rebindlive();
				update_foodxml(data.user_id);
				menu_add_food_new(meal, type);
			}
		});
	});
	$(document).on("submit", "form#save_measure", function(e){
		e.preventDefault();
		var _parent = $(this).closest("div");
		var id = $("input[name='id']", _parent).val();
		var gram = $("input[name='gram']", _parent).val().replace(",",".");
		var measure_text = $("input[name='measure_text']", _parent).val();
		if(!id || !gram || !measure_text){
			return false;
		}
		$.getJSON('/api/sec/add_food/save_measure.php', { 'id': id, 'gram': gram, 'measure_text': measure_text}, function(data) {
			var _div_add = $("div.add").not(".template");
			$("td.amount", _div_add).append($(
					'<p class="disabled"><input name="multiplier" type="radio" /> '+measure_text+' ('+u_unit(gram)+' g)'+
					'<label> <input type="text" size="1" name="amount" value="1" autocomplete="off" data-measure="'+data.id+'" data-g_pr_unit="'+gram+'" /> stk</label>'+
					' <span class="selected_nutrition_info"></span></p>'));
			$("td.amount input[name='amount']", _div_add).each(function(){
				if($(this).data('g_pr_unit') == gram){
					$("input[type='radio']", $(this).closest("p")).prop("checked",true).trigger("click");
				}
			});
			$(".helpText_content").dialog("close"); // this is triggered last, to avoid that the user continues, before his new measure is ready (he will be on a modal dialog)
		});
	})
	.on("submit", "form#save_prepared_weight", function(e){
		e.preventDefault();
		var _parent = $(this).closest("div");
		var id = $("input[name='id']", _parent).val();
		var prepared_weight = $("input[name='prepared_weight']", _parent).val().replace(",",".");
		if(!id){
			return false;
		}
		$.getJSON('/api/sec/add_food/edit_prepared_weight.php', { 'id': id, 'prepared_weight': prepared_weight}, function(data) {
			var _div_add = $("div.add").not(".template");
			$("select[name='options']", _div_add).trigger("change");
			$(".helpText_content").dialog("close"); // this is triggered last, to avoid that the user continues, before his new measure is ready (he will be on a modal dialog)
		});
	});

});

function sendtouser(date)
{
  $.getJSON('/api/sec/foodlog/sendtouser.php', { 'date': date}, function(data) {
		if(data.status == 'error') { alert(data.msg); return;}
		$('.bgYellow').removeClass('bgYellow');
		$("#main_container").prepend(data.html);
		$("#sendtouser_username").unbind().keyup(function(){ $(this).parent().css('border','1px solid transparent'); });
		$("#sendtouser_close").unbind().click(function() { $("#sendtouserDiv").remove(); });
		$("#sendtouserDiv").css({"width":$("#sendtouserDiv").width()+"px","height":$("#sendtouserDiv").height()+"px"});
  })
}

function sendtouser_submit(date)
{
	var username = $("#sendtouser_username").val();
	if(username.length == 0) { 
		$("#sendtouser_username").focus().parent().css("border","1px solid red"); 
		return;
	}
	var title = $("#sendtouser_title").val();
	var message = $("#sendtouser_message").val();
  $.getJSON('/api/sec/foodlog/sendtouser.php', { 'date': date, 'username': username, 'title': title, 'message': message}, function(data) {
		if(data.status == 'ok') { $('#sendtouserDiv').html(data.html);}
		else { $(".error").remove(); $("button", $("#sendtouserDiv")).after("<span class='"+data.status+"' style='margin-left: 15px;'>"+data.msg+"</span>");}
		$("#sendtouser_close").unbind().click(function() { $("#sendtouserDiv").remove(); });
  })
}

function menu_edit(action, type)
{
	$("#clipboard_dialog .ok").remove();
	$("#clipboard_dialog .error").removeClass("error");
	if (type == 'd0')
	{
		var item = 'd0';
	} else {
		var item = $('.bgYellow').attr('id');
	}
	if(action == 'batch_paste')
	{
		var days = $("#batch_paste_days").val();
		if(days < 1)
		{
			$("#batch_paste_days").addClass("error");
			return;
		}
		if(days > 7)
		{
			var str1 = $("#clipboard").data("str1").replace("XXX",days);
			var answer = confirm(str1);
			if (!answer){
				return;
			}
		}
	}
	if(action == 'delete' && item == 'd0')
	{
		$('.mMenu:visible').mMenuHide();
		var answer = confirm($("#main_container").data("confirm_msg"));
		if (!answer){ return false;}
	}
  $.getJSON('/api/sec/foodlog/edit.php', { 'item': item, 'action': action, 'days': days, 'dietplan_id': $("#FoodlogData").data("dietplan_id") }, function(data) {
		if(!data) { return;}
		if(data.err_msg) {
			alert(data.err_msg);
			return;
		}
		if(data.clipboard_size > 0) // refresh clipboard
		{
			$("#clipboard").show();
			$("#clipboard_size").text(data.clipboard_size);
		}
		if(data.html) // refresh foodlog html
		{
			$("#foodlog").replaceWith(data.html.foodlog);
			$("#energyboxContainer").replaceWith(data.html.energybox);
			$("#energyboxDetailsContainer").replaceWith(data.html.energybox_details);
			$("#calendar_20x").html(data.html.calendar);
			eval(data.html.jq_assign_data);
			rebindlive_foodlog();
			rebindlive();
			update_foodxml(data.user_id);
		}
		if(action == 'batch_paste')
		{
			$("#batch_paste_days").val('');
			$("#clipboard_dialog > p").append('<span class="ok" style="margin-left: 10px;">{{LANG_4149}}</span>');
		}
		if(data.redirect){ window.location = data.redirect;}
  })
}

$("#clipboard").click(function(e){
	clipboard('view', e);
});

function clipboard(action, e)
{
  $.getJSON('/api/sec/foodlog/clipboard.php', {'action': action}, function(data) {
		if(!data) { return;}
		$("#clipboard_dialog").dialog('destroy').remove();
		if(data.clipboard_size > 0) // refresh clipboard
		{
			$("#clipboard").show();
			$("#clipboard_size").text(data.clipboard_size);
		}
		else
		{
				$("#clipboard").hide();
		}
		if(data.contents) // show clipboard contents
		{
			var str2 = $("#clipboard").data("str2");
			var reset_html = '<p style="margin-bottom: 0; font-size: 11px;">'+
				'<button type="button" onclick="clipboard(\'delete\');return false;" style="float: right;">{{LANG_275}}</button>'+
				str2+
				'</p>';
			var dialog = '<div id="clipboard_dialog">'+data.contents+reset_html+'</div>';
			$(dialog).dialog({ 
				minHeight: 0,
				position: [e.clientX-300, e.clientY],
				resizable: false,
				title: "{{LANG_4058}}"
			});
			$("button").blur();
		}
  })
}

function calculate_field(value){
	var max_allowed_chars = 20;
	if(value.length > max_allowed_chars || value.match(/[^0-9\+\-*\/ \.,\(\)]/)){
		return false;
	}
	else{
		value = value.replace(",", ".");
	}
	try {
		value = parseFloat(eval(value));
	} catch (e) {
		if (e instanceof SyntaxError) {
			return false;
		}
	}
	return value;
}

function update_selected_nutrition(_this)
{
	var _parent = _this.closest("div.add");
	var _parent_p = _this.closest("p");
	var selected_nutrition = $("tr.selected_nutrition", _parent);
	$("span.selected_nutrition_info, span.save_measure", _parent).hide();
	var value = calculate_field(_this.val());
	if(value > 0 && value < 100000) {
		var v = value * (selected_nutrition.data("value") / 100) * _this.data("g_pr_unit");
		if(v) {
			if(v > 10) { v = v.toFixed();}
			else { v = v.toFixed(1); }
			$("span.selected_nutrition_info", _parent_p).html('('+ u_unit(v) +' '+selected_nutrition.data("label")+')').show();
			$("span.save_measure", _parent_p).show();
		}
	}
	update_bonus_steps($("select[name='bonus']", _parent), v, selected_nutrition.data("label"));
}

function update_bonus_steps(selectbox, exercise_kj, label){
	if(selectbox.length == 0){
		return;
	}
	selectbox.html('').hide();
	var bonus_steps = new Array(0, 0.25, 0.50, 0.75, 1);
	$.each(bonus_steps, function(){
		if(exercise_kj > 0 && this > 0){
			var bonus = this*exercise_kj;
			if(bonus > 10) { bonus = bonus.toFixed();}
			else { bonus = bonus.toFixed(1); }
			var text = this*100+"% ("+u_unit(bonus)+" "+label+")";
		}
		else{
			var text = (this == 0?"Ingen":this*100+"%");
		}
	selectbox.append(
		$("<option>", {
			text: text,
			value: this
		}));
	});
	var current_bonus_step = selectbox.closest("td.amount").data("current_bonus_step");
	$("option[value='"+current_bonus_step+"']", selectbox).prop("selected",true);
	selectbox.show();
}

