<?xml version="1.0" encoding="utf-8" ?>
<Module>
	<ModulePrefs author="LabPixies" 
	author_email="info@labpixies.com" 
	description="__MSG_description__" 
	thumbnail="http://www.labpixies.com/campaigns/calories/images/thumbnail.jpg" 
	screenshot="http://www.labpixies.com/campaigns/calories/images/screenshot.png"
	title_url="http://www.labpixies.com" 
	title="__MSG_title__" height="220" >
	<Require feature="setprefs" />	
	<Require feature="analytics" /> 	
	<Require feature="views" />
	<Require feature="dynamic-height" />
	<Locale  messages="http://www.labpixies.com/campaigns/calories/i19/all_all.xml"/>
	</ModulePrefs>
	<UserPref name="k1" default_value="" datatype="hidden"/>
	<UserPref name="k2" default_value="" datatype="hidden" />
	<UserPref name="k3" default_value="" datatype="hidden" />
	<UserPref name="breakfast" default_value="" datatype="hidden" />
	<UserPref name="lunch" default_value="" datatype="hidden" />
	<UserPref name="dinner" default_value="" datatype="hidden" />
	<UserPref name="misc" default_value="" datatype="hidden" />
	<UserPref name="calories_quota" default_value="" datatype="hidden"/>
	<UserPref name="calorie_settings" default_value="" datatype="hidden"/>
	<UserPref name="calorie_gadget_settings" default_value="" datatype="hidden"/>
	<UserPref name="first_load" default_value="1" datatype="hidden"/>
	
	<UserPref name="curr_tab" default_value="s" datatype="hidden"/>
	<UserPref name="last_search" default_value="bread" datatype="hidden"/>
	<UserPref name="c1" default_value="" datatype="hidden"/>
	<UserPref name="c2" default_value="" datatype="hidden"/>
	<UserPref name="my_items_count" default_value="0" datatype="hidden"/>
<Content type="html" view="home,profile">
<![CDATA[
<title>Calorie Calculator</title>

<style type="text/css">
* {
    margin:0;
    padding:0;
}

body {
    font-family:arial;
    text-align:center;
}

#main {
    width:245px;
    text-align:left;
    height:168px;
    margin:0px auto;
    margin-top:10px;
    position:relative;
}

#header {
    height:35px;
    margin-bottom:17px;
    margin-left:10px;
    text-align:left;
}

#header_text {
    float:left;
    width:185px;
    color:#fff;
    font-size:12px;
    font-weight:bold;
    line-height:14px;
    padding-top:2px;
}

#header_links {
    float:left;
    font-size:10px;
    font-weight:bold;    
    margin-top:3px;
    text-align:right;
}

#header_links a, #header_links a:visited {
    color:#a8f051;
    text-decoration:none;
}

#header_links a:hover {
    color:#fff;
    text-decoration:underline;
}

#buttons {
    margin-left:10px;
}

.mealbutton {
    width:109px;
    height:13px;
    float:left;
    text-transform:uppercase;
    color:#9de0ff;
    font-size:10px;
    padding-top:37px;
    text-align:center;
    cursor:pointer;
}

.leftcolumn {
    margin-right:10px;
}

.buttonrow {
    margin-bottom:7px;
    height:50px;
}

#daily_use {
    /*color:#004b57;*/
}

#popup {
    padding-bottom:10px;
    padding-top:10px;
    position:absolute;

    top:63px;
    width:228px;
    border:1px solid #ffcf00;
    background:#005d6b;

    text-align:center;
    font-size:12px;
    color:#fff;
}

#popup p {
    margin-bottom:10px;
}

#reset_yes a,#reset_yes a:visited,#reset_no a,#reset_no a:visited {
    color:#005D6B;
    line-height:18px;
    font-weight:bold;
    text-decoration:none;
}

#reset_yes a:hover,#reset_no a:hover {
    text-decoration:none;
}

#reset_yes,#reset_no {
    text-align:center;
    width:68px;
    height:18px;
    float:left;
    display:inline;
    margin-left:31px;
}

</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script src="http://www.google-analytics.com/ga.js" type="text/javascript"></script>
<!-- PUT THIS TAG IN THE head SECTION -->
<script type="text/javascript" src="http://partner.googleadservices.com/gampad/google_service.js">
</script>
<script type="text/javascript">
GS_googleAddAdSenseService("ca-pub-8123415297019784");
GS_googleEnableAllServices();
</script>
<script type="text/javascript">
GA_googleAddSlot("ca-pub-8123415297019784", "calorie_calculator_txt");
</script>
<script type="text/javascript">
GA_googleFetchAds();

</script>
<!-- END OF TAG FOR head SECTION -->

<script type="text/javascript" src="http://www.google-analytics.com/ga.js"></script>

<!--[if IE 6]> 
<script type="text/javascript"> 
		try {//IE fix, causes it to automatically cache background image 
				document.execCommand("BackgroundImageCache", false, true); 
		} 
		catch(e){ 
		} 
</script> 
<![endif]--> 
<script type="text/javascript">	
	var _gadgetID=31;
    var $lp = jQuery.noConflict();
	
	var IMAGES_BASE = "http://cdn.labpixies.com/campaigns/calories/images/";
	var API_URL = "http://lpcaloriesv1.appspot.com/";

	var g_meal_names = { 'breakfast':'Breakfast', 'lunch':'Lunch', 'dinner':'Dinner', 'misc':'Misc' };
	var g_my_food = {};

/*----------------------------------------------------------------------------------------------------*/
var lp_pageTracker = _gat._getTracker("UA-345375-1");
lp_pageTracker._initData();

function lp_trackEvent(eventName, eventLable, eventVar) {
	try {
		//alert(eventName + ' - ' + eventLable);
		lp_pageTracker._trackEvent("Calorie Calculator - V2 - Home",eventName,eventLable,eventVar);
	} catch(ee) {}
}
/*----------------------------------------------------------------------------------------------------*/
	
	var c1 = '';
	var c2 = '';
	
	var LP_MSG_title_used = '__MSG_title_used__';
	var LP_MSG_title_quota = '__MSG_title_quota__';
	var LP_MSG_title_quota_empty = '__MSG_title_quota_empty__';
	
	 var prefs = new _IG_Prefs();

	function init() {

		c1 = prefs.getString('c1');
		c2 = prefs.getString('c2');
		
		
		if ((c1.length == 0) || (c1.length == 0))
		{
			prefs.set('breakfast','',
					'lunch','',
					'dinner','',
					'misc','',
					'calories_quota','',
					'calorie_settings','',
					'calorie_gadget_settings','');
		}
					
	    $lp('#main').css('background-image', 'url('+_IG_GetImageUrl( IMAGES_BASE + 'gadget/background.gif' )+')' );
	    $lp('#reset_yes,#reset_no').css('background-image','url('+_IG_GetImageUrl( IMAGES_BASE + 'canvas/save_settings_button.png' ) +')' );
	    
	    $lp('.mealbutton').each(
		function( n, el ) {
		    el.style.backgroundImage = 'url('+_IG_GetImageUrl(IMAGES_BASE + 'gadget/buttons.png')+')';
		    el.style.backgroundPosition = n * (-109) + 'px 0px';
		    $lp(el).hover( 
				function() {
				    var bg_pos = this.style.backgroundPosition.split(' ')[0];
				    this.style.backgroundPosition = bg_pos + ' 50px';
				},
				function() {
				    var bg_pos = this.style.backgroundPosition.split(' ')[0];
				    this.style.backgroundPosition = bg_pos + ' 0px';
				}
		    );
		}
	    ).click( function() {
			lp_trackEvent('Open Canvas', this.id );
			switchToCanvas( {'meal':this.id} );		
	    });
	    
	    loadMeals();
	    	   
	    if(prefs.getString('first_load')=='1' && prefs.getString('calorie_gadget_settings')!='') {
		doSettingsImport();
	    }
	    
	    var settings = prefs.getString('calorie_settings');
	    if(settings.charAt(0) != '{') { //incase we have old gadget residues, we have to remove them, or the JSON parse will fail 
        prefs.set('calorie_settings','');
      }
      			    
		var calories_quota = prefs.getInt('calories_quota')
		
		if (check_numeric(calories_quota) && calories_quota>0)
		{
			$lp('#daily_quota').html(LP_MSG_title_quota.replace('%NUM%',calories_quota));
		}
		else
		{
			$lp('#daily_quota').html(LP_MSG_title_quota_empty).css('cursor','pointer');
			$lp('#daily_quota').click(function() {lp_trackEvent('Open Canvas', 'Set your daily target amount text');switchToCanvas({'settings':'1'});});	
		}				

	    _IG_AdjustIFrameHeight();
	}
		
	// returns TRUE if the value is numeric, FALSE if not
	function check_numeric(str)
	{
		if (str != parseInt(str,10))
			return false;
		else
			return true;
	}	

	function getItemCalories( item, amount ) {
		if (!item.g)
			return Math.floor(item.c*amount);
			
	    if( item.u == 'gram' ) {
			return Math.floor( (amount/100)*item.c )
	    }
	    else {
			return Math.floor( ((amount*item.g)/100)*item.c )
	    }
	}

	function switchToCanvas( params ) {
	    map = gadgets.views.getSupportedViews();
	    gadgets.views.requestNavigateTo( map['canvas'], params );
	}

	var total_cal;
	function loadMeals() {

	    var sum = 0;
	    for( meal in g_meal_names ) {
    		var m = prefs.getInt(meal);

    		$lp('#'+meal).text(g_meal_names[meal] + ' - ' + m);
    		sum+= m;
		
	    }
		total_cal = sum;
	   
	    $lp('#daily_use').html(LP_MSG_title_used.replace('%NUM%','<span style="color:#004b57">'+sum+'</span>'));
	}

	function onReset() {
	    document.getElementById('popup').style.display = '';
	    document.getElementById('popup').style.left = ($lp("#main").offset().left+9) +'px';
	}
	
	function resetData () {
	    lp_trackEvent('Reset Calories', total_cal);	    
		
		$lp('#daily_use').html(LP_MSG_title_used.replace('%NUM%','<span style="color:#004b57">0</span>'));
	    g_my_food = { 'breakfast':{}, 'lunch':{}, 'dinner':{}, 'misc':{} };

	    for(meal in g_meal_names) 
		{
			prefs.set(meal,0);
			$lp('#'+meal).text(g_meal_names[meal] + ' - 0');			
	    }
		
		reset_my_meals(reset_my_meals_callback);
	}
	
	/*---------------------------------------------------------------------------*/
	function reset_my_meals(callback)
	{
		var url = API_URL + 'reset?user_id='+c2+ 
							'&pwd='+c1+												
							'&callback=?';
		$lp.getJSON(url, callback);	
	}
	/*---------------------------------------------------------------------------*/

	/*---------------------------------------------------------------------------*/		
	function reset_my_meals_callback(data)		
	{
		if (!data)
		{
			lp_trackEvent("DataError","Reset failed. No Data");
			return;
		}
		
		if (data.success)
		{
		
		}
		else
		{
			lp_trackEvent("DataError","Reset failed. success false");
		}	   
	}
	/*---------------------------------------------------------------------------*/
	
	function doSettingsImport() {
	    
	    var str = prefs.getString('calorie_gadget_settings');
	    if (str.length == 0) { return; }
				
	    var settAr = str.split(",");
	    var data = {};
	    data.age = settAr[0];
	    data.male = (settAr[1]=="1");
				
	    if (settAr[2]=="0"){
		data.metric = false;
	    } else if (settAr[2]=="1") {
		data.metric = true;
	    }

	    if (settAr[2]=="0"){
		data.height = settAr[4]+','+settAr[5];
		data.weight = settAr[3];
	    } else {
		data.height = settAr[4];
		data.weight = settAr[3];
	    }
	    data.activity = settAr[6];

	    prefs.set('calorie_settings', lpgadgets.lp.utils.jsonStringify(data) );
	    prefs.set('calorie_gadget_settings', '');
	    prefs.set('first_load','0');

	    if (!data.metric)
	    	data.weight = data.weight/2.2;

	    var height = 0;
	    var split = data.height.split(',');
	    if (!data.metric) {
		var feet = parseInt(split[0]);
		var inches = parseInt(split[1]);
		
		height = ((feet*12) + inches) * 2.54;
	    }else{
		height = parseInt(data.height);
	    }
	    if (height==0 || data.weight==0 || data.age==0) {
		return 0;
	    }
	    
	    //Harris Benedict Formula
	    var result;
	    if (data.male) {
		result = 66.5 + (13.75 * data.weight) + (5.003 * height) - (6.775 * data.age); //Men
	    } else {
		result = 655.1 + (9.563 * data.weight) + (1.850 * height) - (4.676 * data.age); //Women
	    }
	    
	    result = Math.round(result*data.activity);
	    
	    prefs.set('calories_quota',result);
	}

	_IG_RegisterOnloadHandler( init );
	
</script>

<div id="container">
<div id="main">
	<div id="header">
		<div id="header_text">	
			<div id="daily_use"></div>
			<div id="daily_quota">__MSG_title_quota__</div>
		</div>
		<div id="header_links">
			<div><a href="javascript:void(0)" onclick="lp_trackEvent('Open Canvas', 'Settings button');switchToCanvas({'settings':'1'}); return false;">__MSG_settings__</a></div>
			<div><a href="javascript:void(0)" onclick="onReset(); return false;">__MSG_reset__</a></div>
		</div>
	</div>
	<div id="buttons">
		<div class="buttonrow">
			<div class="mealbutton leftcolumn" id="breakfast">__MSG_breakfast__</div>
			<div class="mealbutton" id="lunch">__MSG_lunch__</div>
		</div>
		<div class="buttonrow">
			<div class="mealbutton leftcolumn" id="dinner">__MSG_dinner__</div>
			<div class="mealbutton" id="misc">__MSG_misc__</div>
		</div>
	</div>

</div>
</div>

<div id="popup" style="display:none;">
	<p style="margin-left:10px;margin-right:10px;">
		__MSG_reset_sure__
	</p>
	<div id="reset_yes" onclick="resetData(); $lp('#popup').hide();" style="cursor:pointer">
		<a href="javascript:void(0);" onclick="return false;">__MSG_yes__</a>
	</div>
	<div id="reset_no" onclick="$lp('#popup').hide();" style="cursor:pointer">
		<a href="javascript:void(0);" onclick="return false;">__MSG_no__</a>
	</div>
</div>


<div style="margin-top:5px;">
	<script type="text/javascript">
		GA_googleFillSlot("calorie_calculator_txt");
	</script>
</div>

<div>
	<script type="text/javascript">
    var mMENU = _IG_GetCachedUrl("http://cdn.labpixies.com/infra/js/lp_footer.js");
    document.write('<scr'+'ipt type="text/javascript" src="'+mMENU+'"></scr'+'ipt>');
    </script>
</div>

<script type="text/javascript">
_IG_Analytics("UA-345375-1", "/calories_profile");
</script>
<iframe width="1" height="1" style="width:1px; height:1px; overflow:hidden; position:absolute; visibility:hidden;" src="http://static.labpixies.com/campaigns/calories/analytics.html"></iframe>
]]>
</Content>
<Content type="html" view="canvas">
<![CDATA[

<title>Calorie Calculator</title>

<style type="text/css">
* {
    padding:0;
    margin:0;
}

#container {
    position:relative;

}

#main {
    width:465px;    
	height:460px;
    text-align:left;
    overflow:hidden;
}

#error {
    width:465px;    
	height:460px;
    text-align:center;
    color:#363636;
    font-size:11px;
    line-height:15px;
}

#error img {
    margin-top:10px;
    margin-bottom:10px;
}

#padding-replacer {
    margin-top:3px;
    margin-left:9px;
    margin-right:10px;
}

.mealbutton {
    width:100px;
    height:13px;
    float:left;
    text-transform:uppercase;
    color:#9de0ff;
    font-size:10px;
    padding-top:37px;
    text-align:center;
    cursor:pointer;
}

.notlast {
    margin-right:15px;
}

#header {
    height:35px;
    margin-bottom:17px;
}

#header_text {
    float:left;
    width:315px;
    font-size:14px;
    color:#fff;
    line-height:15px;
    font-weight:bold;
}

#header_links {
    float:left;
    font-size:11px;
    font-weight:bold;    
    margin-top:3px;
}

#header_links div {
    text-align:center;
    width:62px;
    height:16px;
    float:left;
    cursor:pointer;
    line-height:16px;
}

#header_links a {
    color:#59a400;
    text-decoration:none;
    font-weight:bold;
}

#daily_use {
 
}

#search {
    border:0;
    width:110px;
    height:18px;
	line-height:18px;
    color:#434343;
    font-size:12px;
    float:right;
    margin-right:15px;
    margin-top:12px;
}

#list_title {
    color:#ffc700;
    font-size:18px;
    font-weight:bold;
    margin-left:6px;
    margin-top:5px;
    height:30px;
    float:left;
}

#list_letters {
    margin-left:7px;
    cursor:default;
    clear:both;
}

.active_letter, .active_letter:visited{
    color:#2f6c91;
    background:#ffc700;
    text-decoration:none;
    font-size:12px;
    font-weight:bold;
    padding-top:2px;
    padding-bottom:2px;
    padding-left:1px;
    padding-right:1px;
}

.letter, .letter:visited {
    text-decoration:none;
    font-size:12px;
    font-weight:bold;
    color:#fff;
    padding-top:2px;
    padding-bottom:2px;
    padding-left:1px;
    padding-right:1px;
}

.letter:hover {
    text-decoration:underline;
}

#buttons {
    height:60px;
}

#food_table {
    overflow:auto;
    height:226px;
    position:relative;
}

#food_table table {
    width:100%;
}

#food_table td {
    color:#434343;
    border-bottom:1px solid #d7e5ed;
    height:24px;
    font-size:11px;
    line-height:24px;
}

.downbtn, .upbtn {
    width:11px;
    height:8px;
    line-height:8px;
    font-size:1px;
    cursor:pointer;
}

.upbtn
{
	margin-top:4px;
}

.downbtn {
    background-position:11px 0px;
}

td.sizer {
    width:11px;
    height:24px;
	vertical-align:top;
}

td.foodname {
    width:221px;
    cursor:pointer;
}

#food_table tr {
    background:#ffffff;
}

#food_table tr.over {
    background:#eaf2f6;
}

#food_table tr.selected {

}

#food_table tr.over td.foodname {
    color:#62af06;
}

#food_table tr.over td.unit,#food_table tr.over td.calories {
    color:#000;
}

table.headers td.foodname {    
    padding-left:22px;
}

td.plus {   
	width:20px;   
}


td.unit {    	
	width:90px;
    cursor:default;
	vertical-align:top;
}

td.unit_header {    	
	width:90px;
    cursor:default;	
}

td.icon {    
	width:20px;    
	vertical-align:top;
}

table.headers {    
	height: 24px;
}

table.headers td {
    font-size:12px;
    font-weight:bold;
}

td.calories {
    text-align:center;
    width:61px;
	vertical-align:top;
}
td.calories_header {
    text-align:center;
    width:61px;
}
td.icon {
    text-align:center; 
}

#panel {
    background:#004B57;
    width:446px;
    position:absolute;
    height:50px;
    bottom:0px;
    overflow:hidden;
	top: 114px;	
	z-index:10;
}

#panel_summary {
    padding-left:10px;
    clear:both;
    font-size:11px;
    color:#fff;    
    line-height:15px;
	padding-top:2px;
}

#panel_title {
    font-size:14px;
    font-weight:bold;
    color:#ffc700;
    float:left;
    display:inline;
    margin-left:10px;
    margin-top:5px;
    width:280px;
    cursor:pointer;
}

#panel_expand {
    float:right;
    display:inline;    
    margin-top:5px;
    margin-right:5px;
    cursor:pointer;
}
#panel_expand a,#panel_expand a:visited {
    font-size:11px;
    font-weight:bold;
    color:#ffc700;
    text-decoration:none;
}
#panel_expand a:hover {
    text-decoration:underline;
}

#panel_expand_button {
    float:right;
    display:inline;
    width:12px;
    height:12px;
    line-height:12px;
    font-size:0px;
    margin-top:5px;
    margin-right:10px;
    cursor:pointer;
	background-position: 12px 0px;
}

#panel_list {
    margin-left:10px;
    list-style-type:none;
}

#panel_list li {
    line-height:24px;
    color:#fff;
    font-size:12px;
}

#panel_list .del {
    font-weight:bold;
    color:#ffc700;
    cursor:pointer;
    background-position:-146px 0px;
    background-repeat:no-repeat;
    width:15px;
    float:left;
    display:inline;
    height:14px;
	margin-top:8px;
	overflow:hidden;
}

#disclaimer, #disclaimer:visited {
    font-size:10px;
    text-decoration:none;
    color:#000;
}

#disclaimer:hover {
    text-decoration:underline;
}

tr.selected td.plus {
    background-position:-123px 5px;
    width:20px;
    background-repeat:no-repeat;
}

.image_plus
{
	background-position:-104px 5px;
	background-repeat:no-repeat;	
}

#loading {
    position:absolute;
    left:215px;
    top:80px;
    display:none;
}

#noresults {
    margin-top:75px;
    display:none;
    font-size:12px;
    text-align:center;
	padding: 0 10px 0 10px;
}

.right_icon
{
	width:14px;
	height:14px;
	overflow:hidden;
	margin-top:4px;
}

.top_btn
{
	cursor:pointer;
	float:left;
	padding-top:13px;
	padding-left:10px;	
	color:#004B57;	
	margin-bottom:8px;
}

.top_btn_bg_left
{				
	padding-left:7px;
	height:16px;
	color:#004B57;
	font-size:11px;
	font-weight:bold;	
}

.top_btn_bg_right
{
	background-position: top right;
	width:7px;
	height:16px;
}

#add_my_item_btn
{
	display:none;				
	cursor:pointer;
	margin: 3px 0px 3px 20px;
}

.add_btn_left
{
	padding-left: 20px;
	font-size:12px;
	fonr-weight:bold;
	color:#FFFFFF;
	height:18px;
	line-height:18px;
}

.add_btn_right
{
	background-position:-192px 0px;
	width:8px;
}			

#save_my_item_btn
{
	width:14px;
	height:14px;
	background-position: -56px 0px;
	overflow:hidden;
	cursor:pointer;
	margin-top:5px;
}

.add_item_input
{
	font-size:12px;
	height:18px;
}

.blue_btn
{
	cursor:pointer;	
	font-size:11px;
	font-weight:bold;
	color:#FFFFFF;
	height:16px;
}

.blue_btn_left
{
	padding-left:7px;
}

.blue_btn_right
{
	width:7px;
	background-position:right top;
}

.style1 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
}
.style2 {
	color: #0097b0
}

#popup {
    position:absolute;
    top:0px;
    left:0px;
    display:none;
    width:510px;
    z-index:10;
}

#popup_inner {
    background:#005D6B;
    border:1px solid #FFCF00;
    width:320px;
    left:75px;
    top:100px;
    position:absolute;
    padding-bottom:10px;
    color:#fff;
    font-size:12px;
    text-align:left;	
}

#popup_title {
    font-size:12px;
    font-weight:bold;
    color:#fff;
    background:#87CA1A;
    padding:5px;
    padding-left:10px;
    margin-bottom:10px;
}

#popup_close {
    padding-right:10px;
    margin-top:3px;
    margin-bottom:20px;
    position:absolute;
    top:1px;
    left:280px;
}

#popup_close a {
    color:#005D6B;
}

#popup a, #popup a:visited {
   text-decoration:none;
}

#metric a { 
   color:#FFC700;
 
}

#popup a:hover {
    text-decoration:underline;
}

#popup .text {
    width:50px;
    padding-top:1px;
}

#metric {
    margin-top:5px;
    font-size:11px;
    margin-bottom:10px;
}

#settings_save {
    text-align:center;
    width:68px;
    height:18px;
    margin:0 auto;
}

#settings_save a, #settings_save a:visited, #reset_yes a,#reset_yes a:visited,#reset_no a,#reset_no a:visited {
    color:#005D6B;
    line-height:18px;
    font-weight:bold;
}

#settings_save a:hover,#reset_yes a:hover,#reset_no a:hover {
    text-decoration:none;
}

#popup_reset {
    display:none;
    text-align:center;
}

#reset_yes,#reset_no {
    text-align:center;
    width:68px;
    height:18px;
    float:left;
    display:inline;
    margin-left:36px;
	cursor:pointer;
	line-height:18px;
}

.settings_row
{
	height:26px;
}

</style>

<script type="text/javascript" src="http://www.google-analytics.com/ga.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>

<!-- PUT THIS TAG IN THE head SECTION -->
<script type="text/javascript" src="http://partner.googleadservices.com/gampad/google_service.js">
</script>
<script type="text/javascript">
  GS_googleAddAdSenseService("ca-pub-8123415297019784");
  GS_googleEnableAllServices();
</script>
<script type="text/javascript">
  GA_googleAddSlot("ca-pub-8123415297019784", "calories_leaderboard_top");
  
  GA_googleAddSlot("ca-pub-8123415297019784", "calories_custom_1");
  GA_googleAddSlot("ca-pub-8123415297019784", "calories_custom_2");
  GA_googleAddSlot("ca-pub-8123415297019784", "calories_box");
</script>
<script type="text/javascript">
  GA_googleFetchAds();
</script>
<!-- END OF TAG FOR head SECTION -->

<!--[if IE 6]> 
<script type="text/javascript"> 
		try {//IE fix, causes it to automatically cache background image 
				document.execCommand("BackgroundImageCache", false, true); 
		} 
		catch(e){ 
		} 
</script> 
<![endif]--> 
<script type="text/javascript">
	var _gadgetID=31;
	var $lp = jQuery.noConflict();
	var prefs = new _IG_Prefs();
			
	var IMAGES_BASE = 'http://www.labpixies.com/campaigns/calories/images/';	
	var API_URL = "http://lpcaloriesv1.appspot.com/";

	//holds the data of selected items per meal. each meal is an object of '_id : {attributes}' nodes
	var g_my_food = { 'breakfast':{}, 'lunch':{}, 'dinner':{}, 'misc':{} };
	var g_my_amounts = { 'breakfast':{}, 'lunch':{}, 'dinner':{}, 'misc':{} };
	
	var g_meal_names = { 'breakfast':'__MSG_breakfast__', 'lunch':'__MSG_lunch__', 'dinner':'__MSG_dinner__', 'misc':'__MSG_misc__' };
	var g_current_meal = 'breakfast';
	//holds the items that are currently being displayed for the user to choose from, same structure as g_my_food
	var g_current_food_list; 
	var g_is_metric = false;
	var g_data_lock = false;
	var g_is_panel_opened = false;
	var g_last_search = '';
	
	var g_my_items = null;
	var g_recent_items = null;
	var g_search_items = null;
	
	var MAX_ITEMS = 100;
	var g_my_items_count;	
	
	var g_meals_index = [];
	g_meals_index[0] = 'breakfast';
	g_meals_index[1] = 'lunch';
	g_meals_index[2] = 'dinner';
	g_meals_index[3] = 'misc';
		
/*----------------------------------------------------------------------------------------------------*/
var lp_pageTracker = _gat._getTracker("UA-345375-1");
lp_pageTracker._initData();

function lp_trackEvent(eventName, eventLable, eventVar) {
	try {
		//alert(eventName + ' - ' + eventLable);
		lp_pageTracker._trackEvent("Calorie Calculator - V2 - Canvas",eventName,eventLable,eventVar);
	} catch(ee) {}
}
/*----------------------------------------------------------------------------------------------------*/
	
	function get_img_url(src)
	{
		return _IG_GetImageUrl(IMAGES_BASE + src);
		//return IMAGES_BASE + src;
	}
	
	// adds a new css class definition to the document, used for assigning classes for cached images
	function addCssClass(classname, rule) {
	    var ssheet=(document.styleSheets.length==0)? document.createStyleSheet(): document.styleSheets[0];
	    if(ssheet.insertRule){
		rulecount=ssheet.cssRules.length;
		fullrule='.'+classname+"{"+ rule +"}";	
		ssheet.insertRule(fullrule, rulecount++ );
	    }else if(document.styleSheets[0].addRule){
		rulecount=ssheet.rules.length;
		ssheet.addRule('.'+classname, rule, rulecount++);	
	    }
	}

	function loadImages() {	    
		addCssClass('image_plus', 'background:transparent url(' + get_img_url('canvas/icons_sprite.png')+');' );
	    addCssClass('image_arrows', 'background:transparent url('+get_img_url('canvas/change_unit_arrows.png')+');' );
		
		$lp('#main').css('background-image', 'url('+get_img_url('canvas/background_new_2.png') +')' );
	    $lp('#panel_expand_button').css('background-image', 'url('+get_img_url('canvas/expand_closelist_buttons_new.png') +')' );

	    $lp('#settings_save,#reset_yes,#reset_no').css('background-image','url('+get_img_url('canvas/save_settings_button.png') +')' );

	    $lp('#loading').html('<img src="'+get_img_url('canvas/load.gif') +'" />');
		
		$lp('.add_btn_bg').css('background-image', 'url('+ get_img_url('canvas/add_item_sprite.png') + ')' );
		$lp('.btn_sprite').css('background-image', 'url('+ get_img_url('canvas/icons_sprite.png') + ')' );
		$lp('#ad_unit').css('background-image', 'url('+ _IG_GetImageUrl('http://cdn.labpixies.com/infra/images/ad_unit_bg_760.png') + ')' );
		
		$lp('.blue_btn').css('background-image', 'url('+ get_img_url('canvas/blue_btn.png') + ')' );
		
		$lp('#help_add_to_meal').attr('src',get_img_url('canvas/add_to_meal.png'));
		$lp('#help_add_to_fav').attr('src',get_img_url('canvas/add_to_fav.png'));
		$lp('#help_add_new').attr('src',get_img_url('canvas/add_new.png'));

		$lp('.blue_btn').css('background-image', 'url('+ get_img_url('canvas/blue_btn.png') + ')' );
		
		loadGui();
	}
	
	// set various gui behavoir
	function loadGui()
	{
		// top tabs : my, recent, search
		$lp('.top_btn').hover(
			function()
			{			
				if ($lp('.top_btn_bg_left',this).css('background-image').length<10) 
					$lp(this).css('text-decoration','underline');
			},
			function()
			{
				$lp(this).css('text-decoration','none');
			}
		);

		// add new item btn
		$lp('#add_my_item_btn').click(function() {
										$lp('#add_my_item_btn').hide();
										$lp('#custom_item_form').show();
										$lp('#custom_name').focus();
										});
		
		$lp('#add_my_item_btn').hover(
			function()
			{							
				$lp('.add_btn_left', this).css('background-position','0px -18px');
				$lp('.add_btn_right', this).css('background-position','-192px -18px');
			},
			function()
			{
				$lp('.add_btn_left', this).css('background-position','0px 0px');
				$lp('.add_btn_right', this).css('background-position','-192px 0px');
			}
		);
		
		// save custom item button
		$lp('#save_my_item_btn').click(function() {
										add_item($lp('#custom_name').val(), $lp('#custom_unit').val(), $lp('#custom_cal').val(), add_item_callback)										
										});
										
		$lp('#save_my_item_btn').hover(
			function()
			{
				$lp(this).css('background-position','-56px -14px');
			},
			function()
			{
				$lp(this).css('background-position','-56px 0px');
			}
		);
		
		// help btn
		$lp('#help_btn').click(function() {
								if ($lp('#help_text').css('display') == 'none')
									lp_trackEvent('Display How to Use Text', 'How to use button');
								$lp('#help_text').toggle();
								_IG_AdjustIFrameHeight();
							  });
							  
		// disclaimer btn
		$lp('#disc_btn').click(function() {
								lp_trackEvent('View Disclaimer', 'Disclaimer button');
								window.open('http://www.labpixies.com/gadget_page.php?id=31',
								'mywindow','location=1,status=1,scrollbars=1,menubar=1');
							  });					  
		
		
		$lp('#user_settings_c_text').html( ('__MSG_custom_cal__').replace('%BR%','</br>'));
	}
	
	// set the currnet top button: my items / search items/ recent itmes
	var g_curr_tab = '';
	function set_top_btn(btn_pressed, no_search)
	{
		var on_item;
		
		if (btn_pressed == g_curr_tab) return;
		
		g_curr_tab = btn_pressed;
						
		switch (btn_pressed)
		{
			// my items
			case 'm':
				on_item = $lp('#my_items_btn');
				$lp('#noresults').hide();
				$lp('#loading').show();
				clear_after_custom_item();	
				// if local dataset is null - go to server for data
				if (!g_my_items)
				{
					$lp('#food_table tr').remove();	
					get_custom_items('', get_custom_items_callback)					
				}
				// use local dataset
				else
				{					
					$lp('#food_table tr').remove();	
					get_custom_items_callback(g_my_items);
				}												
				$lp('#food_table').css('height','190px');
			break;
			
			// recent items
			case 'r':
				on_item = $lp('#recent_items_btn');
				$lp('#noresults').hide();
				$lp('#loading').show();
				$lp('#add_my_item_btn').hide();
				$lp('#custom_item_form').hide();
				
				if (!g_recent_items)
				{
					get_recent_items(get_recent_items_callback);
					$lp('#food_table tr').remove();
				}				
				else
				{
					$lp('#food_table tr').remove();	
					get_recent_items_callback(g_recent_items);
				}												
				$lp('#food_table').css('height','213px');
			break;
			
			// search items
			case 's':
				on_item = $lp('#search_items_btn');				
				$lp('#add_my_item_btn').hide();
				$lp('#custom_item_form').hide();				
				$lp('#food_table tr').remove();
								
				if (!g_search_items)
				{
					if (g_last_search.length > 0)
					{						
						$lp('#noresults').hide();
						$lp('#loading').show();						
						if (!no_search)
						{
							$lp('#search').val(g_last_search);
							get_search_items(g_last_search, get_search_items_callback);
						}
					}
					else
					{					
						$lp('#noresults').show();
						$lp('#noresults').text('__MSG_first_search__');
					}
				}
				else
				{					
					if (!no_search)
					{						
						get_search_items_callback(g_search_items);
					}
					else
					{					
						$lp('#noresults').show();
						$lp('#noresults').text('__MSG_first_search__');
					}					
				}
								
				$lp('#food_table').css('height','213px');
				$lp('#search').focus();
			break;		
		}
		
		$lp('.top_btn_bg_left').css('color','#004B57');		
		$lp('.top_btn_bg').css('background-image','');			
		$lp('.top_btn').css('text-decoration','none');		
		
		$lp('.top_btn_bg_left', on_item).css('color','#FFFFFF');		
		$lp('.top_btn_bg', on_item).css('background-image','url('+ get_img_url('canvas/menu_buttons_back.png') + ')' );			
		
		prefs.set('curr_tab',btn_pressed);
	}

	function loadButtons() {
	    $lp('.mealbutton').each(
			function( n, el ) {
			    el.style.backgroundImage = 'url('+get_img_url('canvas/buttons.png')+')';
			    el.style.backgroundPosition = n * (-100) + 'px 0px';
			}
		    ).click(
				function() {		   
				    $lp('.mealbutton').each(
						function( n, el ) {
						    var bg_pos = el.style.backgroundPosition.split(' ')[0];
						    el.style.backgroundPosition = bg_pos + ' 0px';
						}
				    );
				    var bg_pos = this.style.backgroundPosition.split(' ')[0];
				    this.style.backgroundPosition = bg_pos + ' 50px';

				    g_current_meal = this.id;
				    updatePanel();
				    				
				    $lp('.selected').removeClass('selected');		    
					$lp('.image_plus:not(.right_icon)').removeClass('image_plus');								
					$lp('.del').addClass('image_plus');								
				    $lp('.vmark').removeClass('vmark').css('background-position','');
				    for( id in g_my_food[g_current_meal] ) 
					{
						var tr = $lp('#'+id).addClass('selected');
						$lp('td.plus',tr).addClass('vmark').addClass('image_plus').css('background-position','-123px 5px');
				    }						
				}
			);

	   
	    $lp('#header_links div').each(
		function( n, el ) {
		    el.style.backgroundImage = 'url('+get_img_url('canvas/settings_reset_button.gif')+')';
		    $lp(el).hover(
			function() {
			    this.style.backgroundPosition = '0 16px';
			},
			function() {
			    this.style.backgroundPosition = '0 0';
			}
		    );
		}
	    );

	}

	var g_is_fetching = false;	

	function setupSearch() {		
	    $lp('#search').keyup(
			function(event) {
				//enter
			    if(event.keyCode == 13 ) 
				{
					var search_term = this.value.replace('&','');
					$lp('#search').val(search_term);
					if (search_term.length == 0)
					{						
						return;
					}
				
					set_top_btn('s', true);				
					$lp('#food_table tr').remove();
					$lp('#noresults').hide();
					$lp('#loading').show();
					
					lp_trackEvent('Search Items', search_term);
					get_search_items(search_term, get_search_items_callback);
			    }
			});	
	}

	function getItemCalories( item, amount ) 
	{	
		if (!item.g)		
		{		
			return Math.floor(item.c*amount);		
		}
	
	    if( item.u == 'gram' ) 
		{		
			return Math.floor( (amount/100)*item.c )
	    }
	    else 
		{					
			if( g_is_metric && (item.u == 'oz') && (item.g) ) 
			{			    
				return Math.floor( (amount/100)*item.c )		
			}
			else
			{
				return Math.floor( ((amount*item.g)/100)*item.c );
			}						
		}
	}			  

	function upArrowHover() {
	    this.style.backgroundPosition = '0px 8px';
	}

	function upArrowHoverStop() {
	    this.style.backgroundPosition = '0px 0px';
	}

	function upArrowClick() {
	    var k = eval($lp('span.amount', this.parentNode.parentNode).html());
	    var unit = g_current_food_list[this.parentNode.parentNode.id].u;
	    if( unit == 'gram' ) 
		{
			k+=10;
			$lp('span.amount', this.parentNode.parentNode).html(k);
	    }
	    else 
		{
			if(k>=1) 
			{
				k++;
				$lp('span.amount', this.parentNode.parentNode).html(k);
			}
			else if(k<0.5) 
			{
				k*=2;
				$lp('span.amount', this.parentNode.parentNode).html('1/'+1/k);
			}
			else 
			{
				k=1;
				$lp('span.amount', this.parentNode.parentNode).html('1');
			}
	    }
	    var item = g_current_food_list[this.parentNode.parentNode.id];
	    $lp('.calories',this.parentNode.parentNode).text( getItemCalories(item, k) );

		// if the item is already selected
	    if( $lp(this.parentNode.parentNode).hasClass('selected') ) 		
		{ 
			addItem( g_current_meal, this.parentNode.parentNode.id, k ); // update the amount
	    }
	}

	function downArrowHover() {
	    this.style.backgroundPosition = '11px 8px';
	}
	
	function downArrowHoverStop() {
	    this.style.backgroundPosition = '11px 0px';
	}

	function downArrowClick() {
	    var k = eval($lp('span.amount', this.parentNode.parentNode).html());
	    var unit = g_current_food_list[this.parentNode.parentNode.id].u;
	    if( unit == 'gram') 
		{
			if(k>10) 
			{
				k-=10;
				$lp('span.amount', this.parentNode.parentNode).html(k);
			}
	    }
	    else 
		{
			if(k>1) 
			{
				k--;
				$lp('span.amount', this.parentNode.parentNode).html(k);
			}
			else if (k>0.1) 
			{
				k/=2;
				$lp('span.amount', this.parentNode.parentNode).html('1/'+1/k);
			}
	    }

	    var item = g_current_food_list[this.parentNode.parentNode.id];
		
	    $lp('.calories',this.parentNode.parentNode).text( getItemCalories(item, k) );

	    if( $lp(this.parentNode.parentNode).hasClass('selected') ) { // if the item is already selected
		addItem( g_current_meal, this.parentNode.parentNode.id, k ); // update the amount
	    }
	}
	
	function parseFoodJson(data, is_top) {
		var is_empty = true;
		
	    var table = document.getElementById('food_tbody');
	   				
		var sorted_items = null;
		
		switch (g_curr_tab)
		{
			case 'm':				
				sorted_items = sort_json_items(data, true);
				if(is_top)
				{
					var tmp_id = sorted_items[0].id;				
					g_current_food_list[tmp_id] = sorted_items[0];
				}
				else
				{
					//g_my_items_count = 0;
					g_current_food_list = data.items;
				}
			break;
			
			case 'r':
				sorted_items = sort_json_items(data, true);				
				g_current_food_list = data.items;
			break;
			
			case 's':
				sorted_items = sort_json_items(data, false);				
				g_current_food_list = data.items;
			break;
		}
			    
		for(var i=0;i<sorted_items.length;i++) {
			id = sorted_items[i].id;
			if( id == '_0' ) continue;
			is_empty = false;
									
			//the following creates the row in the food table for an item
			var tr = document.createElement('tr');
			tr.id = id;			

			var plus = document.createElement('td');
			plus.className = 'plus';
			plus.innerHTML = '&nbsp;';			
			tr.appendChild(plus);

			var foodname = document.createElement('td');
			foodname.className = 'foodname';

			var name = data.items[id].n;	
			
			name = name.replace(/&/g,'&amp;').replace(/'/g,"&#39;").replace(/"/g,'&quot;');
			foodname.innerHTML = name;

			tr.appendChild(foodname);

			
			var sizer = document.createElement('td');
			sizer.className = 'sizer';			
			
			//the "increase quantity" button
			var upbtn = document.createElement('div');
			upbtn.className = 'upbtn image_arrows';
			upbtn.onmouseover = upArrowHover;
			upbtn.onmouseout = upArrowHoverStop;
			upbtn.onclick = upArrowClick;
			sizer.appendChild(upbtn);

			//the "decrease quantity" button
			var downbtn = document.createElement('div');
			downbtn.className = 'downbtn image_arrows';
			downbtn.onmouseover = downArrowHover;
			downbtn.onmouseout = downArrowHoverStop;
			downbtn.onclick = downArrowClick;
			sizer.appendChild(downbtn);

			tr.appendChild(sizer);
			
			var initial_amount = 1;
			if( typeof g_my_food[g_current_meal][id] != 'undefined' ) {
			    initial_amount = g_my_amounts[g_current_meal][id];
			}

			var cals;
			var unit;
			
			if( g_is_metric && (data.items[id].u == 'oz' || data.items[id].u == 'gram') && (data.items[id].g) ) 
			{
			    data.items[id].g = 10;
			    data.items[id].u = 'gram';
			    if( initial_amount == 1 ) initial_amount = 10;
			}
			
			if( !g_is_metric && (data.items[id].u == 'oz' || data.items[id].u == 'gram') && (data.items[id].g) ) 
			{
			    data.items[id].g = 28;
			    data.items[id].u = 'oz';
			    if( initial_amount == 10 ) initial_amount = 1;
			}
			
			cals = getItemCalories(data.items[id],initial_amount);
					
			var unit_td = document.createElement('td');
			unit_td.className = 'unit';
			
			var amount_span = document.createElement('span');
			if(initial_amount < 1)
			    amount_span.innerHTML = '1/'+1/initial_amount;
			else
			    amount_span.innerHTML = initial_amount;

			amount_span.className = 'amount';
			unit_td.appendChild(amount_span);

			var unit_name = data.items[id].u;
			if( unit_name.length >= 16 ) {
			    unit_name = unit_name.substring(0,13)+'...';
			    unit_td.title = data.items[id].u;
			}

			unit_td.innerHTML += ' '+unit_name;
			tr.appendChild(unit_td);

			var calories_td = document.createElement('td');
			calories_td.className = 'calories';
			
			calories_td.innerHTML = cals;
			tr.appendChild(calories_td);
			
			var icon_td = document.createElement('td');
			icon_td.className = 'icon';
									
			switch (g_curr_tab)
			{
				case 'm':
					//if(!is_top)
					//	g_my_items_count++;
					icon_td.innerHTML = '<div class="right_icon" style=""></div>';					
				break;				
				
				case 'r':										
					// custom item
					if (!id.match('cid'))				
					{
						// show custom item icon
						icon_td.innerHTML = '<div title="__MSG_tl_custom_item__" class="right_icon image_plus" style="background-position:0px 0px;"></div>';
					}
					// db item
					else
					{		
						var is_fav = data.items[id].f;
						// show fav icon
						if (is_fav)
							icon_td.innerHTML = '<div title="__MSG_tl_added_item__" class="right_icon image_plus" style="background-position:-41px 0px;"></div>';
						// show no icon
						else
							icon_td.innerHTML = '<div class="right_icon image_plus" style="background-position:-86px -14px;"></div>';
					}
				break;
				
				
				case 's':		
					// custom item
					if (!id.match('cid'))				
					{
						// show custom item icon
						icon_td.innerHTML = '<div title="__MSG_tl_custom_item__" class="right_icon image_plus" style="background-position:0px 0px;"></div>';
					}
					// db item
					else
					{		
						var is_fav = data.items[id].f;
						// show fav icon
						if (is_fav)
							icon_td.innerHTML = '<div title="__MSG_tl_added_item__" class="right_icon image_plus" style="background-position:-41px 0px;"></div>';
						// show no icon
						else
							icon_td.innerHTML = '<div class="right_icon image_plus" style="background-position:-86px -14px;"></div>';
					}
				break;
			}		
									
			tr.appendChild(icon_td);
						
			tr.onmouseover = onItemStartHover;
			tr.onmouseout = onItemStopHover;
			
			foodname.onclick = onItemClick;
			plus.onclick = onItemClick;
			plus.title = '__MSG_tl_meal_item__';
			
			if( id in g_my_food[g_current_meal] ) {
			    tr.className = 'selected';
			    plus.className = 'plus vmark image_plus';
				plus.title = '__MSG_tl_meal_added_item__';
			}
												
			if (is_top)
			{			
				$lp('#food_tbody').prepend(tr);
			}
			else
			{				
				table.appendChild(tr);
			}
	    }
				
		if (is_empty)
		{
			var no_result_txt = '';
			switch (g_curr_tab)
			{
				case 'm':
					no_result_txt = ('__MSG_no_result_my__').replace("%BR%",'<br/>');
				break;
				
				case 'r':
					no_result_txt = '__MSG_no_result_recent__';
				break;
			
				case 's':	
					no_result_txt = ('__MSG_no_result_search__').replace("%ITEM%",$lp('#search').val());
				break;
			}
			
			g_is_fetching = false;
			$lp('#noresults').html(no_result_txt);
			$lp('#noresults').show();
			$lp('#loading').hide();
			return;
		}
		
	    $lp('#loading').hide();
	    g_is_fetching = false;

	    document.getElementById('food_table').scrollTop=0;
	}
	
	function onItemStartHover() {	
		var item_id = this.id;				
		
	    $lp(this).addClass('over');
	    $lp('td.plus', this).addClass('image_plus').css('background-color','#eaf2f6');	
		$lp('td.plus:not(.vmark)', this).css('background-position','-104px 5px');		

		switch (g_curr_tab)
		{
			case 'm':
				$lp('td.icon', this).css({'background-color':'#eaf2f6','cursor':'pointer'});	    
				$lp('.right_icon', this).addClass('image_plus');				
			
				$lp('.right_icon', this).css('background-position','-70px 0px').attr('title','__MSG_tl_del_item__');					
				// if custom item
				if (!item_id.match('cid'))
					$lp('td.icon', this).click(function(){confirm_delete_item(item_id);});		
				else
					$lp('td.icon', this).click(function(){confirm_delete_fav_item(item_id);});								
				
			break;
			
			case 's':				
				$lp('td.icon', this).css('background-color','#eaf2f6');	   			
				$lp('td.image_plus:not(.vmark)', this).css('cursor','pointer');	
				
				// if custom item - display icon
				if (!item_id.match('cid'))
				{									
					$lp('.right_icon', this).css('background-position','-14px 0px').attr('title','__MSG_tl_custom_item__');									
				}
				// if db icon - display fav icon
				else
				{							
					var is_fav = g_current_food_list[item_id].f;	
					$lp('td.icon', this).css('cursor','pointer');						
					
					if (is_fav)
					{
						// display "delete from fav" icon
						$lp('.right_icon', this).css('background-position','-28px -14px').attr('title','__MSG_tl_del_item__');
						$lp('.right_icon', this).click(function() {delete_fav_item(item_id, delete_fav_item_callback);});
					}
					else
					{
						// display "add to fav" icon
						$lp('.right_icon', this).css('background-position','-28px 0px').attr('title','__MSG_tl_add_item__');
						$lp('.right_icon', this).click(function() {set_fav_item(item_id, set_fav_item_callback);});
					}					
				}								
			break;
			
			case 'r':				
				$lp('td.icon', this).css('background-color','#eaf2f6');	   			
				$lp('td.image_plus:not(.vmark)', this).css('cursor','pointer');	
				
				// if custom item - display icon
				if (!item_id.match('cid'))
				{									
					$lp('.right_icon', this).css('background-position','-14px 0px').attr('title','__MSG_tl_custom_item__');									
				}
				// if db icon - display fav icon
				else
				{							
					var is_fav = g_current_food_list[item_id].f;	
					$lp('td.icon', this).css('cursor','pointer');						
					
					if (is_fav)
					{
						// display "delete from fav" icon
						$lp('.right_icon', this).css('background-position','-28px -14px').attr('title','__MSG_tl_del_item__');
						$lp('.right_icon', this).click(function() {delete_fav_item(item_id, delete_fav_item_callback);});
					}
					else
					{
						// display "add to fav" icon
						$lp('.right_icon', this).css('background-position','-28px 0px').attr('title','__MSG_tl_add_item__');
						$lp('.right_icon', this).click(function() {set_fav_item(item_id, set_fav_item_callback);});
					}					
				}								
			break;
		}		
	}

	function onItemStopHover() {		
		var item_id = this.id;		
	
	    if( $lp(this).hasClass('over') ) {
			$lp(this).removeClass('over');
	    }

	    $lp('.vmark',this).css('background-color','');
	    $lp('td.plus:not(.vmark)', this).removeClass('image_plus').css('background-color','');
		$lp('td.icon', this).css('cursor','default');	  
		
		switch (g_curr_tab)
		{
			case 'm':
				$lp('td.icon', this).css('background-color','');	    				
				$lp('.right_icon', this).removeClass('image_plus');	
				$lp('td.icon', this).unbind('click');
			break;
			
			case 's':
				$lp('td.icon', this).css('background-color','');	    				
				
				// if custom item - display grey icon
				if (!item_id.match('cid'))
				{
					$lp('.right_icon', this).css('background-position','0px 0px');
				}
				// if db item
				else
				{						
					var is_fav = g_current_food_list[item_id].f;	
					if (is_fav)
					{
						$lp('.right_icon', this).css('background-position','-42px 0px');
					}
					else
					{
						$lp('.right_icon', this).css('background-position','-86px -14px');
					}	
				}
				$lp('.right_icon', this).unbind('click');
			break;
			
			case 'r':
				$lp('td.icon', this).css('background-color','');	    				
				
				// if custom item - display grey icon
				if (!item_id.match('cid'))
				{
					$lp('.right_icon', this).css('background-position','0px 0px');
				}
				// if db item
				else
				{						
					var is_fav = g_current_food_list[item_id].f;	
					if (is_fav)
					{
						$lp('.right_icon', this).css('background-position','-42px 0px');
					}
					else
					{
						$lp('.right_icon', this).css('background-position','-86px -14px');
					}	
				}
				$lp('.right_icon', this).unbind('click');
			break;
		}	
	}

	function onItemClick() 
	{
		// add only new item
		if( !g_my_food[g_current_meal][this.parentNode.id] && !g_data_lock)
		{
			var amount = eval($lp('span.amount',this.parentNode).text());	
			$lp('td.plus',this.parentNode).removeClass('image_plus').css({'background-repeat':'no-repeat','background-position':'3px 4px','background-image':'url('+get_img_url('canvas/load.gif') + ')'});
			addItem( g_current_meal, this.parentNode.id, amount );
		}		
	}
	
	function get_meal_id(meal_name)
	{
		switch (meal_name)
		{
			case 'breakfast':
				return 1;
			break;
			
			case 'lunch':
				return 2;
			break;
			
			case 'dinner':
				return 3;
			break;
			
			case 'misc':
				return 4;
			break;
		}		
	}

	function addItem(meal, id, amount) {
	    if(g_data_lock) return;	
		
		g_data_lock = true;
		
		lp_trackEvent('Add Item - ' + meal, id);
		
	    g_my_food[meal][id] = g_current_food_list[id];	   
	    g_my_amounts[meal][id] = amount;
				
	    calculateCalories(meal);

	    if(meal == g_current_meal) updatePanel();
	    updateGlobal();				
		
		// save my meal item
		set_my_meal_item(meal, get_meal_id(meal), id, amount, set_my_meal_callback);		
	}

	function onReset() {
	    lp_trackEvent('Reset Calories',$lp('#total_meals_cal').text());
	    $lp('#popup').hide();	   
		$lp('#daily_use').html(LP_MSG_title_used.replace('%NUM%','<span style="color:#004b57">0</span>'));
	    g_my_food = { 'breakfast':{}, 'lunch':{}, 'dinner':{}, 'misc':{} };
	    $lp('.selected').removeClass('selected');
	    $lp('.vmark').removeClass('image_plus').removeClass('vmark');
				
		prefs.set("breakfast",0,"lunch",0,"dinner",0,"misc",0);
		reset_my_meals(reset_my_meals_callback);		
	}

	function onDeleteItem(item_id) {
	    if( g_data_lock ) return;
		g_data_lock = true;
		
	    var id;
				
		if (typeof(item_id) != 'object')
		{
			id = item_id;			
		}
		else
		{
			id = this.parentNode.food_id;			
		}
						
	    delete g_my_food[g_current_meal][id];

	    var row=$lp('#'+id);		
		row.removeClass('selected');
	    $lp('.vmark', row).removeClass('vmark').removeClass('image_plus');
	    updatePanel();
	    updateGlobal();

		set_my_meal_item(g_current_meal, get_meal_id(g_current_meal), id, 0, set_my_meal_callback);	
	}
	
	function sort_panel(a, b)
	{
		if (a[1].toLowerCase() > b[1].toLowerCase() )		
			return 1;
		else
			return -1;
	}

	function updatePanel() {
	    $lp('#panel_title').text( g_meal_names[g_current_meal] + ' - ' + calculateCalories(g_current_meal) + ' __MSG_calories__' );
	
	    $lp('#panel_list').html('');
	    $lp('#panel_summary').html('');
				
	    var sorted = [];
	    for( id in g_my_food[g_current_meal] ) {
			sorted.push( [ id, g_my_food[g_current_meal][id]['n'] ] );
	    }
	    
		sorted.sort(sort_panel);

		if(sorted.length == 0)
		{
			$lp('#panel_summary').html('<font style="color:#9DE0FF;">'+ ('__MSG_no_meal_items__').replace('%MEAL%','<font style="text-transform:capitalize">'+g_current_meal+'</font>')+'</font>');
		}
		
	    for( i=0; i<sorted.length; i++ ) {
			var id = sorted[i][0];
			var item = g_my_food[g_current_meal][id];

			var li = document.createElement('li');
			li.food_id = id;
			li.style.cursor = 'auto';
			
			if( g_is_metric && (item.u == 'oz' || item.u == 'gram') && (item.g) ) 
			{
			    item.g = 10;
			    item.u = 'gram';			 
			}
			
			if( !g_is_metric && (item.u == 'oz' || item.u == 'gram') && (item.g) ) 
			{
			    item.g = 28;
			    item.u = 'oz';			    
			}
					
			var cals = getItemCalories(item, g_my_amounts[g_current_meal][id]);
			var delete_item = $lp('<div class="del image_plus" id="del_'+id+'">&nbsp;</div>').click(onDeleteItem).appendTo(li);						
			var name_span = $lp('<span>'+item.n+' - '+g_my_amounts[g_current_meal][id]+' '+item.u+', '+cals+' __MSG_cal__</span>').appendTo(li);
			
			delete_item.hover(
				function()
				{
					$lp(this).css('background-position','-146px -14px');
				},
				function()
				{
					$lp(this).css('background-position','-146px 0px');				
				}
			);
			
			$lp('#panel_list').append( li );

			var content = $lp('#panel_summary').html();

			if( i%2 != 0 ) content += '<span style="color:#D1DADF">'+item.n+'</span>';
			else content += item.n;

			if( i<sorted.length-1 ) content +=',&nbsp;&nbsp;';

			$lp('#panel_summary').html( content );
	    }
	}

	function updateGlobal() {
		var cal_sum = calculateCalories('breakfast') + calculateCalories('lunch') +
				    calculateCalories('dinner') + calculateCalories('misc');			   
	   $lp('#daily_use').html(LP_MSG_title_used.replace('%NUM%','<span id="total_meals_cal" style="color:#004b57">'+cal_sum+'</span>'));
	}

	function calculateCalories(meal) {
	    var sum = 0;
	    for( id in g_my_food[meal] ) 
		{
			if (g_my_food[meal])
				sum += getItemCalories(g_my_food[meal][id], g_my_amounts[meal][id]);
	    }	    

	    return Math.floor(sum);
	}

	var g_is_view_metric = false;
	var g_calories_type = 's';
	var g_calories;
	var CALORIES_SUGGESTED = 's';
	var CALORIES_CUSTOM = 'c'; 
	function saveSettings() {
		var calories;	    	    
	    var data = {};
		var orig_is_metric = g_is_metric;
		var event_metric, event_caltype;
	
	    if(g_is_view_metric != g_is_metric) {
			g_is_metric = g_is_view_metric;
			$lp('#food_table tr').remove();			
        }
							    
	    data.metric = g_is_metric;
	    data.age = $lp('#settings_age').val();
	    data.male = document.getElementById('gender_m').checked;
		
		if (document.getElementById('settype_s').checked)
		{
			data.calories_type = CALORIES_SUGGESTED;
			calories = getRecommendedCalories();	
			event_caltype = 'suggested';
		}
		else
		{
			data.calories_type = CALORIES_CUSTOM;
			calories = $lp('#custom_calories').val();	
			event_caltype = 'custom';
		}
		g_calories_type = data.calories_type
		
		// check input
		
		// suggested caloreis
		if (data.calories_type == CALORIES_SUGGESTED)
		{
			// check numeric age
			if (!check_numeric($lp('#settings_age').val()))
			{
				alert('__MSG_err_set_age__');
				$lp('#settings_age').focus();
				return 0;
			}
			
			// check numeric weight
			if (!check_numeric($lp('#settings_weight').val()))
			{
				alert('__MSG_err_set_weight__');
				$lp('#settings_weight').focus();
				return 0;			
			}
		
			if (g_is_metric)
			{				
				// check numeric height
				if (!check_numeric($lp('#settings_height_cm').val()))
				{
					alert('__MSG_err_set_height__');
					$lp('#settings_height_cm').focus();
					return 0;
				}	
				event_metric = 'metric';
			}
			else
			{
				// check numeric height
				if (!check_numeric($lp('#settings_height_ft').val()))
				{
					alert('__MSG_err_set_height__');
					$lp('#settings_height_ft').focus();
					return 0;
				}		
				
				if (!check_numeric($lp('#settings_height_in').val()))
				{
					alert('__MSG_err_set_height__');
					$lp('#settings_height_in').focus();
					return 0;
				}					
				event_metric = 'imperial';
			}		
		}
		
		// custom caloreis
		else
		{
			// check numeric calories
			if (!check_numeric($lp('#custom_calories').val()))
			{
				alert('__MSG_err_item_cal__');
				$lp('#custom_calories').focus();
				return 0;
			}			
		}				
				
		$lp('#daily_quota').html(LP_MSG_title_quota.replace('%NUM%',calories)).css('cursor','default');		
		$lp('#daily_quota').unbind('click');
		
	    prefs.set('calories_quota', calories);
		g_calories = calories;
		
		data.custom_cal = $lp('#custom_calories').val();		
				
	    data.weight = $lp('#settings_weight').val();
	    if( !g_is_metric ) {
			data.height = $lp('#settings_height_ft').val()+','+$lp('#settings_height_in').val();
	    }
	    else {
			data.height = $lp('#settings_height_cm').val();
	    }
	    data.activity = $lp('#settings_activity').val();
	    
	    prefs.set('calorie_settings', lpgadgets.lp.utils.jsonStringify(data) );
		
		var gender = 1
		if (!data.male)
			gender = 0;			
		save_user_data(data.age, gender);
		
		if (data.calories_type == CALORIES_SUGGESTED)
			lp_trackEvent('Save Settings. ' + event_caltype + ',' + event_metric, 'Gender:' + gender + ',' + data.age + ', Activity:' +  data.activity);
		else
			lp_trackEvent('Save Settings. ' + event_caltype);
						
		// if the value system is cahnegd - refresh the data
		if (orig_is_metric != g_is_metric)
			return 2;			
		
		return 1;
	}
	
	function onSettingsSave() 
	{			
		var ret = saveSettings();
		
		if (ret == 1)
			$lp('#popup').hide();	  
		if (ret == 2)
		{				
			onReset();
			$lp('#popup').hide();	 
		}			
	}

	function loadSettings() {	  
	    var json = prefs.getString('calorie_settings');
	    if( json != "" ) {
			var data = lpgadgets.lp.utils.jsonParse(json);

			if( data.metric != g_is_metric ) {			    
			    g_is_metric = data.metric;
			}
			
			$lp('#settings_age').val(data.age);
			$lp('#settings_weight').val(data.weight);
			$lp('#custom_calories').val(data.custom_cal);
			if( !g_is_metric ) {
			    var split = data.height.split(',');
			    $lp('#settings_height_ft').val(split[0]);
			    $lp('#settings_height_in').val(split[1]);
			}
			else {
			    $lp('#settings_height_cm').val(data.height);
			}

			$lp('#settings_activity').val(data.activity);

			if(data.male) {
			    document.getElementById('gender_m').checked = true;
			}
			else {
			    document.getElementById('gender_f').checked = true;
			}
			
			if(data.calories_type == CALORIES_SUGGESTED) {
				document.getElementById('settype_s').checked = true;
				g_calories_type = CALORIES_SUGGESTED;
			}
			else {
				document.getElementById('settype_c').checked = true;
				g_calories_type = CALORIES_CUSTOM;							    
			}
			
			g_calories = prefs.getString('calories_quota');
			toggleTargetView(g_calories_type);
	    }				
	}
	
	// set the settings according to calories target type: suggested or custom
	function toggleTargetView(target_type)
	{
		if (target_type == CALORIES_CUSTOM)
		{					
			$lp('#user_settings_c').show();
			$lp('#user_settings_s').hide();					
			$lp('#custom_calories').focus();
		}
		else
		{
			$lp('#user_settings_c').hide();
			$lp('#user_settings_s').show();
			$lp('#settings_age').focus();
		}
	}

	//only show the extra fields, don't change the gadget or save anything
	function toggleMetricSystemView() { 			
	    if(g_is_view_metric) 
		{
			g_is_view_metric = false;
			$lp('#settings_height_imperial').show();
			$lp('#settings_height_metric').hide();
			$lp('#settings_weight_units').html('&nbsp;__MSG_lbs__');
			$lp('#metric a').text('__MSG_switch_to_metric__');		
			$lp('#units_name').text('__MSG_units_i__');		
	    }
	    else 
		{
			g_is_view_metric = true;
			$lp('#settings_height_imperial').hide();
			$lp('#settings_height_metric').show();
			$lp('#settings_weight_units').html('&nbsp;__MSG_kg__');
			$lp('#metric a').text('__MSG_switch_to_imperial__');	
			$lp('#units_name').text('__MSG_units_m__');					
	    }	    
	}

	function getRecommendedCalories() {
	    var gender = document.getElementById("gender_m").checked ? 'm':'f';
	    var age = parseInt(document.getElementById("settings_age").value);
	    var activity_level = parseFloat(document.getElementById("settings_activity").value);
	    
	    var weight = parseFloat(document.getElementById('settings_weight').value);

	    if (!g_is_metric)
	    if (!g_is_metric)
	    	weight = weight/2.2;
	    	    
	    var height = 0;
	    if (!g_is_metric) {
		var feet = parseInt(document.getElementById("settings_height_ft").value);
		var inches = parseInt(document.getElementById("settings_height_in").value) || 0;
		
		height = ((feet*12) + inches) * 2.54;
	    }else{
		height = parseInt(document.getElementById("settings_height_cm").value);
	    }
	    if (height==0 || weight==0 || age==0) {
		return 0;
	    }
	    
	    //Harris Benedict Formula
	    var result;
	    if (gender == 'm') {
		result = 66.5 + (13.75 * weight) + (5.003 * height) - (6.775 * age); //Men
	    } else {
		result = 655.1 + (9.563 * weight) + (1.850 * height) - (4.676 * age); //Women
	    }
	    
	    result = Math.round(result*activity_level);
	    
	    return result || 0;
	}
	
	function loadMeals() {
		get_my_meals(function (data)
					{
						g_my_food['breakfast'] = data.meals[0];
						g_my_food['lunch'] = data.meals[1];
						g_my_food['dinner'] = data.meals[2];
						g_my_food['misc'] = data.meals[3];												
						
						for( id in g_my_food[meal] ) 
						{
							g_my_amounts[meal][id] = g_my_food[meal][id]['a'];
					    }
						
						updatePanel();
						updateGlobal();		
					}
				);		
	}

	
	function track_expand(str)
	{
		if ($lp('#panel_summary').css('display') != 'none')
			lp_trackEvent('Expand Items List', str);
	}


	function init() {	    
	    loadImages();
	    loadButtons();
	    setupSearch();	

		g_my_items_count = prefs.getInt('my_items_count');
	  
	    if( prefs.getString('first_load') == '1' && prefs.getString('calorie_gadget_settings')!='' ) 
		{
			doSettingsImport();
			$lp('#popup').show();
	    }
	    var settings = prefs.getString('calorie_settings');
	    //in case we have old gadget residues, we have to remove them, or the JSON parse will fail 
		if(settings.charAt(0) != '{') 
		{ 
			prefs.set('calorie_settings','');
		}
	    
	    loadSettings();

		if (check_numeric(g_calories))
		{
			$lp('#daily_quota').html(LP_MSG_title_quota.replace('%NUM%',g_calories));
		}
		else
		{
			$lp('#daily_quota').html(LP_MSG_title_quota_empty).css('cursor','pointer');
			$lp('#daily_quota').click(function() {show_settings_popup();})	
		}
	    $lp('#panel_list_container').hide();
	    
	    $lp('#panel_expand,#panel_expand_button,#panel_title,#show_list a').click(
			function() 
			{
			    if(!g_is_panel_opened) 
				{					
					$lp("#panel").animate({'bottom':'0px', 'height':'335px'},500,
						      function()
							  {
								  $lp('#panel_expand a').text('__MSG_close_list__');
								  $lp('#panel_expand_button').css('background-position','0px 0px');

								  $lp('#panel_list_container').show();
								  $lp('#panel_summary').hide();
								  
								  $lp('.del').addClass('image_plus');								
						      });
			    }
			    else 
				{
					$lp('#panel_list_container').hide();
					$lp('#panel_summary').show();
					
					$lp("#panel").animate({'bottom':'0px', 'height':'50px'},500,
							      function()
								  {
									  $lp('#panel_expand a').text('__MSG_expand_list__');
									  $lp('#panel_expand_button').css('background-position','12px 0px');
							      });
			    }

			    g_is_panel_opened = !g_is_panel_opened;
			    return false;
			}
	    );
	    				
		init_custom_items();					   
	}
	
	function set_init_gui()
	{
		var params = gadgets.views.getParams();
	    if( (typeof params.settings != "undefined" ) && params.settings == "1" ) {				
			show_settings_popup();						
	    }
		
		// FF2 problem workaround
		if (jQuery.browser.mozilla)
			$lp('#food_tbody_cont').css('table-layout','fixed"');

	    if( typeof params.meal != "undefined" ) $lp('#'+params.meal).click();
	    else $lp('#breakfast').click();

	    prefs.set('first_load',0);
	    if(g_is_metric) $lp('#metric a').text('__MSG_switch_to_imperial__');
		
		g_last_search = prefs.getString('last_search');
		set_top_btn(prefs.getString('curr_tab'), false);
		g_curr_tab = prefs.getString('curr_tab');
		lp_trackEvent('Onload Tab', g_curr_tab);
				
		updatePanel();
		updateGlobal();	
				
		_IG_AdjustIFrameHeight();
	}

	function doSettingsImport() {	   
	    var str = prefs.getString('calorie_gadget_settings');
	    if (str.length == 0) { return; }
				
	    var settAr = str.split(",");
	    var data = {};
	    data.age = settAr[0];
	    data.male = (settAr[1]=="1");
				
	    if (settAr[2]=="0"){
		data.metric = false;
	    } else if (settAr[2]=="1") {
		data.metric = true;
		toggleMetricSystemView();
	    }

	    if (settAr[2]=="0"){
		data.height = settAr[4]+','+settAr[5];
		data.weight = settAr[3];
	    } else {
		data.height = settAr[4];
		data.weight = settAr[3];
	    }
	    data.activity = settAr[6];

	    prefs.set('calorie_settings', lpgadgets.lp.utils.jsonStringify(data) );
	    prefs.set('calorie_gadget_settings', '');
	}
	
	
var custom_items = {};
var recent_items = {};
var c1 = '';
var c2 = '';
var last_item_id = 3;

var DFLT_ERR = 'Data is null';

/*---------------------------------------------------------------------------*/
function init_custom_items()
{
	c1 = prefs.getString('c1');
	c2 = prefs.getString('c2');
	
	// if no password is created - generate a password
	if ((c1.length == 0) || (c2.length == 0))
	{
		c1 = generate_pwd();	
		
		// reset old data
		prefs.set('breakfast','',
				'lunch','',
				'dinner','',
				'misc','',
				'calories_quota','',
				'calorie_settings','',
				'calorie_gadget_settings','');
		
		// request a user id
		get_user_id(c1, get_user_id_callback);
	}
	else
	{		
		get_my_meals(get_my_meals_callback);
	}
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// called upon error in custom items data api
function custom_cal_error(text)
{	
	lp_trackEvent('Cal AppEngine Error', text);
	
	$lp('#main').css('background-image','');
	$lp('#main').html('<center><div style="text=align:center;width:465px;height:460px;font-family: Arial, Helvetica, sans-serif;font-size:11px; line-height:15px; color:#363636"><img src="http://cdn.labpixies.com/images/oops_data_icon.png" width="150" height="74" style="margin-top:15px;margin-bottom:15px"/><br/>__MSG_data_err1__<br/>__MSG_data_err2__</div></center>');	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// on first run - recieves user id from the server
function get_user_id(pwd, callback)
{	
	var url = API_URL + 'get_user_id?pwd='+pwd+'&callback=?';
	$lp.getJSON(url, callback);		
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// recieves a user id from the server
function get_user_id_callback(data)
{		
	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{
		c2 = data.user_id;
		prefs.set('c2', c2.toString(), 'c1', c1);
		
		get_my_meals(get_my_meals_callback);
	}
	else
	{
		custom_cal_error(data.error);
	}	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// generates a password
function generate_pwd()
{
	var length = 32;
	var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
	var pass = "";
	var x, i;
	
	for(x=0;x<length;x++)
	{
		i = Math.floor(Math.random() * 62);
		pass += chars.charAt(i);
	}
	return pass;
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// adds new custom item.
function add_item(name, unit, cal, callback)
{	
	var m_name = clear_string(name);
	
	g_data_lock = true;
	
	if ((m_name.length == 0) && (cal.length == 0))
	{
		g_data_lock = false;
		clear_after_custom_item();
		return;	
	}
	
	//check items couint
	if (g_my_items_count >= MAX_ITEMS)
	{
		alert( ('__MSG_err_item_count__').replace('%NUM%',MAX_ITEMS) );
		g_data_lock = false;
		return;	
	}
				
	//check item calories
	if (!check_numeric(cal))
	{		
		alert('__MSG_err_item_cal__');
		g_data_lock = false;
		$lp('#custom_cal').focus();	
		return;	
	}
			
	//check item name
	if (m_name.length == 0)
	{
		alert('__MSG_err_item_name__');
		g_data_lock = false;
		$lp('#custom_name').focus();	
		return;
	}
	
	lp_trackEvent('My Items - Add a New Custom Item', m_name);
					
	var url = API_URL + 'add_custom_item?user_id='+c2+ 
						'&pwd='+c1+
						'&name='+encodeURIComponent(m_name)+
						'&unit='+unit+
						'&cal='+cal+
						'&callback=?';
	$lp.getJSON(url, callback);	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// fired after the item is added
function add_item_callback(data)
{
	g_data_lock = false;
	
	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{			
		clear_after_custom_item();						
		$lp('#noresults').hide();
		
		// add to local dataset	
		if (g_my_items)
		{
			for(id in data.items)
			{
				var new_id = id;
				var new_item = {};
				
				new_item.n = data.items[new_id].n;
				new_item.c = data.items[new_id].c;
				new_item.u = data.items[new_id].u;
									
				g_my_items.items[new_id]=new_item;		
			}						
		}
		
		//g_my_items_count++;		
		
		update_my_items_count(1);		
		
		parseFoodJson(data, true);
	}
	else
	{
		custom_cal_error(data.error);
	}
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// display confirmation to delete custom item
function confirm_delete_item(item_id)
{
	var item_name = $lp('.foodname', $lp('#'+item_id)).text();	
	var msg_text = 	'__MSG_confirm_delete__'.replace('%NAME%', item_name);
	var answer = confirm(msg_text);

	if(answer)
		delete_item(item_id, delete_item_callback);			
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// deletes existing custom item
function delete_item(item_id, callback)
{	
	if (g_data_lock) return;
	
	lp_trackEvent('My Items - Remove Custom Item', g_my_items.items[item_id].n);
	
	g_data_lock = true;
	var url = API_URL + 'delete_custom_item?user_id='+c2+ 
						'&pwd='+c1+
						'&item_id='+item_id+						
						'&callback=?';
	$lp.getJSON(url, callback);	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// fired after the item is deleted
function delete_item_callback(data)
{
	var item_id;
		
	g_data_lock = false;
	
	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{		
		item_id = data.item_id;
		
		$lp('#'+item_id).remove();
		
		// delete item from local data		
		if (g_my_items)		
			delete (g_my_items.items[item_id]);				
			
		if (g_search_items)
			delete (g_search_items.items[item_id]);	

		//g_my_items_count--;			
		
		// if exsit in recent - delete from there
		if (g_recent_items)
		{
			if (g_recent_items.items[item_id])
				delete_recent_item(item_id, delete_recent_item_callback);
		}
		
		// delete from current meal
		onDeleteItem(item_id);
		
		// delete from the rest of the meals
		for(meal in g_meal_names) 
		{
			if ((meal != g_current_meal) && (g_my_food[meal][item_id]))
			{			
				delete g_my_food[meal][item_id];
				set_my_meal_item(meal, get_meal_id(meal), item_id, 0, null);	
			}
		}
			
		updatePanel();
	    updateGlobal();
			
		if ($lp('#food_tbody').html().length == 0)
		{		
			$lp('#noresults').html( ('__MSG_no_result_my__').replace("%BR%",'<br/>') );
			$lp('#noresults').show();
		}
		
		update_my_items_count(-1);		
	}
	else
	{
		custom_cal_error(data.error);
	}
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// Returns list of user’s custom items, search for “search_string” in the item name
function get_custom_items(search_string, callback)
{
	var url = API_URL + 'get_custom_items?user_id='+c2+ 
						'&pwd='+c1+		
						'&with_fav=1'+
						'&callback=?';
	$lp.getJSON(url, callback);	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// fired after the items are recieved
function get_custom_items_callback(data)
{
	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{
		// go over the tiems and add them to search results				
		g_my_items = data;
		parseFoodJson(data);
	}
	else
	{
		custom_cal_error(data.error);
	}
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// add/remove item to user meal
function set_my_meal_item(meal, meal_id, item_id, amount, callback)
{
	prefs.set(meal, calculateCalories(meal));
	
	var url = API_URL + 'update_item?user_id='+c2+ 
						'&pwd='+c1+	
						'&meal_id='+meal_id+
						'&item_id='+item_id+
						'&amount='+amount+
						'&callback=?';
	$lp.getJSON(url, callback);	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// fired after my melas items are set
function set_my_meal_callback(data)
{		
	if (!data)
	{
		g_data_lock = false;
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{						
		var item_row = $lp('#'+data.item_id);
		var new_item = null;
						
		if (data.amount > 0)
		{					
			$lp(item_row).addClass('selected');
			$lp('td.plus',item_row).css({'background-position':'-123px 5px','background-image':''});			
			$lp('td.plus',item_row).addClass('vmark').addClass('image_plus');			
			$lp('td.plus',item_row).attr('title','__MSG_tl_meal_added_item__');	
		}
		else
		{
			$lp('td.plus',item_row).css({'background-position':'-104px 5px','background-image':''});
		}
			
		// add to recent items
		switch (g_curr_tab)
		{
			case 'm':
				new_item = g_my_items.items[data.item_id];
			break;
			
			case 's':
				new_item = g_search_items.items[data.item_id];
			break;
		}
		
		if (g_recent_items)
		{
			if (data.removed_item.length>0)			
				delete (g_recent_items.items[data.removed_item]);
						
			if ((g_curr_tab != 'r') && (!g_recent_items.items[data.item_id]))
				g_recent_items.items[data.item_id]=new_item;				
		}
		g_data_lock = false;
	}
	else
	{
		g_data_lock = false;
		custom_cal_error(data.error);
	}
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// Returns list of user’s meals items
function get_my_meals(callback)
{
	var url = API_URL + 'get_items?user_id='+c2+ 
						'&pwd='+c1+									
						'&callback=?';
	$lp.getJSON(url, callback);	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// fired after my melas items are recieved
function get_my_meals_callback(data)
{
	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{
		for (i=0;i<g_meals_index.length;i++)
		{								
			g_my_food[g_meals_index[i]] = data.meals[i];			
									
			for( id in g_my_food[g_meals_index[i]] ) 
			{
				g_my_amounts[g_meals_index[i]][id] = g_my_food[g_meals_index[i]][id]['a'];
			}
		}
		
		set_init_gui();	
	}
	else
	{
		custom_cal_error(data.error);
	}
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// returns list of user’s recent items. 
function get_recent_items(callback)
{
	var url = API_URL + 'get_recent_items?user_id='+c2+ 
						'&pwd='+c1+									
						'&callback=?';
	$lp.getJSON(url, callback);	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// fired after the recent items are recieved
function get_recent_items_callback(data)
{
	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{		
		// save local dataset
		g_recent_items = data;
		// display recent items
		parseFoodJson(data);
	}
	else
	{
		custom_cal_error(data.error);
	}
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// add an item to “recent tiems” group. If the group exceeds the allowed 100 items, delete the oldest item fom the group and return it’s id in the callback.
function set_recent_item(item_id, callback)
{
	var url = API_URL + 'set_recent_item?user_id='+c2+ 
						'&pwd='+c1+	
						'&item_id='+item_id+
						'&callback=?';
												
	$lp.getJSON(url, callback);	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// fired after the recent item is added
function set_recent_item_callback(data)
{
	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{
		// add to local dataset	
		if (g_recent_items)
		{
			for(id in data.items)
			{
				var new_id = id;
				var new_item = {};
				
				new_item.n = data.items[new_id].n;
				new_item.c = data.items[new_id].c;			
				new_item.u = data.items[new_id].u;
				if (data.items[new_id].g)
					new_item.g = data.items[new_id].g;
														
				g_recent_items.items[new_id]=new_item;								
			}
			
			// if the recent items have reached a maximum - delete the removed item
			if (data.removed_item.length > 0)
			{
				if (g_recent_items.items[data.removed_item])
					delete (g_recent_items.items[data.removed_item]);			
			}
		}
	}
	else
	{
		custom_cal_error(data.error);
	}
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// removes an item from “recent tiems” group. used on deletion of a custom item
function delete_recent_item(item_id, callback)
{
	var url = API_URL + 'delete_recent_item?user_id='+c2+ 
						'&pwd='+c1+	
						'&item_id='+item_id+
						'&callback=?';
	$lp.getJSON(url, callback);	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// fired after the recent item is removed
function delete_recent_item_callback(data)
{
	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{
		// delete item from local data	
		if (g_recent_items)		
			delete (g_recent_items.items[data.item_id]);		
	}
	else
	{
		custom_cal_error(data.error);
	}
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// add an item to favorite tiems” group.
function set_fav_item(item_id, callback)
{
	if (g_my_items_count >= MAX_ITEMS)
	{
		alert( ('__MSG_err_item_count__').replace('%NUM%',MAX_ITEMS) );
		g_data_lock = false;
		return;	
	}

	lp_trackEvent('Set Item as Favorite', item_id);

	var url = API_URL + 'add_fav_item?user_id='+c2+ 
						'&pwd='+c1+	
						'&item_id='+item_id+
						'&callback=?';
	$lp.getJSON(url, callback);	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// fired after the favorite item is added
function set_fav_item_callback(data)
{
	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{
		var item_id = data.item_id;
		var tr = $lp('#'+item_id);
		var new_item = {};
				
		if (g_current_food_list)
		{		
			if (g_current_food_list[item_id])
				g_current_food_list[item_id].f=true;
		}	
		
		if (g_recent_items)
		{
			if (g_recent_items.items[item_id])
				g_recent_items.items[item_id].f = true
		}		
			
		if (g_search_items)
		{		
			if (g_search_items.items[item_id])
				g_search_items.items[item_id].f = true	
		}		
		
		$lp('.icon', tr).html('<div class="right_icon image_plus" style="background-position:-41px 0px;"></div>');
		
		// add to local dataset	
		if (g_my_items)		
		{
			new_item.n = g_current_food_list[item_id].n;
			new_item.c = g_current_food_list[item_id].c;
			new_item.u = g_current_food_list[item_id].u;
			new_item.g = g_current_food_list[item_id].g;
								
			g_my_items.items[item_id]=new_item;	
		}

		update_my_items_count(1);		
	}
	else
	{
		custom_cal_error(data.error);
	}
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// display confirmation to delete custom item
function confirm_delete_fav_item(item_id)
{
	var item_name = $lp('.foodname', $lp('#'+item_id)).text();
	var msg_text = 	'__MSG_confirm_delete__'.replace('%NAME%', item_name);
	var answer = confirm(msg_text);

	if(answer)
		delete_fav_item(item_id, delete_fav_item_from_my_callback);			
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// removes an item from favorite tiems” group. used on deletion of afavorite item
function delete_fav_item(item_id, callback)
{
	var url = API_URL + 'delete_fav_item?user_id='+c2+ 
						'&pwd='+c1+	
						'&item_id='+item_id+
						'&callback=?';
	$lp.getJSON(url, callback);	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// fired after the fav item is removed
function delete_fav_item_callback(data)
{	
	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{
		var item_id = data.item_id;
		var tr = $lp('#'+item_id);

		if (g_current_food_list)		
		{
			if (g_current_food_list[item_id])			
				g_current_food_list[item_id].f=false;
		}
		
		if (g_recent_items)
		{
			if (g_recent_items.items[item_id])
				g_recent_items.items[item_id].f = false
		}		
			
		if (g_search_items)
		{		
			if (g_search_items.items[item_id])
				g_search_items.items[item_id].f = false
		}		
		
		$lp('.icon', tr).html('<div class="right_icon image_plus" style="background-position:-86px -14px;"></div>');
		
		if (g_my_items)
			delete (g_my_items.items[item_id]);
			
		update_my_items_count(-1);			
	}
	else
	{
		custom_cal_error(data.error);
	}
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// fired after the fav item is removed from "my items"
function delete_fav_item_from_my_callback(data)
{	
	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{
		var item_id = data.item_id;
		var tr = $lp('#'+item_id);
		var is_empty = true;
		var item;
		
		if (g_current_food_list)
		{
			if (g_current_food_list[item_id])
				g_current_food_list[item_id].f = false;
		}
		
		if (g_recent_items)
		{
			if (g_recent_items.items[item_id])
				g_recent_items.items[item_id].f = false;
		}		
			
		if (g_search_items)
		{		
			if (g_search_items.items[item_id])
				g_search_items.items[item_id].f = false;
		}	
		
		tr.remove();
		
		if (g_my_items)
		{
			if (g_my_items.items[item_id])
				delete (g_my_items.items[item_id]);
				
			// check if empty		
			for (item in g_my_items.items)
			{
				is_empty = false;
				break;
			}	
			
			if (is_empty)
			{
				$lp('#noresults').html( ('__MSG_no_result_my__').replace("%BR%",'<br/>') );
				$lp('#noresults').show();			
			}			
		}		

		update_my_items_count(-1);				
	}
	else
	{
		custom_cal_error(data.error);
	}
}
/*---------------------------------------------------------------------------*/	

/*---------------------------------------------------------------------------*/
// Returns list of items y search. max result - 100 items
function get_search_items(search_string, callback)
{
	g_last_search = search_string;
	prefs.set('last_search', g_last_search);
	var url = API_URL + 'get_items_search?user_id='+c2+ 
						'&pwd='+c1+						
						'&search_string='+search_string+
						'&callback=?';
	$lp.getJSON(url, callback);	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
// fired after the items are recieved
function get_search_items_callback(data)
{
	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{
		// go over the tiems and add them to search results
		$lp('#food_table tr').remove();
		$lp('#noresults').hide();
		$lp('#loading').show();
				
		g_search_items = data;	
		parseFoodJson(data);
	}
	else
	{
		custom_cal_error(data.error);
	}
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
function reset_my_meals(callback)
{
	var url = API_URL + 'reset?user_id='+c2+ 
						'&pwd='+c1+												
						'&callback=?';
	$lp.getJSON(url, callback);	
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/		
function reset_my_meals_callback(data)		
{
	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}
	
	if (data.success)
	{
		 updatePanel();
	}
	else
	{
		custom_cal_error(data.error);
	}	   
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
function save_user_data(age, gender)
{
	var url = API_URL + 'user_data?user_id='+c2+ 
						'&pwd='+c1+	
						'&age='+age+
						'&gender='+gender+
						'&callback=?';
	$lp.getJSON(url, saveUserDataCallback);
}

function saveUserDataCallback(data) {

	if (!data)
	{
		custom_cal_error(DFLT_ERR);
		return;
	}

	if (!data.success) {
	
		custom_cal_error(data.error);
	}
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
function clear_after_custom_item()
{
	$lp('#add_my_item_btn').show();
	$lp('#custom_item_form').hide();
	$lp('#custom_name').val('');
	$lp('#custom_cal').val('');
		
	$lp('.add_btn_left', $lp('#add_my_item_btn')).css('background-position','0px 0px');
	$lp('.add_btn_right', $lp('#add_my_item_btn')).css('background-position','-192px 0px');
}
/*---------------------------------------------------------------------------*/	

/*---------------------------------------------------------------------------*/	
// sort the items A to Z
function items_sort(a, b)
{
	if (a.n.toLowerCase() > b.n.toLowerCase())
		return 1
	else
		return -1;
}

function sort_json_items(data, is_sort)
{
	var items_arr = [];
	var item;
	var new_item = {};
	
	for(item in data.items)
	{		
		if (data.items[item])
		{
			new_item = data.items[item];
			new_item.id = item;
			items_arr.push(new_item);
		}
	}
	
	if (is_sort)
		items_arr.sort(items_sort);
	
	return items_arr;
}
/*---------------------------------------------------------------------------*/	

/*---------------------------------------------------------------------------*/
// returns TRUE if the value is numeric, FALSE if not
function check_numeric(str)
{
	if (str != parseInt(str,10))
		return false;
	else
		return true;
}
/*---------------------------------------------------------------------------*/
// removes bad chars from the name of the custom item
function clear_string(str)
{
	var bad_chars = /[!@#$%^&*(){}\[\]"'?<>\/.,|:`~;]/ig;  
	return str.replace(bad_chars,"");   
} 
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
function show_reset_popup()
{
	$lp('#popup_settings').hide();
	$lp('#popup_title').text(prefs.getMsg("reset_title"));
	$lp('#popup_reset,#popup').show();
}
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
function show_settings_popup()
{	
	if(g_is_view_metric!=g_is_metric)
		toggleMetricSystemView();
	$lp('#popup_reset').hide();
	$lp('#popup_title').text(prefs.getMsg("settings_title"));
	$lp('#popup,#popup_settings').show();
		
	if ($lp('#user_settings_c').css('display') != 'none') 
		$lp('#custom_calories').focus();
	else
		$lp('#settings_age').focus();		
}
/*---------------------------------------------------------------------------*/

function update_my_items_count(dir)
{
	g_my_items_count = g_my_items_count + dir;
	prefs.set('my_items_count',g_my_items_count);
}

var LP_MSG_title_used = '__MSG_title_used__';
var LP_MSG_title_quota = '__MSG_title_quota__';
var LP_MSG_title_quota_empty = '__MSG_title_quota_empty__';

	_IG_RegisterOnloadHandler(init);

	_IG_Analytics("UA-345375-1", "/calories_canvas");
</script>
<center>

 <div id="ad_unit" style="width:760px; height:106px;">
	<div style="text-align:left; margin-left:22px; padding-top:9px;">
	 <script type="text/javascript">
		GA_googleFillSlot("calories_leaderboard_top");
		</script>
	</div>
</div>		

<div style="height:15px; font-size:1px;"></div>

<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td style="width:17px">&nbsp;</td>
<td style="width:465px">
<div id="container">
<div id="main">
	<div id="padding-replacer">
	<div id="header">
		<div id="header_text">
			<div id="daily_use">__MSG_title_used__</div>
			<div id="daily_quota">__MSG_title_quota__</div>			
		</div>
		<div id="header_links">
			<div style="margin-right:5px;" onclick="show_settings_popup()"><a href="javascript:void(0)">__MSG_settings__</a></div>
			<div onclick="show_reset_popup()"><a href="javascript:void(0)" onclick="show_reset_popup()" >__MSG_reset__</a></div>
		</div>
	</div>
	<div id="buttons">
		<div class="mealbutton notlast" id="breakfast">__MSG_breakfast__</div>
		<div class="mealbutton notlast" id="lunch">__MSG_lunch__</div>
		<div class="mealbutton notlast" id="dinner">__MSG_dinner__</div>
		<div class="mealbutton" id="misc">__MSG_misc__</div>
	</div>
	
	
	<div id="panel">
			<div id="panel_title" onclick="track_expand('Meal title')"></div>
			
			<div id="panel_expand_button" onclick="track_expand('Expand list button')"></div>
			<div id="panel_expand" onclick="javascript:track_expand('Expand list button')"><a href="javascript:void(0)">__MSG_expand_list__</a></div>
			
			<div id="panel_summary" style="padding-left:10px;clear:both;"></div>
			<div id="panel_list_container" style="overflow:auto;width:445px;height:310px;clear:left;cursor:default;">
				<ul id="panel_list"></ul>
			</div>
		</div>

		<div id="list_area" style="padding-top:50px;">
		<input id="search" type="text" value=""/>
		
		<div id="my_items_btn" class="top_btn" onclick="set_top_btn('m', false);lp_trackEvent('Switch Tab', 'm');">
			<table cellpadding="0" cellspacing="0" border="0">
				<tr>
					<td class="top_btn_bg top_btn_bg_left">__MSG_tab_my__</td>
					<td class="top_btn_bg top_btn_bg_right"></td>
				</tr>
			</table>		
		</div>
		
		<div id="recent_items_btn" class="top_btn" onclick="set_top_btn('r', false);lp_trackEvent('Switch Tab', 'r');">
			<table cellpadding="0" cellspacing="0" border="0">
				<tr>
					<td class="top_btn_bg top_btn_bg_left">__MSG_tab_recent__</td>
					<td class="top_btn_bg top_btn_bg_right"></td>
				</tr>
			</table>		
		</div>
				
		<div id="search_items_btn" class="top_btn" onclick="set_top_btn('s', false);lp_trackEvent('Switch Tab', 's');">
			<table cellpadding="0" cellspacing="0" border="0">
				<tr>
					<td class="top_btn_bg top_btn_bg_left">__MSG_tab_search__</td>
					<td class="top_btn_bg top_btn_bg_right"></td>
				</tr>
			</table>		
		</div>
						
		<div style="clear:both;">					
			<div>
			<table class="headers" cellspacing="0" cellpadding="0" border="0">
				<tr>
					<td class="foodname" style="cursor:auto;width:231px;">__MSG_food_item__</td>
					<td class="unit_header">__MSG_unit__</td>
					<td class="calories_header">__MSG_cal_per_unit__</td>
				</tr>
			</table>
			</div>			
						
			<table cellpadding="0" cellspacing="0" border="0" id="add_my_item_btn">
				<tr>
					<td class="add_btn_bg add_btn_left">__MSG_add_item_btn__</td>
					<td class="add_btn_bg add_btn_right"></td>
				</tr>
			</table>	

			<table cellpadding="0" cellspacing="0" border="0" id="custom_item_form" style="display:none;background-color:#5EB630;margin-left:1px;width:444px;">
				<tr style="height:24px">
					<td width="20">&nbsp;</td>
					<td valing="top" style="cursor:auto;width:220px;"><input id="custom_name" class="add_item_input" style="width:140px;" maxlength="50"/></td>
					<td valing="top" style="width:97px;">
						<select id="custom_unit" class="add_item_input" style="z-index:1">
							<option value="bar">bar</option>
							<option value="bottle">bottle</option>
							<option value="can">can</option>
							<option value="cup">cup</option>
							<option value="glass">glass</option>
							<option value="item">item</option>
							<option value="jar">jar</option>
							<option value="pack">pack</option>
							<option value="piece">piece</option>							
							<option value="portion">portion</option>
							<option value="slice">slice</option>
						</select>
					</td>
					<td valing="top" style="width:87px;"><input id="custom_cal" class="add_item_input" style="width:60px;" maxlength="5"/></td>
					<td class="icon"><div class="btn_sprite" id="save_my_item_btn" title="__MSG_tl_save_item__"></div></td>
				</tr>
			</table>				
			
		</div>
		
		<div id="food_table" style="padding-left:1px;width:444px;overflow-y:scroll;">
			<div id="loading"></div>
			<div id="noresults">__MSG_noresults__</div>						
			<table id="food_tbody_cont" cellspacing="0" cellpadding="0" border="0">
				<tbody id="food_tbody"></tbody>
			</table>
		</div>
	</div>
	</div> 
	
</div>


<!-- SETTINGS POPUP -->
<div id="popup">
	<div id="popup_inner">
		<div id="popup_title">__MSG_settings_title__</div>
		<div id="popup_close">
			<a href="javascript:void(0);" onclick="$lp('#popup').hide();return false;">__MSG_settings_close__</a>
		</div>

		<div id="popup_settings" style="padding-left:10px;padding-right:10px;">	
			<table cellspacing="0" cellpadding="0" border="0" style="font-family:arial,sans-serif;font-size:12px;color:#FFFFFF;">
				<tr>
					<!-- CALORIES TYPE -->
					<td width="100" valign="top">										
						<table cellpadding="0" cellspacing="0" border="0" style="color:#FFFFFF;font-size:12px;padding-right:8px;">
							<tr>
								<td><input type="radio" name="set_type" id="settype_c" onclick="toggleTargetView(CALORIES_CUSTOM)" checked/></td>
								<td width="8"></td>
								<td><label for="settype_c">__MSG_settype_c__</label></td>
							</tr>
							<tr height="20"><td colspan="3"></td></tr>
							<tr>
								<td><input type="radio" name="set_type" id="settype_s" onclick="toggleTargetView(CALORIES_SUGGESTED)"/></td>
								<td width="8"></td>
								<td><label for="settype_s">__MSG_settype_s__</label></td>
							</tr>	
							<tr height="40"><td colspan="3"></td></tr>
							<tr>
								<td colspan="3">
									<span style="font-size:12px;">__MSG_units__: <span id="units_name" style="font-size:bold;">__MSG_units_i__</span></span>
									<div id="metric"><a href="javascript:void(0)" onclick="toggleMetricSystemView(); return false;">__MSG_switch_to_metric__</a></div>
								</td>
							</tr>
						</table>										
					</td>
					<!-- /CALORIES TYPE -->
					
					<td width="1" valign="top"><div style="margin-right:10px;width:1px;height:155px;margin-bottom:10px;background-color:#87ca1a"></div></td>
					
					<!-- SETTINGS -->
					<td width="189" valign="top">						
						<div id="user_settings_c" style="float:left;">
							<div id="user_settings_c_text"></div>
							<input id="custom_calories" size="5" maxlength="5" style="margin-top:10px"/>
						</div>
				
						<div id="user_settings_s" style="float:left;display:none;">			
							<table cellspacing="0" cellpadding="0" border="0" style="font-family:arial,sans-serif;font-size:12px;color:#FFFFFF;">
								<tr>
									<td class="settings_row">
										__MSG_age__:<input style="margin-left:12px" class="text" type="text" name="age" id="settings_age" maxlength="2"/>
									</td>
								</tr>
								<tr>
									<td class="settings_row">
										__MSG_gender__:
										<input style="margin-left:12px" type="radio" name="gender" id="gender_m"/><label for="gender_m">__MSG_male__</label>
										<input type="radio" name="gender" id="gender_f"/><label for="gender_f">__MSG_female__</label>
									</td>
								</tr>			
								<tr>
									<td class="settings_row">
										__MSG_weight__:<input style="margin-left:12px" type="text" class="text" name="weight" id="settings_weight" maxlength="4"/><span id="settings_weight_units">&nbsp;__MSG_lbs__</span>
									</td>
								</tr>
								<tr>
									<td class="settings_row">										
										<div id="settings_height_imperial">
											__MSG_height__:<input style="margin-left:12px" type="text" class="text" name="height" id="settings_height_ft" maxlength="4"/>&nbsp;__MSG_ft__&nbsp;
											<input type="text" class="text" name="height_in" id="settings_height_in" maxlength="4"/>&nbsp;__MSG_in__
										</div>
										<div id="settings_height_metric" style="display:none">
											<span style="margin-right:12px">__MSG_height__:</span><input type="text" class="text" name="height" id="settings_height_cm" maxlength="4"/>&nbsp;__MSG_cm__
										</div>
									</td>
								</tr>		
								<tr>
									<td class="settings_row">
										__MSG_activity_level__
									</td>
								</tr>
								<tr>
									<td class="settings_row">
										<select id="settings_activity" style="">
											<option value="1.0">__MSG_no_exercise__</option>
											<option value="1.2">__MSG_little_exercise__</option>
											<option value="1.375">__MSG_exercise_3__</option>
											<option value="1.4625">__MSG_exercise_5__</option>
											<option value="1.6375">__MSG_exercise_daily__</option>
										</select>				
									</td>
								</tr>
							</table>
						</div>						
					</td>
					<!-- /SETTINGS -->
				</tr>
				<tr>
					<td colspan="3">
						<center>
						<div id="settings_save" onclick="onSettingsSave();" style="line-height:18px;cursor:pointer">					
						__MSG_save__
						</div>
						</center>
					</td>
				</tr>
			</table>
		</div>
		
		<div id="popup_reset" style="padding-left:25px;padding-right:25px;margin-top:70px;margin-bottom:70px;">			
			<table cellpadding="0" cellspacing="0" border="0" style="font-family:arial,sans-serif;font-size:12px;color:#FFFFFF;">
				<tr>
					<td colspan="2" height="35">
						__MSG_reset_sure__
					</td>
				</tr>
				<tr>
					<td>
						<div id="reset_yes" onclick="onReset(); $lp('#popup').hide();">__MSG_yes__</div>
					</td>
					<td>
						<div id="reset_no" onclick="$lp('#popup').hide();">__MSG_no__</div>
					</td>
				</tr>
			</table>			
		</div>
	</div>

</div>
<!-- /SETTINGS POPUP -->
	
<div style="margin-top:10px;">

<div id="help_btn" style="float:left;margin-right:10px;">
<table cellpadding="0" cellspacing="0" border="0">
	<tr>
		<td class="blue_btn blue_btn_left">__MSG_how_to_btn__</td>
		<td class="blue_btn blue_btn_right"></td>
	</tr>
</table>
</div>

<div id="disc_btn" style="float:left;">
<table cellpadding="0" cellspacing="0" border="0">
	<tr>
		<td class="blue_btn blue_btn_left">__MSG_disc_btn__</td>
		<td class="blue_btn blue_btn_right"></td>
	</tr>
</table>
</div>

<div id="help_text" style="padding-top:10px;clear:both;display:none">
<table width="445" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td width="20" valign="top"><span class="style1">1.</span></td>
        <td><span class="style1">Set your daily calories amount by clicking the "Settings" button.</span></td>

      </tr>
      <tr>
        <td width="20" style="font-size:1px; line-height:5px;">&nbsp;</td>
        <td  style="font-size:1px; line-height:5px;">&nbsp;</td>
      </tr>
      <tr>
        <td width="20" valign="top"><span class="style1">2.</span></td>
        <td><span class="style1"> Select the meal (<strong>Breakfast, Lunch, Dinner, Misc</strong>) to which you want to add food items.</span></td>

      </tr>      <tr>
        <td style="font-size:1px; line-height:8px;">&nbsp;</td>
        <td  style="font-size:1px; line-height:8px;">&nbsp;</td>
      </tr>
      <tr>
        <td width="20" valign="top"><span class="style1">3.</span></td>
        <td><span class="style1">Search for food item you would like to add - just type the food's name in the <strong>search box</strong> and press Enter.</span></td>

      </tr>      <tr>
        <td style="font-size:1px; line-height:8px;">&nbsp;</td>
        <td  style="font-size:1px; line-height:8px;">&nbsp;</td>
      </tr>
      <tr>
        <td width="20" valign="top"><span class="style1">4.</span></td>
        <td><span class="style1"> Add the food item from the search results clicking on the [<img id="help_add_to_meal" width="13" height="13" align="absmiddle" />] left to the food item. You can also mark the chosen item as favorite using the [<img id="help_add_to_fav" width="13" height="13" align="absmiddle" />] button.<br />

           Favorite items will appear in "My items" tab and will be easier to find.</span></td>
      </tr>      <tr>
        <td style="font-size:1px; line-height:8px;">&nbsp;</td>
        <td  style="font-size:1px; line-height:8px;">&nbsp;</td>
      </tr>
      <tr>

        <td width="20" valign="top"><span class="style1">5.</span></td>
        <td><span class="style1">If you have not found your desired food item in the existing database, you can add the item yourself! <br />
          Go to &quot;<strong>My items</strong>&quot; tab and click [<img id="help_add_new" width="114" height="18" align="absmiddle" />]. After you insert your item it will appear in My items tab and it will also be a part of your entire database - so you will able to search it.</span></td>
      </tr>      <tr>
        <td style="font-size:1px; line-height:8px;">&nbsp;</td>

        <td  style="font-size:1px; line-height:8px;">&nbsp;</td>
      </tr>
      <tr>
        <td width="20" valign="top"><span class="style1">6.</span></td>
        <td><span class="style1">Keep adding items until your entire daily menu is inserted.</span></td>

      </tr>		<tr>
	  	  	  
        <td style="font-size:1px; line-height:8px;">&nbsp;</td>

        <td  style="font-size:1px; line-height:8px;">&nbsp;</td>
      </tr>
      <tr>
        <td width="20" valign="top"><span class="style1">7.</span></td>
        <td><span class="style1">Now you can review &amp; reflect your daily calories amount - to view your full item list of a meal, click the &quot;<strong>Expand list</strong>&quot; button. You can remove the items you added from the expanded list.</span></td>

      </tr>      <tr>
        <td style="font-size:1px; line-height:8px;">&nbsp;</td>
        <td  style="font-size:1px; line-height:8px;">&nbsp;</td>
      </tr>
      <tr>
        <td width="20" valign="top"><span class="style1">8.</span></td>
        <td><span class="style1">When the day is over reset your daily menu by clicking the &quot;Reset&quot; button.</span></td>

      </tr>
      <tr>
        <td width="20">&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td width="20">&nbsp;</td>
        <td class="style1 style2" style="cursor:pointer" onclick="$lp('#help_text').toggle();_IG_AdjustIFrameHeight();">__MSG_close_btn__</td>
      </tr>
    </table>
</div>

</div>

</div>

</div>
</td>
<td style="width:20px">&nbsp;</td>

<td style="width:200px;" align="right" valign="top">
		<div style="width:200px; margin-bottom:10px;">
			<script type="text/javascript">
			  GA_googleFillSlot("calories_custom_1");
			</script>
		</div>
		<div style="width:200px; margin-bottom:10px;">
			<script type="text/javascript">
			  GA_googleFillSlot("calories_custom_2");
			</script>
		</div>
		<div style="width:200px;">
			<script type="text/javascript">
			  GA_googleFillSlot("calories_box");
			</script>
		</div>
</td>
<td style="width:18px">&nbsp;</td>
</tr>
</table>

<div>
	<script type="text/javascript">
		var mMENU = _IG_GetCachedUrl("http://cdn.labpixies.com/infra/js/lp_footer.js");
		document.write('<scr'+'ipt type="text/javascript" src="'+mMENU+'"></scr'+'ipt>');
	</script>
</div>
<iframe width="1" height="1" style="width:1px; height:1px; overflow:hidden; position:absolute; visibility:hidden;" src="http://static.labpixies.com/campaigns/calories/analytics.html"></iframe>
]]>
</Content>
<Content type="html">
<![CDATA[
<title>Calorie Calculator</title>
<!-- 
Calorie Calculator Module
Design & Code: LabPixies
All subsequent code and resources used are proprietary of LabPixies unless directly stated otherwise.
Copyright (C) 2008 LabPixies.    
www.labpixies.com

This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 2.5 License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/2.5/ or
send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.
-->
<style type="text/css"> 
<!--
body, html {
	margin: 0;
	padding: 0;
}
.style1 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
	font-weight: bold;
	color: #FFFFFF;
}
.style4 {font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #80cc90; }
.style6 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 10px;
	color: #FFFFFF;
	font-weight: bold;
}
.style7 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 10px;
	color: #97c2d5;
}
.style8 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 10px;
}
.style9 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 10px;
	color: #FFFF00;
	font-weight: bold;
}
.style10 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 11px;
	font-weight: bold;
	color: #FFFFFF;
}
.style11 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 10px;
	color: #003300;
	height: 16px;
}
.style12 {
	font-size: 10px;
	font-family: Arial, Helvetica, sans-serif;
	color: #FFFFFF;
}
.style13 {font-size: 12px; color: #FFFFFF; font-family: Arial, Helvetica, sans-serif;}
.style14 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 1px;
}
.style15 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 10px;
	color: #FFFF00;
	font-weight: bold;
}

.style16 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 11px;
	font-weight: bold;
	color: #FFFFFF;
}


.tableborder {
	border: 1px solid #FFFF00;
}

a:link    {text-decoration:none;color:#006CB3;}
a:visited {text-decoration:none;color:#006CB3;}
a:hover   {text-decoration:underline;color:#006CB3;}
a:active  {text-decoration:underline;color:#006CB3;}

-->
</style>
<!-- PUT THIS TAG IN THE head SECTION -->
<script type="text/javascript" src="http://partner.googleadservices.com/gampad/google_service.js">
</script>
<script type="text/javascript">
  GS_googleAddAdSenseService("ca-pub-8123415297019784");
  GS_googleEnableAllServices();
</script>
<script type="text/javascript">
  GA_googleAddSlot("ca-pub-8123415297019784", "calorie_calculator_txt");
</script>
<script type="text/javascript">
  GA_googleFetchAds();
</script>
<!-- END OF TAG FOR head SECTION -->

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script src="http://www.google-analytics.com/ga.js" type="text/javascript"></script>

<script type="text/javascript">
var _gadgetID=31;
var $lp=jQuery.noConflict();

//var mMENU = _IG_GetCachedUrl("http://cdn.labpixies.com/infra/js/lp_menu.js");
//document.write('<scr'+'ipt type="text/javascript" src="'+mMENU+'"></scr'+'ipt>');

var IMAGES_BASE = 'http://cdn.labpixies.com/campaigns/calories/';

function get_image(src) {	
	return  _IG_GetImageUrl(IMAGES_BASE + src);
}

var prefs = null;
var unitNames	= ["Unit", "Slice", "Bar", "Portion", "Glass", "Gram", "Bowl", "Piece", "Handful", "Pack", "Scoop", "knob", "Teaspoon", "Tablespoon", "pot", "meal", "sprinkling","quarter" ];
//Data arrays in the format of [name, unit Name index, num of units, calories]
var mainDishAr	= [["Bacon - Smoked/Cooked",1,1,25,0,1,1,0],
				   ["Beef - Prime",5,150,340,0,1,1,0],
				   ["Beef - Rib Steak",5,150,305,0,1,1,0],
				   ["Beef - Roasted",5,150,220,0,1,1,0],
				   ["Beef - Rump steak",5,150,310,0,1,1,0],
				   ["Beef - Sirloin",5,150,248,0,1,1,0],
				   ["Beef - Steak",5,150,228,0,1,1,0],
				   ["Beef - Carpaccio",3,1,226,0,1,1,0],
				   ["Cereal - sweetened",6,1,155,1,0,0,1] ,
					["Cereal - unsweetened",6,1,106,1,0,0,1] ,
				   ["Chicken - breast or leg",3,1,140,0,1,1,0],
				   ["Chicken - Roasted",3,1,270,0,1,1,0],
				   ["Chicken curry",3,1,640,0,1,1,0],
				   ["Cod",3,1,130,0,1,1,0],
				   ["Country pate",1,1,165,0,1,1,0], 
				   ["Couscous - with lamb",3,1,435,0,1,1,0],
				   ["Crab",3,1,60,0,1,1,0],
				   ["Duck",3,1,320,0,1,1,0],
				   ["Duck cutlet",3,1,350,0,1,1,0],
				   ["Egg",7,1,80,1,1,1,1],
				   ["Fish soup",6,1,150,0,1,1,0],
				   ["Foie Gras",1,1,179,0,1,1,1],
				   ["Fried Fish, Battered",7,1,232,0,1,1,0],
				   ["Hake",3,1,118,0,1,1,0],
				   ["Ham",1,1,96,1,1,1,1],
				   ["Ham - Cooked",1,1,275,1,1,1,1],
				   ["Hamburger",0,1,260,0,1,1,0],
				   ["Hot Dog",0,1,368,0,1,1,0],
				   ["Lamb - Cutlet",7,1,117,0,1,1,0],
				   ["Lamb - Leg",1,1,270,0,1,1,0],
				   ["Lamb, Mutton",1,1,225,0,1,1,0],
				   ["Liver",5,150,240,0,1,1,0],
				   ["Minced Meat",5,150,560,0,1,1,0],
				   ["Minced Meat - Lean",5,150,360,0,1,1,0],
				   ["Muesli",3,1,165,1,0,0,1] ,
				   ["Paella",3,1,518,0,1,1,0],
				   ["Pizza - cheese",1,1,230,0,1,1,0] ,
				   ["Pizza - ham and cheese",1,1,270,0,1,1,0] ,
				   ["Pork - Lean",3,1,220,0,1,1,0],
				   ["Pork - Spareribs",7,1,545,0,1,1,0],
				   ["Pork - Chops",7,1,235,0,1,1,0],
				   ["Pork - Roast",1,1,137,0,1,1,0],
				   ["Potted Meat",1,1,220,0,1,1,1],
				   ["Prawns",8,1,103,0,1,1,0],
				   ["Rabbit",3,1,186,0,1,1,0],
				   ["Salmon",3,1,130,1,1,1,0],
				   ["Salmon - Smoked",1,1,74,1,1,1,0],
				   ["Sausages",0,1,212,1,1,1,1],
				   ["Sausages - Frankfurters",0,1,75,0,1,1,0],
				   ["Scallops",7,5,60,0,1,1,0],
				   ["Sea Bass",3,1,85,0,1,1,0],
				   ["Sea Bream",3,1,85,0,1,1,0],
				   ["Sole",3,1,90,0,1,1,0],
				   ["Tuna - Fresh",3,1,282,0,1,1,0],
				   ["Tuna - Tinned",3,1,176,0,1,1,0],
				   ["Turkey - Roasted",5,85,140,0,1,1,0],
				   ["Veal",3,1,130,0,1,1,0],
				   ["Veal - Blanquette in sauce",3,1,420,0,1,1,0]
				   
				   ];

var sideDishAr	= [["Artichoke",3,1,14,1,1,1,0],
					["Asparagus",0,10,20,1,1,1,0],
					["Aubergine",3,1,25,1,1,1,0],
					["Avocado",0,1,180,1,1,1,0] ,
				   ["Beans - green",3,1,48,1,1,1,0],
				   ["Beetroot",0,1,46,0,1,1,0] ,
				   
				   ["Biscuits - savoury",7,10,90,0,0,0,1] ,
				   
				   ["Blinis",0,1,226,1,1,1,1] ,
				   
				   ["Bread - baguette",17,1,170,1,0,0,1] ,
					["Bread - brioche",1,1,27,1,0,0,1] ,
					
				   ["Bread - white",1,1,80,1,1,1,1],
				   ["Bread - wholemeal/nut",1,1,35,1,1,1,1],
				   ["Broccoli",3,1,25,1,1,1,0],
				   ["Carrots",3,1,50,1,1,1,0],
				   ["Cauliflower",3,1,30,1,1,1,0],
				   ["French Fries/Chips",3,1,508,0,1,1,1],
				   ["Oven French Fries/Chips",3,1,276,0,1,1,1] ,
				   ["Courgette",3,1,26,0,1,1,0] ,
				   
				   ["Crêpe - savoury",0,1,295,1,1,1,1] ,
				   ["Crêpe/pancake",0,1,40,1,1,1,1] ,
				   ["Crisps",9,1,234,0,1,1,1] ,
				   ["Cucumber",3,1,11,1,1,1,1] ,
				   ["Dim sum",0,1,210,0,1,1,0] ,
				   ["Lasagne",3,1,383,0,1,1,0] ,
				   ["Leeks",3,1,30,0,1,1,0] ,
				   ["Melba toast/crisproll",1,1,39,1,1,1,0] ,
				   ["Muesli",3,1,165,1,0,0,1] ,
				   ["Mushrooms - cooked",3,1,27,1,1,1,0] ,
				   ["Mushrooms - raw",3,1,27,1,1,1,1] ,
				   ["Olives - black",0,10,150,1,1,1,1] ,
				   ["Olives - green",0,10,60,1,1,1,1] ,
				   ["Pasta",3,1,248,0,1,1,0] ,
				   ["Peas",3,1,124,1,1,1,0] ,
				   ["Pepper",0,1,26,1,1,1,0] ,
				   ["Pizza - cheese",1,2,230,0,1,1,0] ,
				   ["Pizza - ham and cheese",1,1,270,0,1,1,0] ,
				   ["Potatoes - baked",3,1,90,0,1,1,0] ,
				   ["Potatoes - boiled",3,1,90,0,1,1,0] ,
				   ["Potatoes - Daupinois",3,1,90,0,1,1,0] ,
				   ["Potatoes - mashed",3,1,190,0,1,1,0] ,
				   ["Quiche Lorraine",1,1,539,0,1,1,1] ,
				   ["Ratatouille",3,1,100,0,1,1,0] ,
				   ["Raviolli in tomato sauce",3,1,202,0,1,1,0] ,
				   ["Rice",3,1,238,1,1,1,0] ,
				   ["Salad - green, as side dish",6,1,26,1,1,1,0] ,
				   ["Salad - mixed, as main course",6,1,245,0,1,1,0] ,
				   ["Sandwich - ham",0,1,390,1,1,1,1] ,
				   ["Spinach",3,1,34,1,1,1,0] ,
				   ["Spring roll",0,1,150,1,1,1,0] ,
				   ["Sweetcorn",3,1,218,1,1,1,0],
				   ["Tabbouleh",3,1,400,1,1,1,0] ,
				   ["Toasted sandwich - cheese & ham",0,1,428,1,1,1,0] ,
				   ["Tomato",0,1,22,1,1,1,1] ,
				   ["Tomato - stuffed",0,1,132,0,1,1,0] ,
				   ["Turnip",3,1,35,0,1,1,0],
				   ["Vegetable soup",6,1,95,0,1,1,0] ,
				   ["Wasa",1,1,50,1,1,1,0]
				   
				   ];

var toppingsAr	= [["Butter knob",11,1,60,1,1,1,1], 
					["Butter",5,25,188,1,1,1,1], 
					["Butter - low-fat, knob",11,1,32,1,1,1,1],
					["Butter - low-fat",5,25,100,1,1,1,1],
				   ["cr�me fraiche",12,1,64,0,1,1,0], 
				   ["cr�me fraiche - low-fat",12,1,41,0,1,1,0], 
				   
				   ["Honey",13,1,63,1,0,0,1], 
				   
 
					["Jam",12,1,53,1,0,0,1], 
					

				   ["Ketchup/brown sauce/BBQ sauce",13,1,17,0,1,1,0], 
				   ["Margarine/spread knob",11,1,37,1,1,1,1], 
				   ["Margarine/spread",5,25,185,1,1,1,1], 
				   ["Margarine/spread - low-fat, knob",11,1,19,1,1,1,1], 
				   ["Margarine/spread - low-fat",5,25,95,1,1,1,1],
				    ["Mayonnaise",13,1,107,0,1,1,1], 
				    ["Mayonnaise - low-fat",13,1,59,0,1,1,1], 
				   ["Mustard",12,1,7,0,1,1,1], 
				   ["Oil",13,1,135,0,1,1,0],
				   
				   ["Nutella",13,2,160,1,0,0,1], 
				   ["Pasta Sauce - Bolognaise",3,1,96,0,1,1,0], 
				   ["Pasta Sauce - Carbonara",3,1,63,0,1,1,0],
				   ["Pasta Sauce - tomato",13,1,12,1,1,1,1],
				   ["Peanut Butter",13,2,190,1,1,1,1],
				   ["Sauce - Barnaise",13,1,93,0,1,1,0], 
				   ["Sauce - Bchamel/white",13,1,17,0,1,1,0], 
				   ["Sauce - cocktail",13,1,30,0,1,1,0], 
				   ["Sugar, tablespoon",13,1,59,1,1,1,1],
				   ["Sugar, teaspoon",12,1,20,1,1,1,1],
				   ["Tarama",3,1,274,0,1,1,1], 
				   ["Vinaigrette",13,1,100,0,1,1,0],
				   ["Vinaigrette - low-fat",13,1,48,0,1,1,0]
				   
				   ];

var dessertAr	= [["Apple",0,1,47,1,1,1,1], 
					["Apricots",0,1,13,1,1,1,1], 
					["Banana",0,1,62,1,1,1,1], 
					["Banana split",3,1,400,1,1,1,1], 
					["Biscuits",0,5,130,1,1,1,1], 
				   ["Biscuits - butter",7,3,200,1,1,1,1], 
				   ["Biscuits - chocolate",7,3,200,1,1,1,1], 
				   ["Brioche",0,1,280,1,1,1,1], 
				   ["Brownie",0,1,380,1,1,1,1], 
				   ["Cake - cream",0,1,284,1,1,1,1], 
				   ["Cake - flan/gateau",7,1,140,1,1,1,1], 
				   ["Cake - fruit",7,1,160,1,1,1,1], 
				   ["Cake - sponge/Battenburg",7,1,400,1,1,1,1], 
				   ["Chocolate - dark",2,1,165,1,1,1,1], 
				   ["Chocolate - milk",2,1,162,1,1,1,1], 
				   ["Chocolate - white",2,1,130,1,1,1,1], 
				   ["Confectionery - cereal bar",2,1,200,1,1,1,1], 
				   ["Confectionery - chocolate bar",2,1,280,1,1,1,1], 
				   ["Confectionery - low-fat",2,1,110,1,1,1,1], 
				   ["Cr?me Caramel",0,1,120,1,1,1,1], 
				   ["Croissant",0,1,191,1,1,1,1], 
				   ["Croissant - almond",0,1,451,1,1,1,1], 
				   ["Dessert - creamy",3,1,170,1,1,1,1], 
				   ["Dessert - fruit pudding",7,1,270,1,1,1,1], 
				   ["Fruit - stewed, sweetened",3,1,116,1,1,1,1], 
				   ["Fruit - stewed, unsweetened",3,1,85,1,1,1,1], 
				   ["Fruit salad",3,1,94,1,1,1,1], 
				   ["Grapefruit",0,1,90,1,1,1,1], 
				   ["Grapes",8,1,100,1,1,1,1], 
				   ["Ice cream - with sauce",10,1,153,1,1,1,1], 
				   ["Kiwi fruit",0,1,25,1,1,1,1], 
				   ["Macaroon/small biscuits",0,1,113,1,1,1,1], 
				   ["Melon",3,1,51,1,1,1,1], 
				   ["Meringue",0,1,236,1,1,1,1], 
				   ["Mousse  - fruit",3,1,155,1,1,1,1], 
				   ["Mousse - chocolate",3,1,445,1,1,1,1], 
				   ["Muffin - chocolate",0,1,260,1,1,1,1], 
				   ["Orange",0,1,45,1,1,1,1], 
				   ["Pancake - sugar and lemon",0,1,118,1,1,1,1], 
				   ["Pastries - apple turnover",0,1,300,1,1,1,1], 
				   ["Pastries - other",0,1,172,1,1,1,1],
				   ["Pastries - Pain au chocolat / aux raisins",0,1,280,1,1,1,1], 
				   ["Peach",0,1,57,1,1,1,1], 
				   ["Pear",0,1,60,1,1,1,1], 
				   ["Pineapple",3,1,50,1,1,1,1], 
				   ["Pineapple - tinned",1,2,60,1,1,1,1], 
				   ["Prunes/dried fruit",0,1,33,1,1,1,1],
				   ["Strawberries",8,1,40,1,1,1,1], 
				   ["Tart",7,1,359,1,1,1,1], 
				   ["Waffle/doughnut",0,1,317,1,1,1,1]
				   
				   ];

var dairyAr		= [["Cheese - Babybel",0,1,100,0,1,1,0], 
				   ["Cheese - blue",7,1,137,0,1,1,0], 
				   ["Cheese - Boursin/garlic cheese",7,1,166,1,1,1,0], 
				   ["Cheese - Camember/Brie",7,1,146,1,1,1,0],
				   ["Cheese - cheddar/hard cheese",7,1,186,1,1,1,0], 
				   ["Cheese - cream cheese",3,1,80,1,1,1,0], 
				   ["Cheese - cream cheese flavored",3,1,116,1,1,1,0], 
				   ["Cheese - fondue/raclette",15,1,714,1,1,1,0], 
				   ["Cheese - Mozzarella",7,1,415,1,1,1,0], 
				   ["Cheese - Parmesan",3,1,160,1,1,1,0], 
				   ["Cheese - spread",3,1,92,1,1,1,0], 
				   ["Cheese - topping",16,1,113,1,1,1,0], 
				   ["Cheese sauce",3,1,490,1,1,1,0], 
				   ["Cheese-ream cheese, low-fat",3,1,44,1,1,1,0], 
				   ["cheese - goat's cheese",7,1,32,1,1,1,0], 
				   ["Cream",13,5,76,0,1,1,0], 
				   
				   ["Milk - skimmed",4,1,51,1,1,1,1],
				   
					["Milk - whole",4,1,98,1,1,1,1],
					

					["Milk - semi-skimmed",4,1,69,1,1,1,1],
					

				   ["Yogurt - creamy",14,1,190,1,1,1,1],
				   ["Yogurt - fruit",14,1,106,1,1,1,1],
				   ["Yogurt - fruit, low-fat",14,1,60,1,1,1,1],
				   ["Yogurt - plain/low-fat",14,1,63,1,1,1,1]
				   
				   ];
				   

var beveragesAr	= [["Beer",4,1,150,0,1,1,0],
					["Champagne",4,1,80,0,1,1,0],
					["Cider",4,1,50,1,1,1,1],
					["Soda",4,1,67,1,1,1,1],
					["Diet Soda",4,1,3,1,1,1,1],
				   ["Coffee",4,1,2,1,1,1,1],
				   ["Tea",4,1,2,1,1,1,1],
				   ["Fortified Wines",4,1,55,0,1,1,0],
				   ["Soft Drinks/Fruit juice",4,1,72,1,1,1,1],
				   ["Fruit juice - Tomato",4,1,24,1,1,1,1],
				   ["Liqueur",4,1,80,0,1,1,0],
				   ["Pastis",4,1,106,0,1,1,0],
				   ["Spirits",4,1,100,1,1,1,1],
				   ["Water",4,1,0,1,1,1,1],
				   ["Wine",4,1,90,0,1,1,0],
				   ["Wine - Dessert",4,1,190,0,1,1,0],
				   ["Sugar, teaspoon",12,1,20,1,1,1,1]
				   
				   ];


			var dishArray = [mainDishAr,sideDishAr,toppingsAr,dessertAr,dairyAr,beveragesAr];
			
			var mealNames = ["Breakfast","Lunch","Dinner","Misc"];
			
			var currDishAr = dishArray[0];
			
			var mealIndex = 0;
			var dishIndex = 0;
			var totalDailyCalorie = 0;
			var scrollOffset = 0;
			
			function setUnit(){
				var index = document.getElementById("select_food").value;
				var unitIndex = currDishAr[index][1];
				var quantity = currDishAr[index][2];
				
				var unitStr = unitNames[unitIndex];
				
				if (unitIndex==5 && (document.getElementById("metricTable").style.display == "none")) {
					unitStr = "oz";
					quantity = quantity/28.349;
					quantity = quantity.toFixed(2);
				}
				document.getElementById("unitStr").innerHTML = "<b>Unit: </b>"+quantity+" "+unitStr;
			}
			
			function setSelectFoodContent(num){
				var selectElm = document.getElementById("select_food");
				var i = 0;
				currDishAr = dishArray[num];
				
				//clean up
				selectElm.innerHTML = "";
				document.getElementById("unitStr").innerHTML = "";
				document.getElementById("defaultAmount").selected = true;
				
				var firstOpt = document.createElement("option");
				firstOpt.value = "none";
				firstOpt.innerHTML = "Select Food";
				firstOpt.selected = true;
				firstOpt.style.fontFamily = "Arial";
				firstOpt.style.fontSize = "10px";
				selectElm.appendChild(firstOpt);
				
				//add
				for(i=0;i<currDishAr.length;i++){
					if (currDishAr[i][mealIndex+4] == 1) {
						var currOpt = document.createElement("option");
						currOpt.value = i;
						currOpt.innerHTML = (currDishAr[i][0]).substring(0,21);
						currOpt.title = currDishAr[i][0];
						currOpt.style.fontFamily = "Arial";
						currOpt.style.fontSize = "10px";
						selectElm.appendChild(currOpt);
					}
				}
			}


			function getDishImage(num){
				var temp = parseInt(num);
				switch(temp){
					case 0:
						return get_image("images/maindish_icon.gif");
					case 1:
						return get_image("images/sidedish_icon.gif");				
					case 2:
						return get_image("images/toppings_icon.gif");		
					case 3:
						return get_image("images/dessert_icon.gif");		
					case 4:
						return get_image("images/dairy_icon.gif");		
					case 5:
						return get_image("images/beverages_icon.gif");
				}
				//alert("Should not happen");
				return get_image("images/maindish_icon.gif");
			}

			function goToDish(num){
				if (num == -1) {
					num = document.getElementById("DishSelector").value;
				}else{
					document.getElementById("DishSelector").value = num;
				}
				
				//set image
				document.getElementById("SelectedDish").src = getDishImage(num);
				
				//set select content
				setSelectFoodContent(num);
				
				//toggle tables
				document.getElementById("SelectionTable").style.display = "none";
				document.getElementById("MealSelect").style.display = "inline";
				
				dishIndex = num;
			}
			
			
			function changeMeal(num){
				var i=0;
				
				for(i=0;i<4;i++){
					var temp = document.getElementById("meal"+i);
					temp.src = temp.src.replace("_on","_off");
				}
				var elm = document.getElementById("meal"+num);
				elm.src = elm.src.replace("_off","_on");
				
				mealIndex = num;
				
				
				
				var str = getMealCookieStr(mealIndex);
				
				parseMealCookie(mealIndex,str);
				resetScrollState();
				updateButtons();
				
				//toggle tables
				document.getElementById("SelectionTable").style.display = "inline";
				document.getElementById("MealSelect").style.display = "none";
			}
			
			
			function addMealItem(){
				var i=0;
				var itemIndex,quantity;
				
				itemIndex = document.getElementById("select_food").value;
				
				if (itemIndex == "none") {
					//alert("Please select food item");
					return;
				}
				quantity = parseFloat(document.getElementById("select_amount").value);
				
				//get data
				//var meals = lp_get_cookie("calorie_settings");
				var meals = prefs.getString("calorie_settings");
				
				if (meals.length == 0) {
					meals = "______";
					
				}
				
				
				var mealsArray = meals.split("__");
				
				var currMeal = mealsArray[mealIndex];
				var numItems = currMeal.split("-").length;
				
				if (numItems > 20) {
					return;
				}
				if (currMeal!=null) {
					currMeal += ("-"+dishIndex+","+itemIndex+","+quantity);
				}else{
					currMeal = ("-"+dishIndex+","+itemIndex+","+quantity);
				}
				
				mealsArray[mealIndex] = currMeal;
			
				var newStr = mealsArray[0];
				
				for(i=1;i<mealsArray.length;i++){
					newStr += ("__"+mealsArray[i]);
				}
				
				//lp_set_cookie( 'calorie_settings', newStr, (1000*60*60*24*30) , '/campaigns/calories/', '.labpixies.com', '' );
				prefs.set("calorie_settings", newStr);
				lp_trackEvent('AddItem');
				
				//reparse current meal cookie
				parseMealCookie(mealIndex,mealsArray[mealIndex]);
				updateTotal();
				updateButtons();
			}
			
			function removeMealItem(index){
		
				var i=0;
				var itemIndex,quantity;

				//remove from prefs
				//var meals = lp_get_cookie("calorie_settings");
				var meals = prefs.getString("calorie_settings");
				
				if (meals.length == 0) {
					return; //?
				}
				
				updateNewScrollHeight(index);
				
				var mealsArray = meals.split("__");
				
				var currMeal = mealsArray[mealIndex];
				if (currMeal!=null) {
					var items = currMeal.split("-");
					var j = 0;
					var itemStr = "";
					for(j=1;j<items.length;j++){
						if (j != index) {
							itemStr += ("-"+items[j]);
						}
					}
					currMeal = itemStr;
				}
				
				mealsArray[mealIndex] = currMeal;
			
				var newStr = mealsArray[0];
				
				for(i=1;i<mealsArray.length;i++){
					newStr += ("__"+mealsArray[i]);
				}
				
				//lp_set_cookie( 'calorie_settings', newStr, (1000*60*60*24*30) , '/campaigns/calories/', '.labpixies.com', '');
				lp_trackEvent('RemoveItem');
				prefs.set("calorie_settings", newStr);
				
				//reparse current meal cookie
				parseMealCookie(mealIndex,mealsArray[mealIndex]);
				updateTotal();
				updateButtons();
			}
			
			function parseTotalCals(){
				//var meals = lp_get_cookie("calorie_settings");
				var meals = prefs.getString("calorie_settings");
				var i,j,total;
				
				if (meals.length == 0) {
					return 0; //?
				}
				
				total = 0;
				
				var mealsArray = meals.split("__");
				for(i=0;i<mealsArray.length;i++){
					var items = mealsArray[i].split("-");
					var j = 1;
					
					//add items and sum total calories
					for(j=1;j<items.length;j++){
						var itemDetails = items[j].split(",");
						var itemQuan = parseFloat(itemDetails[2]);
						var currDishAr = dishArray[parseInt(itemDetails[0])];
						var itemCal = currDishAr[parseInt(itemDetails[1])][3];
						itemCal = Math.floor(itemCal*itemQuan);
						total += itemCal;				
					}
				}
				return total;
			}	
			
			function parseMealCookie(meal,cookieStr){
				
				//remove all items
				document.getElementById("mealDetails").innerHTML = "";;
				
				
				
				var items = cookieStr.split("-");
				var i = 1;
				var totalCal = 0;
				
				//add items and sum total calories
				for(i=1;i<items.length;i++){
					totalCal +=	addItemDetails(i,items[i]);				
				}
				
				document.getElementById("MealTitle").innerHTML = mealNames[meal]+": "+totalCal;
			}
			
			function addItemDetails(itemDetailIndex,item){
				
				var itemDetails = item.split(",");
				
				var currDishAr = dishArray[parseInt(itemDetails[0])];
			
			
				var index = parseInt(itemDetails[1]);
				var itemQuan = parseFloat(itemDetails[2]);
				var itemCal = currDishAr[index][3];
				itemCal = itemCal*itemQuan;
				var itemName = currDishAr[index][0];
				
				
				
				var ItemStr = '<div align="center"><table width="94" border="0" cellspacing="0" cellpadding="0">'+
							'<tr><td><img src="'+get_image('images/trans.gif') +'" width="4" height="4" /></td></tr><tr><td width="14" valign="top"><img title="Remove item from list" onclick="removeMealItem('+itemDetailIndex+');" src="'+get_image('images/remove_item.gif')+'" width="9" height="9" /></td>'+
								'<td width="80"><span class="style6">'+itemName+' - '+itemQuan+'</span><br />'+
								'<span class="style7">'+itemCal+' Calories</span>'+
								'</td></tr></table></div>';
				

				document.getElementById("mealDetails").innerHTML += ItemStr;
				
				return itemCal;
			}
			
			function getMealCookieStr(index){
				//var meals = lp_get_cookie("calorie_settings");
				var meals = prefs.getString("calorie_settings");
				
				if (meals.length == 0) {
					return ""; 
				}
				var mealsArray = meals.split("__");
				return mealsArray[index];
			}
			
			function load_images()
			{
				$lp('#yellow_meter').attr('src',get_image('images/yellow_meter.gif'));
				$lp('#meal0').attr('src',get_image('images/breakfast_button_on.gif'));
				$lp('#meal1').attr('src',get_image('images/lunch_button_off.gif'));
				$lp('#meal2').attr('src',get_image('images/dinner_button_off.gif'));
				$lp('#meal3').attr('src',get_image('images/misc_button_off.gif'));
				$lp('#maindish_icon').attr('src',get_image('images/maindish_icon.gif'));
				$lp('#sidedish_icon').attr('src',get_image('images/sidedish_icon.gif'));
				$lp('#toppings_icon').attr('src',get_image('images/toppings_icon.gif'));
				$lp('#dessert_icon').attr('src',get_image('images/dessert_icon.gif'));
				$lp('#dairy_icon').attr('src',get_image('images/dairy_icon.gif'));
				$lp('#beverages_icon').attr('src',get_image('images/beverages_icon.gif'));
				$lp('#SelectedDish').attr('src',get_image('images/maindish_icon.gif'));
				$lp('#swithcto_title').attr('src',get_image('images/swithcto_title.gif'));
				$lp('#add_button').attr('src',get_image('images/add_button.gif'));
				$lp('#upButton').attr('src',get_image('images/scroll_up.gif'));
				$lp('#scroll_down').attr('src',get_image('images/scroll_down.gif'));
				$lp('#bottomGif').attr('src',get_image('images/bottom2.gif'));				
				$lp('#Img1').attr('src',get_image('images/bottom3.gif'));
				$lp('#save').attr('src',get_image('images/save.gif'));
				$lp('#dark_blue_back').attr('src',get_image('images/dark_blue_back.gif'));
												
				$lp('.transparent').attr('src',get_image('images/trans.gif'));
				$lp('.light_blue_back').attr('src',get_image('images/light_blue_back.gif'));								
				
				$lp('.greentop_back').attr('background',get_image('images/greentop_back.gif'));
				$lp('.light_blue_back_bg').attr('background',get_image('images/light_blue_back.gif'));
				$lp('.dark_blue_back').attr('background',get_image('images/dark_blue_back.gif'));
				
			}
			
			function load(){

				prefs = new _IG_Prefs();
				var str = getMealCookieStr(0);
				
				parseMealCookie(0,str);
				
				updateButtons();
				
				//if(str == "" && (lp_get_cookie("calorie_gadget_settings")==null)){
				if(str == "" && (prefs.getString("calorie_gadget_settings").length == 0)){
					//document.getElementById("settingsTable").style.visibility = "visible";
				}else{
					loadSettingScreenData();
					updateTotal();					
				}
				
				load_images();				
			}
			
			function resetAll(){
				if(confirm("Are you sure you want to reset your calorie calculator?")){
					//lp_set_cookie( 'calorie_settings', "______", (1000*60*60*24*30) , '/campaigns/calories/', '.labpixies.com', '' );
					prefs.set("calorie_settings", "______");
					changeMeal(0);	
					lp_trackEvent('ResetAll');
					updateTotal();
				}
			}
			
			function openSettings(){
			
				document.getElementById("settingsTable").style.display = "";
				
				
				loadSettingScreenData();
			}
			
			function closeSettings(save){
				
				if (save == 0) {
					document.getElementById("settingsTable").style.display = "none";
					return;
				}
				
				if (checkSettings()) {	
					document.getElementById("settingsTable").style.display = "none";
					saveSettings();
					updateTotal();
					lp_trackEvent('SaveSettings');
				}
			}
			
			function toggleSystem(){
				if (document.getElementById("metricTable").style.display == "none") {
					document.getElementById("standardTable").style.display = "none";
					document.getElementById("metricTable").style.display = "inline";
					document.getElementById("switchToText").innerHTML = "__MSG_switch_to_imperial__";
				}else{
					document.getElementById("metricTable").style.display = "none";
					document.getElementById("standardTable").style.display = "inline";
					document.getElementById("switchToText").innerHTML = "__MSG_switch_to_metric__";
				}
			}
			
			function loadSettingScreenData(){
				
				//var str = lp_get_cookie("calorie_gadget_settings");
				var str = prefs.getString("calorie_gadget_settings");
				
				if (str.length == 0) { return }
				
				var settAr = str.split(",");
				
				document.getElementById("age").value = settAr[0];
				document.getElementById("maleGender").checked = (settAr[1]=="1");
				document.getElementById("femaleGender").checked = (settAr[1]!="1");
				
				if (settAr[2]=="0" && document.getElementById("metricTable").style.display!="none"){
					toggleSystem();
				}else if (settAr[2]=="1" && document.getElementById("metricTable").style.display=="none") {
					toggleSystem();
				}
				
				
				document.getElementById("feet").value =  "0";
				document.getElementById("inches").value =  "0";
				document.getElementById("standardWeight").value = "0";
				document.getElementById("metricHeight").value =  "0";
				document.getElementById("metricWeight").value =  "0";
			
				
				if (settAr[2]=="0"){
					document.getElementById("feet").value = settAr[4];
					document.getElementById("inches").value = settAr[5];
					document.getElementById("standardWeight").value = settAr[3];
						
				}else{
					document.getElementById("metricHeight").value = settAr[4];
					document.getElementById("metricWeight").value = settAr[3];
				}
				markSelected("activityLevel",settAr[6]);
			}
			
			function saveSettings(){
				
				var age,gender,sys,weight,heightF,heightIn,activity;
				var isStandard = (document.getElementById("standardTable").style.display != "none");
				
				gender = document.getElementById("maleGender").checked ? 1 : 2;
				sys = (document.getElementById("standardTable").style.display != "none") ? 0 : 1;
				
				age = parseInt(document.getElementById("age").value);
				activity = (document.getElementById("activityLevel").value);
				
				var curWeight = (isStandard ? "standardWeight" : "metricWeight");
				weight = parseInt(document.getElementById(curWeight).value);
				
				
				if (isStandard) {
					heightF = parseInt(document.getElementById("feet").value);
					heightIn = parseInt(document.getElementById("inches").value);
				}else{
					heightF = parseInt(document.getElementById("metricHeight").value);
					heightIn = 0;
				}
				
				var str = age+","+gender+","+sys+","+weight+","+heightF+","+heightIn+","+activity;
				//lp_set_cookie( 'calorie_gadget_settings', str, (1000*60*60*24*30) , '/campaigns/calories/', '.labpixies.com', '' );
				prefs.set("calorie_gadget_settings", str);
			}
			
			function updateTotal(){
				document.getElementById("recommended").innerHTML = getRecommendedCalories();
				document.getElementById("dailyAmount").innerHTML = parseTotalCals();
			}
			
			function getRecommendedCalories() {
				
				var maleGender = document.getElementById("maleGender").checked;
				var isStandard = (document.getElementById("standardTable").style.display != "none");
				var calorieResult = 0;
				
				
				var age = parseInt(document.getElementById("age").value);
				
				
				var activityLevel = parseFloat(document.getElementById("activityLevel").value);
				
				var curWeight = (isStandard ? "standardWeight" : "metricWeight");
				
				var weight = parseInt(document.getElementById(curWeight).value);
				
				
				if (isStandard) 
					weight = weight/2.2;
					
				
				
				
				
				var height = 0;
				if (isStandard) {
					var feet = parseInt(document.getElementById("feet").value);
					var inches = parseInt(document.getElementById("inches").value);
					
					
					
					height = ((feet*12) + inches) * 2.54;
				}else{
					height = parseInt(document.getElementById("metricHeight").value);
					
				}
				
				if (height==0 || weight==0 || age==0) {
					return 0;
				}
				
				//Harris Benedict Formula
				if (maleGender == true) {
					calorieResult = 66.5 + (13.75 * weight) + (5.003 * height) - (6.775 * age); //Men
				} else {
					calorieResult = 655.1 + (9.563 * weight) + (1.850 * height) - (4.676 * age); //Women
				}
				
				calorieResult = Math.round(calorieResult*parseFloat(document.getElementById("activityLevel").value));
				
				return calorieResult;
			}
			
			
			function checkSettings(){
				var isStandard = (document.getElementById("standardTable").style.display != "none");
				var age = parseInt(document.getElementById("age").value);
				if (isNaN(age)){
						alert ("Please enter a valid age");
					return false;
				}
				else if ( (age <= 12) || (age > 80)) {
					alert ("Age must be between 13 and 80");
					return false;
				}
				
				
				
				var curWeight = (isStandard ? "standardWeight" : "metricWeight");
				
				var weight = parseInt(document.getElementById(curWeight).value);
				if (isNaN(weight)){
					alert ("Please enter a valid weight");
					return false;
				}
				
				var lowerLimit = 40;
				var upperLimit = 500;
				if (!isStandard) {
					var lowerLimit = 18;
					var upperLimit = 227;
				}
				
				if ( (weight <= lowerLimit) || (weight > upperLimit) ) {
					alert ("Please enter a valid weight");
					return false;
				}
				
				
				
				
				
				var height = 0;
				if (isStandard) {
					var feet = parseInt(document.getElementById("feet").value);
					var inches = parseInt(document.getElementById("inches").value);
					
					if (isNaN(feet)){
						alert ("Please enter a valid height");
						return false;
					}
					
					if ( (feet < 4) || (feet > 7) ) {
						alert ("Height must be between 4 and 7 feet");
						return false;
					}

					if (isNaN(inches)){
						alert ("Please enter a valid height");
						return false;
					}
					
					height = ((feet*12) + inches) * 2.54;
				}else{
					height = parseInt(document.getElementById("metricHeight").value);
					if ( (height < 120) || (height > 215) ) {
						alert ("Height must be between 120 and 215 centimeter");
						return false;
					}
				}
				
				return true;
			}
			
			function markSelected(selectName,value){

				var selectElm = document.getElementById(selectName);
				var optionArr = selectElm.options;
				var i = 0;
				var arrLength = optionArr.length;
                
				for(i=0;i < arrLength; i++){
					if(optionArr[i].value == value){
						optionArr[i].selected=true;
						
						return;
					}
				}
			}
			
			function updateNewScrollHeight(index){
				var elm = document.getElementById("mealDetails");
				var numItems = elm.childNodes.length;
				var i;
				var total = 0;
				
				if(index<=numItems){
					if(scrollOffset < 0){
						scrollOffset += elm.childNodes[index-1].offsetHeight;
					}
				}
				if (scrollOffset > 0 ) {
					scrollOffset = 0;
				}
				var elm = document.getElementById("mealDetails");
				elm.style.top = scrollOffset;
			}
			
			function getRealItemsHeight(){
				var elm = document.getElementById("mealDetails");
				var numItems = elm.childNodes.length;
				var i;
				var total = 0;
				
				for(i=0;i<numItems;i++){
					total += elm.childNodes[i].offsetHeight;
				}
				
				return total;
			}
			
			function scrollItems(dir){
				
				var realHeight = getRealItemsHeight();
				var newScroll = scrollOffset + (10*dir);
				
				if(newScroll <= (90-realHeight) || newScroll>=10){
					
					updateButtons();
					return;
				}
	
				scrollOffset =newScroll;
				var elm = document.getElementById("mealDetails");
				elm.style.top = scrollOffset;
				
				updateButtons();
			}
			
			function resetScrollState(){
				scrollOffset = 0;
				var elm = document.getElementById("mealDetails");
				elm.style.top = scrollOffset;
			}
			
			function updateButtons(){
				var realHeight = getRealItemsHeight();
				var up = document.getElementById("upButton");
				var down = document.getElementById("downButton");
				
				up.style.visibility = "hidden";
				down.style.visibility = "hidden";
				
				if(scrollOffset < 0){
					//enable up
					up.style.visibility = "visible";
				}
				
				if (realHeight > 110) {
					
					if (scrollOffset-10 >= (90-realHeight)) {
						//enable down
						
						down.style.visibility = "visible";
					}
				}
			}
			
//load();


</script>

<center>	
			<div id="menu_div" style='height:23px;'></div>
			<div style='height:10px;'></div>
			<table width="270" border="0" cellspacing="0" cellpadding="0" ID="Table1">
				<tr>
					<td height="36" class="greentop_back"><table width="270" border="0" cellspacing="0" cellpadding="0" ID="Table2">
							<tr>
								<td width="5"><img class="transparent" width="5" height="5" /></td>
								<td><span class="style1">You Used <span id="dailyAmount">0</span> Calories<br />
										out of your <span id="recommended">0</span> <span onclick="openSettings();" style="cursor:pointer;" title="*Avg calorie intake recommended for weight maintenance. Click to enter your settings">
											*daily</span> amount</span></td>
								<td width="60"><table width="60" height="30" border="0" cellpadding="0" cellspacing="0" ID="Table3">
										<tr>
											<td onclick="openSettings();" style="cursor:pointer;"><div align="right" class="style4">Settings</div>
											</td>
										</tr>
										<tr>
											<td onclick="resetAll();" style="cursor:pointer;"><div align="right" class="style4">Reset</div>
											</td>
										</tr>
									</table>
								</td>
								<td width="5"><img class="transparent" width="5" height="5" /></td>
							</tr>
						</table>
					</td>
				</tr>
				<tr>
					<td><img id="yellow_meter" width="270" height="7" /></td>
				</tr>
				<tr>
					<td><table width="270" border="0" cellspacing="0" cellpadding="0" id="mealButtons">
							<tr>
								<td width="166"class="light_blue_back_bg"><img style="cursor:pointer;" id="meal0" onclick="changeMeal(0);" width="55"
										height="12" /><img style="cursor:pointer;" id="meal1" onclick="changeMeal(1);" width="39"
										height="12" /><img style="cursor:pointer;" id="meal2" onclick="changeMeal(2);" width="37"
										height="12" /><img style="cursor:pointer;" id="meal3" onclick="changeMeal(3);" width="30"
										height="12" /></td>
								<td width="104" class="dark_blue_back"><img id="dark_blue_back" width="9" height="9" /></td>
							</tr>
						</table>
					</td>
				</tr>
				<tr>
					<td>
						<table ID="otherTables" style="BACKGROUND-COLOR: #46b1e2" width="260" height="170" border="0"
							cellspacing="0" cellpadding="0">
							<tr>
								<td width="161" valign="top" class="light_blue_back_bg">
									<!-- Select dish table-->
									<table width="166" border="0" cellspacing="0" cellpadding="0" ID="SelectionTable">
										<tr>
											<td colspan="5"><img class="transparent" width="5" height="10" /></td>
										</tr>
										<tr>
											<td width="5"><img class="transparent" width="5" height="5" /></td>
											<td><img style="cursor:pointer;" onclick="goToDish(0);" id="maindish_icon" width="52" height="62" /></td>
											<td><img style="cursor:pointer;" onclick="goToDish(1);" id="sidedish_icon" width="52" height="62" /></td>
											<td><img style="cursor:pointer;" onclick="goToDish(2);" id="toppings_icon" width="52" height="62" /></td>
											<td width="5"><img class="light_blue_back" width="5" height="9" /></td>
										</tr>
										<tr>
											<td width="5">&nbsp;</td>
											<td><img style="cursor:pointer;" onclick="goToDish(3);" id="dessert_icon" width="52" height="62" /></td>
											<td><img style="cursor:pointer;" onclick="goToDish(4);" id="dairy_icon" width="52" height="62" /></td>
											<td><img style="cursor:pointer;" onclick="goToDish(5);" id="beverages_icon" width="52" height="62" /></td>
											<td width="5">&nbsp;</td>
										</tr>
									</table>
									<!-- Add food item table-->
									<table width="166" border="0" cellspacing="0" cellpadding="0" ID="MealSelect" style="display:none;">
										<tr>
											<td width="5"><img class="transparent" width="5" height="5" /></td>
											<td width="52"><img id="SelectedDish" width="52" height="62" /></td>
											<td width="104"><img id="swithcto_title" width="42" height="9" /><br />
												<select name="select" class="style8" ID="DishSelector" onchange="goToDish(-1);">
													<option selected value="0">Main Dish</option>
													<option value="1">Side Dish</option>
													<option value="2">Toppings</option>
													<option value="3">Desserts</option>
													<option value="4">Dairy</option>
													<option value="5">Beverages</option>
												</select>
											</td>
											<td width="5"><img class="light_blue_back" width="5" height="9" /></td>
										</tr>
										<tr>
											<td width="5">&nbsp;</td>
											<td valign="top" colspan="2">
												<table width="156" border="0" cellspacing="0" cellpadding="0" ID="Table7">
													<tr>
														<td><img class="transparent" width="5" height="5" /></td>
													</tr>
													<tr>
														<td align="center"><select onchange="setUnit();" name="select_food" class="style8" id="select_food">
																<option selected>Select Food...</option>
															</select></td>
													</tr>
													<tr>
														<td><img class="transparent" width="5" height="5" /></td>
													</tr>
													<tr>
														<td align="left" class="style1"><span style="font-weight:normal" id="unitStr">Unit:</span></td>
													</tr>
													<tr>
														<td><img class="transparent"width="5" height="5" /></td>
													</tr>
													<tr>
														<td align="left" class="style1">Amount:
															<select name="select_amount" class="style8" id="select_amount">
																<option id="defaultAmount" value="1">1</option>
																<option value="1.5">1.5</option>
																<option value="2">2</option>
																<option value="2.5">2.5</option>
																<option value="3">3</option>
																<option value="3.5">3.5</option>
																<option value="4">4</option>
																<option value="4.5">4.5</option>
																<option value="5">5</option>
															</select></td>
													</tr>
													<tr>
														<td><img class="transparent" width="5" height="10" /></td>
													</tr>
													<tr>
														<td><div align="center"><img style="cursor:pointer;" onclick="addMealItem();" id="add_button" width="29" height="11" /></div>
														</td>
													</tr>
												</table>
											</td>
											<td width="5">&nbsp;</td>
										</tr>
									</table>
								</td>
								<td width="104" id="eee" height="170" valign="top" class="dark_blue_back">
									<table width="104" height="170" border="0" cellspacing="0" cellpadding="0" ID="MealDetail">
										<tr>
											<td width="5" id="ttt" class="dark_blue_back"><img class="transparent" width="5" height="5" /></td>
											<td width="94" valign="top"><table width="94" border="0" cellspacing="0" cellpadding="0" ID="Table8">
													<tr>
														<td id="MealTitle" class="style16"></td>
													</tr>
													<tr>
														<td><div align="center"><img onclick="scrollItems(1);" id="upButton" width="84" height="13" /></div>
														</td>
													</tr>
													<tr>
														<td>
															<div style="position:absolute;overflow:hidden;height:120px;">
																<div style="position:relative;" id="mealDetails" cellpadding="0" cellspacing="0">
																</div>
															</div>
														</td>
													</tr>
													<tr>
														<td  id="ttttt" class="dark_blue_back">
															<div style="position:absolute;top:251px;" id="downButton"><img class="transparent" width="5" height="5" /><img onclick="scrollItems(-1);" id="scroll_down" />
															</div>
														</td>
													</tr>
												</table>
											</td>
											<td width="5"></td>
										</tr>
										
									</table>
								</td>
							</tr>
						</table>
					</td>
				</tr>
				<tr>
					<td><a href="http://www.labpixies.com/gadget_page.php?id=31" target="_blank"><img border="0" id="bottomGif" /></a><img border="0" id="Img1" /></td>
				</tr>
			</table>
						
			<div style="width:100%; margin-top:5px;" align="center">
						<script type="text/javascript">
	             GA_googleFillSlot("calorie_calculator_txt");
	          </script>
			</div>
			
			<div ID="settingsTable" style="width:190px; height:190px;position:relative;top:-277px; display:none;">
				<table width="190" height="190" border="0" cellpadding="0" cellspacing="0" class="tableborder" ID="Table5">
					<tr>
						<td bgcolor="#007236"><table width="190" border="0" cellpadding="0" cellspacing="0" ID="Table6">
								<tr>
									<td width="10"><div align="right"></div>
									</td>
									<td valign="top"><div align="right">
											<table width="166" border="0" cellspacing="0" cellpadding="2" ID="Table9">
												<tr>
													<td><div align="right"><span onclick="closeSettings(0);" style="cursor:pointer;" class="style15">close</span></div>
													</td>
												</tr>
												<tr>
													<td valign="middle"><span class="style10">Age: <input name="age" type="text" class="style3" size="5" ID="age" />
														</span>
													</td>
												</tr>
												<tr>
													<td valign="middle"><span class="style10">Gender: </span><span class="style5"><span class="style4">
																<input name="radiobutton" type="radio" value="radiobutton" ID="maleGender" /> male
																<input name="radiobutton" type="radio" value="radiobutton" ID="femaleGender" /> 
																female</span> </span>
													</td>
												</tr>
												
												<tr>
													<td class="style15">
														<div align="right" id="switchToText" onclick="toggleSystem();" style="cursor:pointer;">Switch to Metric system</div>
													</td>
												</tr>
												<tr>
												</tr>
												<tr>
													<td>
														<table width="166" border="0" cellspacing="0" cellpadding="0" ID="standardTable">
															<tr>
																<td height="22"><span class="style10">Weight:</span></td>
																<td><span class="style10"> <input name="standardWeight" type="text" class="style11" size="5" ID="standardWeight" />
																	</span><span class="style12">Lbs</span></td>
															</tr>
															<tr style="PADDING-TOP: 2px">
																<td height="22"><span class="style10">Height:</span></td>
																<td><span class="style10"> <input maxlength="5" value="0" name="feet" type="text" class="style11" size="3" ID="feet" />
																	</span><span class="style12">Ft&nbsp;<span class="style10"> <input value="0" name="inches" type="text" class="style11" size="3" ID="inches" />
																		</span>In</span></td>
															</tr>
														</table>
														<table style="display:none;" width="166" border="0" cellspacing="0" cellpadding="0" ID="metricTable">
															<tr>
																<td height="22"><span class="style10">Weight:</span></td>
																<td><span class="style10"> <input value="0" name="metricWeight" type="text" class="style11" size="5" ID="metricWeight" />
																	</span><span class="style12">Kilos</span></td>
															</tr>
															<tr style="PADDING-TOP: 2px">
																<td height="22"><span class="style10">Height:</span></td>
																<td><span class="style10"> <input name="metricHeight" value="0" type="text" class="style11" size="3" ID="metricHeight" />
																	</span><span class="style12">Centimeters<span class="style10"></td>
															</tr>
														</table>
													</td>
												</tr>
												
												<tr>
													<td><span class="style10">Activity Level: </span>
													</td>
												</tr>
												<tr>
													<td>
														<select name="activityLevel" class="style11" ID="activityLevel">
															<option value="1.0" >No Exercise</option>
															<option value="1.2" >Little Exercise</option>
															<option value="1.375">Exercise 3 times a week</option>
															<option value="1.4625">Exercise 5 times a week</option>
															<option value="1.6375">Exercise Every day</option>
														</select>
													</td>
												</tr>
												
												<tr>
													<td><div align="center"><img onclick="closeSettings(1);" style="cursor:pointer;" id="save" width="40" height="21" /></div>
													</td>
												</tr>
											</table>
										</div>
									</td>
									<td width="10">&nbsp;</td>
								</tr>
							</table>
						</td>
					</tr>
				</table>
			</div>
		</center>
		<script type="text/javascript">
		    var mMENU = _IG_GetCachedUrl("http://cdn.labpixies.com/infra/js/lp_footer.js");
		  document.write('<scr'+'ipt type="text/javascript" src="'+mMENU+'"></scr'+'ipt>');
		</script>
		<!-- init module -->
		<script type="text/javascript">

            /*----------------------------------------------------------------------------------------------------*/
			var lp_pageTracker = _gat._getTracker("UA-345375-1");
			lp_pageTracker._initData();

			function lp_trackEvent(eventName, eventLable, eventVar) {
				try {
					//alert(eventName + ' - ' + eventLable);
					lp_pageTracker._trackEvent("Calorie Calculator - V1",eventName,eventLable,eventVar);
				} catch(ee) {}
			}
			/*----------------------------------------------------------------------------------------------------*/
	
            function deploy_gadget()
			{
				load();
				//lpgadgets.lp.menu.deploy("menu_div",{"textDirection":"__MSG_tdDir__","lang":"__MSG_lang__"});
				_IG_AdjustIFrameHeight();
			}
			
			_IG_RegisterOnloadHandler(deploy_gadget);

			_IG_Analytics("UA-345375-1", "/calories_v1");
		</script>
    <iframe width="1" height="1" style="width:1px; height:1px; overflow:hidden; position:absolute; visibility:hidden;" src="http://static.labpixies.com/campaigns/calories/analytics.html"></iframe>
]]>
</Content>
</Module>
