/* TOOLTIPS AND HELPICONS */
/* BLUE BOX TEMPLATE */
jQuery(document).ready(function() {

	// TODO: delete this after the new add-food-from-201 has been implemented
	// generic class for opening a modal jquery dialog
  $('a.open_modal_dialog').live('click', function (e) {
    e.preventDefault();
    var page = $(this).attr("href")
    var pagetitle = $(this).attr("title")
    var $dialog = $('<div style="overflow: hidden;"></div>') // TODO: show spinning load gif while iframe is loading
    .html('<iframe style="margin: 0; padding: 0; border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
    .dialog({
      autoOpen: false,
      resizable: false,
      modal: true,
      height: $(window).height() * 0.9,
      width: 800,
      title: pagetitle
    });
  $dialog.dialog('open');
  });

		if (window.madlog_mobile)
		{
			var factor = 10;
		} else {
			var factor = 1; }
		rebindlive();
		// QTIP beginner's tips
		$(".qtipTt").each(function() {$(this).trigger('triggerQtip');});

//		if(window.location.hash.length == 0)
			if($("form").size() == 1)
			{
				$('#login_username').focus();
			}
		$('.focus_here').focus();
		$("button.link").click(function(){
			var label = $(this).text();
			$(this).text('');
			var buttonValue = $(this).val();
			$(this).text(label);
			window.location = buttonValue;
		});
		// Header, global
		$("#headerIcons img").hover(
				function() {var newSrc=$(this).attr("src").replace(/(No)?Hover/,"Hover"); $(this).attr("src",newSrc);},
				function() {var newSrc=$(this).attr("src").replace(/(No)?Hover/,"NoHover"); $(this).attr("src",newSrc);});
		$("#headerUsername")
			.hover(
				function() {$(this).css({"border-bottom":"1px solid #eee"});},
				function() {$(this).css({"border-bottom":"1px solid transparent"});
				})
			.click(function() {
				if($("#headerUsernameDropdown").is(":visible"))
					$("#headerUsernameDropdown").hide();
				else
				{
					if (headerUsernameDropdown_timer != false)
					{
						clearTimeout(headerUsernameDropdown_timer);
						headerUsernameDropdown_timer = false;
					}
					$("#headerUsernameDropdown").show();
				}
				$(this).css({"border-bottom":"1px solid transparent"});
				return false;
				});
		/* end */
		var headerUsernameDropdown_timer = false;
		var newsDropdown_timer = false;
		$("#headerUsernameDropdown").click(function(e) {e.stopPropagation();});
		$("#headerUsernameDropdown")
			.mouseover(function(e) {
					e.stopPropagation(); $("#headerUsername").css({"border-bottom":"1px solid transparent"});
					if (headerUsernameDropdown_timer != false)
					{
						clearTimeout(headerUsernameDropdown_timer);
						headerUsernameDropdown_timer = false;
					}
				})
			.mouseleave(function() {
					if (headerUsernameDropdown_timer != false)
					{
						clearTimeout(headerUsernameDropdown_timer);
					}
					headerUsernameDropdown_timer = setTimeout(function() {
						$("#headerUsernameDropdown").hide();
						}, 1000*factor);
				});
		$(".headerCnt").click(function() { $(this).prev().trigger('click');});
		$("#headerIconNews").click(function(event) {
				if($("#newsDropdown").is(":visible"))
				{
					$("#newsDropdown").hide();
					$("#headerIconNews").attr("src","/gfx/template/headerIcons/newsOffNoHover.png");
				}
				else
				{
					$("#newsDropdown").show();
					$("#headerIconNews").attr("src","/gfx/template/headerIcons/newsClicked.png");
					$("#headerIconNews").next().remove();
					xajax_show_news();
				} });
		$("#newsDropdown")
				.mouseover(function(e) {
						if (newsDropdown_timer != false)
						{
							clearTimeout(newsDropdown_timer);
							newsDropdown_timer = false;
						}
					})
				.mouseleave(function() {
						if (newsDropdown_timer != false)
						{
							clearTimeout(newsDropdown_timer);
						}
						newsDropdown_timer = setTimeout(function() {
							$("#headerIconNews").attr("src","/gfx/template/headerIcons/newsOffNoHover.png");
							$("#newsDropdown").hide();
							}, 1000*factor);
				});
		$("#loginBtn").click(function() {$("#login_form").submit();});
		if($("body").data("doc.title")) { document.title = $("body").data("doc.title");}
	});

function rebindlive()
{
		$(".qtipTt")
			.unbind('triggerQtip')
			.bind('triggerQtip', function() {
			if(!$(this).data('content') ||!$(this).is(":visible"))
				return;
			// disable for IE6 and lower
			if($.browser.msie && $.browser.version=="6.0") 
			{ 
				return;
			};
			var tipId = $(this).data('tipId');
			var tipIdDOM = $(this).attr('id');
			$(this).qtip({
				content: {text:$(this).data("content"), title: { text:$(this).data("title"), button: "X" }},
				show: { when: false, ready: true },
				hide: { when: "event:never" },
				api: {onHide: function(){$('#'+tipIdDOM).removeClass('qtipTt');xajax_log_tt(tipId);xajax_layout_set(tipId,1);}}, // the tipIdDOM selector is for js triggered pages (like 804)
				position: {
					corner: {
						target: $(this).data("targetCorner"),
						tooltip: $(this).data("tooltipCorner")
					},
					adjust: {screen: true, x:$(this).data('offsetX'), y:$(this).data('offsetY')}
				},
				style: {
					tip: $(this).data("tooltipCorner"),
					"background-color": "#eff7ff",
					"font-size":"12px",
					"font-family":"'Helvetica Neue',Arial,Helvetica,Geneva,sans-serif",
					"line-height":"16px",
					border: {
						width: 3,
						radius: 3,
						color: "#95b5d9"
					},
					title: {
						"background-color": "#b3cce9",
						"color": "#172a44",
						"font-size":"13px",
						"font-weight":"bold",
						"padding-top":"3px",
						"padding-bottom":"5px"
					},
					button: {
						"color": "#172a44",
						"font-size":"13px",
						"font-weight":"bold"
					}
				}
			});
		});

	// QTIP tooltip
	$("img.tooltip, a.tooltip").unbind().each(function(){
		// replace with mTooltip for IE6 and lower
		if($.browser.msie && $.browser.version=="6.0") 
		{ 
			$(this).addClass("mTooltip");
			$(this).data("mTooltipContent","<div style=\"font-size: 12px; width: 250px; background-color: #dedede; \">"+$(this).data("helpTxt")+"</div>");
			return;
		};
		// hack because qtip doesnt hide the title tag, when showing the tip
		$(this).attr('title','');
		$(this).qtip({
		content: {text: $(this).data("helpTxt"), title: { text:false }},
		show: {delay: 0},
		hide: { fixed: true },
		position: { 
			adjust: { screen: true, x:0, y:10 } 
		},
		style: {
			tip: true,
			"color":"#ffffff",
			"background-color": "#22324b",
			"font-size":"12px",
			"font-family":"Verdana,Arial,Sans-serif",
			"line-height":"18px",
			width: {max: 290},
			border: {
				width: 8,
				radius: 8,
				color: "#22324b"
			}
		}
	});
	});
	// mTooltip
	var mTooltipTimer = false;
	var mTooltipItem = false;
	var mTooltipEvent = false;
	$(".mTooltip")
		.unbind('.mTooltip')
		.bind('mousemove.mTooltip', function(e) {
			// use e.stopPropagation to only show the first tooltip initiated
			e.stopPropagation();
			$(".mTooltipContent").remove();
			// Manage delay timer
			if (mTooltipTimer != false)
			{
				clearTimeout(mTooltipTimer);
				mTooltipTimer = false;
				mTooltipItem = false;
			}
			if($(this).is(".foodline, .mealheader"))
			{
				if($("div.add").is(":visible")){
					return;
				}
				var delay = 400;
			}
			else
			{
				var delay = 140;
			}
			mTooltipItem = this;
			mTooltipEvent = e;
			mTooltipTimer = setTimeout(function() {
				// dont show if these elements are visible
				if($("#dialog1").is(":visible"))
				{
					return;
				}
				var e = mTooltipEvent;
				// target is a foodline with a tooltip effect (201)
				if($(mTooltipItem).is(".foodline, .mealheader"))
				{
					var content = $("<div>"+cns_infobox($(mTooltipItem).attr('id'))+"</div>");
					$(content).css({"font-size":"11px","width":"240px","background-color":"white","display":"none","border":"1px solid #666"}).addClass('mTooltipContent').appendTo('body');
				}
				// target is a tooltip with it's content in a data element
				if($(mTooltipItem).data("mTooltipContent"))
				{
					var content = $($(mTooltipItem).data("mTooltipContent"));
					$(content).css({"display":"none", "border":"1px solid #bbb", "padding":"3px 7px"}).addClass('mTooltipContent').appendTo('body');
				}
				// target is a tooltip with it's content in it's title
				if($(mTooltipItem).hasClass("dataFromTitle"))
				{
					var content = $('<span style="background: #ffff88;">'+$(mTooltipItem).attr("title")+'</span>');
					$(content).css({"display":"none", "border":"1px solid #bbb", "padding":"3px 7px"}).addClass('mTooltipContent').appendTo('body');
				}
				// target is an image
				if($(mTooltipItem).is('img'))
				{
					if($(mTooltipItem).attr('src').match(/cdnutrition/))
					{
						if($(mTooltipItem).attr('src').match(/static/))
						{
							var src = $(mTooltipItem).attr('src').replace(/cdnutrition\/[0-9]+/,"cdnutrition/2");
						}
						else
						{
							var src = $(mTooltipItem).attr('src').replace(/style=[0-9]+/,"style=2");
						}
						var content = $("<img src="+src+" />");
						$(content).css({"display":"none","border":"1px solid #bbb"}).addClass('mTooltipContent').appendTo('body');
					}
				}
				// target is a normal tooltip, where it takes content from the .next div, and clones it's style
				if(!content)
				{
					var content = $(mTooltipItem).next().clone().addClass('mTooltipContent').appendTo('body');
				}
				// apply default css and position according to mousemove event
				//( we create the tooltip div as a new element in the dom, to be able to remove it )
				//( and add it again later and because we need to calculate the position with relation )
				//( to the body and not whatever relative context it may be placed in) )
				$(content).css({left:(e.pageX+10) + "px", top:(e.pageY+10) + "px", "z-index":"2000", "position":"absolute"});
				// test for edge collision and re-position
				if(e.pageX + content.outerWidth() + 10 > $(window).width())
				{
					$(content).css({left:(e.pageX-10 - content.outerWidth()) + "px"});
				}
				if(e.pageY - $(window).scrollTop() + content.outerHeight() + 10 > $(window).height())
				{
					if(e.pageY - $(window).scrollTop() - content.outerHeight() > 0)
					{
						$(content).css({top:(e.pageY-10 - content.outerHeight()) + "px"});
					}
				}
				// done - show it!
				$(content).show();
			}, delay);
		})
		.bind('mouseleave.mTooltip', function() {
			if (mTooltipTimer != false)
			{
				clearTimeout(mTooltipTimer);
				mTooltipTimer = false;
			}
			mTooltipItem = false;
			$(".mTooltipContent").remove();
			});
	/* CALENDAR */
	$('td.Cal_sDatecell')
		.unbind()
		.bind('mouseover', function() {
			$(this).addClass('Cal_hoverCell');
			})
		.bind('mouseout', function() {
			$(this).removeClass('Cal_hoverCell');
			})
		.bind('click', function() {
			var clicked_date = $(this).data('date');
			if($(this).parents('.calendar:first').attr('id').match(/20x/))
			{
				window.location = '/scripts/change_date.php?user_date='+ clicked_date +'&uid='+ $("#calendar_20x").data("uid") +'&key='+ $("#calendar_20x").data("key");
			}
			if($(this).parents('.calendar:first').attr('id').match(/foodcalc|recipe/))
			{
				transfer(clicked_date);
			}
			if($(this).parents('.calendar:first').attr('id').match(/804/))
			{
			  var uid = $("img.photo").attr("id").replace(/^photo/,'');
				xajax_change804(uid, 'date', clicked_date);
			}
			if($(this).parents('.calendar:first').attr('id').match(/foodlog/))
			{
				if($('.bgYellow').attr('id'))
				{
					xajax_copy_foodline($('.bgYellow').attr('id'), clicked_date);
				}
				else
				{
					xajax_copy_day(clicked_date);
				}
			}
			if($(this).parents('.calendar:first').attr('id').match(/message/))
			{
				$('td.Cal_sDatecell').removeClass("clicked_date");
				$(this).addClass("clicked_date");
				do_transfer();
			}
			$('.mMenu:visible').mMenuHide();
			});
	$('span.jumpToday')
		.unbind()
		.bind('click', function() {
			var d = new Date();
			// Format date as YYYY-mm-dd
			var myDate = d.getFullYear() +'-'+ (d.getMonth() < 9 ? '0' : '') + (d.getMonth() + 1) + '-'+ (d.getDate() < 10 ? '0' : '') + d.getDate();
			xajax_calendar($(this).parent().siblings('div.calendar').attr('id'), myDate, $(this).parents('.calendar:first').data('uid'), $(this).parents('.calendar:first').data('key'));
			})
		.bind('mouseover', function() {
			$(this).css({'cursor' : 'pointer', 'text-decoration' : 'underline'});
			})
		.bind('mouseout', function() {
			$(this).css({'cursor' : 'default', 'text-decoration' : 'none'});
			});
	$('.Cal_prevMonth')
		.unbind()
		.bind('mouseover', function() {
			$(this).css({'cursor':'pointer','background-image':'url("/gfx/calendar/prevMonthHover.png")'});
		})
		.bind('mouseout', function() {
			$(this).css({'background-image':'url("/gfx/calendar/prevMonth.png")'});
		});
	$('.Cal_nextMonth')
		.unbind()
		.bind('mouseover', function() {
			$(this).css({'cursor':'pointer','background-image':'url("/gfx/calendar/nextMonthHover.png")'});
		})
		.bind('mouseout', function() {
			$(this).css({'background-image':'url("/gfx/calendar/nextMonth.png")'});
		});
	$("div[class*='Month']")
		.bind('click', function() {
				var parent_cal = $(this).parents('.calendar:first');
				var dateIn = $(this).attr('id').replace('goto','');
				xajax_calendar(parent_cal.attr("id"), dateIn, parent_cal.data('uid'), parent_cal.data('key'));
	});
	/* ENERGYBOX */
	$('tr.energyboxDetailsRow')
		.unbind('.energybox')
		.css({'cursor':'pointer'})
		.bind('mouseenter.energybox', function() {
				$(this).css('background','#bfcd9b');
		})
		.bind('mouseleave.energybox', function() {
				$(this).css('background','#edf2ca');
		})
		.bind('click.energybox', function() {
				var row = $(this).attr('id').replace('Row','');
				if(location.href.match(/id=(205|233)/) || !location.search.match(/id/))
				{
					window.location="/index.php?id=201&food_details=1&dietplan_id="+$("#FoodlogData").data("dietplan_id")+"#anchor_"+row;
				}
				else
				{
					window.location = location.href.replace(/#.*$/g,'') +"&food_details=1&dietplan_id="+$("#FoodlogData").data("dietplan_id")+"#anchor_"+row;
				}
			});
	// Rebind foodlog too - if relevant
	if(typeof rebindlive_foodlog == 'function')
	{
		rebindlive_foodlog();
	}
	$('.click_select').unbind().bind('click',function() {$(this).select();});
	$(".guideBtn").unbind().bind('click',function(){
		xajax_guide_step($(this).attr('id'));
		$("#guideMinimized").hide();
	});
}
jQuery.extend(jQuery.expr[':'], {
    focus: function(e){
        try{ return e == document.activeElement; }
        catch(err){ return false; }
    }
});

