var RE_WEIGHT = /^[1-9][0-9]{1,2}$/;
var starting_weight;
var goal_weight;
var eventType = "mousedown";
var dietTargetDatePicker;
var weight_chart;
var food_chart;
var burn_chart;
var myHost = 'http://' + window.location.hostname;
var onBackground  = '#FFF url("' + myHost + '/css/custom-theme/images/verify.png") no-repeat left center';


jQuery(function($){
	//$(document).bind( eventType, function(){blurWeight('starting');blurWeight('target1');});
	$(document).bind( eventType, function(){blurWeight('starting');});
   $('#starting_weight').bind(eventType, function(event){event.stopPropagation();})
   $('#target1_weight').bind(eventType, function(event){event.stopPropagation();})
   $('.wght_links a').bind(eventType, function(event){event.stopPropagation();})
});

function displayNoDietMsg(){
	if($('#hg_welcomePopUp').length > 0)
		closeWelcomePopUp();
	var myLoc = new String(window.location)
    confirmation_dialog.html("Looks like you haven't chosen a diet yet. Take a look at our selection of diets and <a href='/diets'>find one that fits you!</a>");
    confirmation_dialog.dialog('option', 'buttons', {
            "Close": function(){$(this).dialog("close");if(myLoc.search("\/my-diet\/$")== -1){window.location='/my-diet/';}}
    });
    confirmation_dialog.dialog('option', 'title', 'Oops...');
	if(confirmation_dialog.next().children('button')){
		confirmation_dialog.next().children('button').each(
			function(){	
				if($(this).text().indexOf('Close')!= -1){
					$(this).addClass('hg_cancelButton');
				}
			}
		);
	}
    confirmation_dialog.dialog('open');
    return false;
}

function openDietPhaseDialog(){
  $("#diet-phase-dialog-inner").load(
      "/ajax/ajax.my-diet.php",
      {action: 'get_diet_phase_dialog'},
      function(){
          $("#diet-phase-dialog").dialog('open');
      }
    );
}

$(document).ready(function(){

    $('#diet-phase-dialog').dialog({
            autoOpen: false,
            modal: true,
            width: 500,
            draggable: true,
            resizable: false,
            zIndex: 9,
            buttons: {
                    "Cancel": function() {
                            $(this).dialog("close");
                    },
                    "Update Phase": function() {
                           $(this).dialog("close");
                           document.dietPhaseFrm.submit();

                    }
            }
    });
	if($('#diet-phase-dialog').next().children('button')){
		$('#diet-phase-dialog').next().children('button').each(
			function(){	
				if($(this).text().indexOf('Cancel')!= -1){
					$(this).addClass('hg_cancelButton');
				}
			}
		);
	}
	
})

$('input#starting_weight').css('cursor','default');
$('input#target1_weight').css('cursor','default');

function editWeight(val){
    if(val=='starting')
        blurWeight('target');
    else
        blurWeight('starting');
    $('#'+val+'_edit').hide();
    $('#'+val+'_save').show();
	$('input#'+val+'_weight').css('cursor','text');
	$('input#'+val+'_weight').css('background','url(/images/bg_weight.png) no-repeat');
    window[val + '_weight'] = $('input#'+val+'_weight').val();
    $('input#'+val+'_weight').attr('readonly',false);
    $('input#'+val+'_weight').val('');
    $('input#'+val+'_weight').focus();
}
function blurWeight(val, displayVal){
   if(val == 'todays')
		$('input#'+val+'_weight').css('color','#A9A9A9');
	$('#'+val+'_save').hide();
    $('#'+val+'_edit').show();
    if(!displayVal)
		$('input#'+val+'_weight').val(window[val + '_weight']);
	else
		$('input#'+val+'_weight').val(displayVal);
    $('input#'+val+'_weight').attr('readonly',true);
	$('input#'+val+'_weight').css('cursor','default');
	if(val != 'todays')
		$('input#'+val+'_weight').css('background','#CCCCCC');
	$('input#'+val+'_weight').blur();
	
}
function saveWeight(val){
    var weight = $('input#'+val+'_weight').val();
	 if(!RE_WEIGHT.test(weight)){
		if(val == 'target1')
			valToDisplay = 'Goal'
		else
			valToDisplay = val
        alert('Please provide a valid '+valToDisplay+' weight.');
           blurWeight(val);
        return false;
    }

    $.ajax({
            type: "POST",
            url: "/ajax/ajax.my-diet.php",
            data: 'action=edit_'+val+'_weight&weight=' + weight,
            success: function(bmi) {                
                $('#'+val+'_save').hide();
                $('#'+val+'_edit').show();
                $('input#'+val+'_weight').val(weight + 'lbs');
                $('input#'+val+'_weight').attr('readonly',true);
                window[val + '_weight'] = $('input#'+val+'_weight').val();
                
                if(val == 'starting'){                    
                    var start_data = [[one_year_date,weight],[current_date,weight]];                   
                    weight_chart.series[1].data = start_data;                    
                    weight_chart.replot();
                }
                else if(val == 'target1'){
                    var target_data = [[one_year_date,weight],[current_date,weight]];
                    weight_chart.series[2].data = target_data;                    
                    weight_chart.replot();
                }
                updateBmiPointer(val, bmi);
            }
        });
		blurWeight(val);
    return true;
}

function saveCurrentWeight(){    
    var weight = $('input#todays_weight').val();
    if(!RE_WEIGHT.test(weight)){
        alert('Please provide a valid weight.');
       blurWeight('todays', 'Enter current weight');
        return;
    }
    $.ajax({
        type: "POST",
        url: "/ajax/ajax.my-diet.php",
        data: 'action=add_current_weight&weight=' + weight,
        dataType: 'json',
        success: function(data) {
            blurWeight('todays');
			$('#logged_notice').show();
			$('#logged_notice').css('filter','');
			$('#logged_notice').css('background', '#CCCCCC');
			 $("#logged_notice").fadeOut(5000);
			$('input#todays_weight').val("Enter current weight");
            $('input#current_weight').val(weight + 'lbs');
            $('#tp_cur_weight').html(weight);
            weight_chart.series[0].data = data.weights;
            weight_chart.replot(); //{resetAxes:["y2axis"]});
            // weight_chart.drawSeries(0);
            $('#tp_bmi_display').html(data.bmi);
            updateBmiPointer('current', data.bmi); 
			
    }
    }); 
	//document.reload();
}

function updateActivityLevel(val){

    $.ajax({
        type: "POST",
        url: "/ajax/ajax.my-diet.php",
        dataType: 'json',
        data: 'action=update_activity_level&level_id=' + val,
          success: function(data) {
               // $('#cal_needs').html( data.daily_calorie_needs);
               location.reload(true);
         }
    });
}


var save_target_date = function(y,m,d) {
        var real_format = "yyyy-MM-dd";
        // var display_format = "M/d/yyyy";

        var date = formatDate(new Date(y,m-1,d),real_format);
        // var display_value = formatDate(new Date(y,m-1,d),display_format);

        $.ajax({
                type: "POST",
                url: "/ajax/ajax.my-diet.php",
                data: 'action=edit_target_date&date=' + date,
                success: function(html) {
                    $('#target_date').html(html);
                }
            });


};


function saveTargetDate(dateText, inst) {
    $.ajax({
        type: "POST",
        url: "/ajax/ajax.my-diet.php",
        data: 'action=edit_target_date&date=' + dateText,
        success: function(html) {
            $('#target_date').html(html);
        }
    });
};


$(document).ready(function(){
   dietTargetDatePicker = $('#hid_target_date').datepicker({
       dateFormat: 'yy-m-d',
       minDate: today,
       onSelect: saveTargetDate

   });
});

/*
 *  This function defines the JqPlotChart 'class' and is used to output each of the Weight charts.
 *
 */
//function JqPlotChart(element, data, ticks, tickColors){
//    this.element = element ;
//    this.data = data;
//    this.options = '';
//    this.plot = null;
//    this.d = new Date();
//    this.current_date = this.d.getFullYear()+'-'+(this.d.getMonth()+1)+'-'+this.d.getDate();
//
//    this.setOptions= function(min_date){
//
//        this.options = {
//
//                axesDefaults: {
//                    show: false,    // wether or not to renderer the axis.  Determined automatically.
//                    min: null,      // minimum numerical value of the axis.  Determined automatically.
//                    max: null,      // maximum numverical value of the axis.  Determined automatically.
//                    pad: 1.2,       // a factor multiplied by the data range on the axis to give the
//                                    // axis range so that data points don't fall on the edges of the axis.
//                    ticks: [],      // a 1D [val1, val2, ...], or 2D [[val, label], [val, label], ...]
//                                    // array of ticks to use.  Computed automatically.
//                    numberTicks: 7,  // undefined,
//                    renderer: $.jqplot.LinearAxisRenderer,  // renderer to use to draw the axis,
//                    rendererOptions: {},    // options to pass to the renderer.  LinearAxisRenderer
//                                            // has no options,
//                    tickOptions: {
//                        mark: 'outside',    // Where to put the tick mark on the axis
//                                            // 'outside', 'inside' or 'cross',
//                        showMark: true,
//                        showGridline: true, // wether to draw a gridline (across the whole grid) at this tick,
//                        markSize: 4,        // length the tick will extend beyond the grid in pixels.  For
//                                            // 'cross', length will be added above and below the grid boundary,
//                        show: true,         // wether to show the tick (mark and label),
//                        showLabel: true,    // wether to show the text label at the tick,
//                        tickColors: tickColors ? tickColors : null,
//                        formatString: ''   // format string to use with the axis tick formatter
//                    },
//                    showTicks: true,        // wether or not to show the tick labels,
//                    showTickMarks: true    // wether or not to show the tick marks
//                },
//
//
//                seriesDefaults: {
//                    // xaxis: 'xaxis', // either 'xaxis' or 'x2axis'.
//                    yaxis: 'y2axis' // either 'yaxis' or 'y2axis'.
//                },
//
//                // title:'Data Point Highlighting',
//                series:[{color:'#FF9933'}],
//                axes:{
//                    xaxis:{
//                        renderer:$.jqplot.DateAxisRenderer,
//                        rendererOptions:{tickRenderer:$.jqplot.CanvasAxisTickRenderer},
//                        tickOptions:{
//                            formatString:'%b %#d', // , %y',
//                            fontSize:'7pt',
//                            fontFamily:'Tahoma',
//                            color: '#cccccc'
//                            // angle: 30
//                        },
//                        min: min_date,
//                        max: this.current_date
//
//                    },
//                    y2axis:{
//                        rendererOptions:{tickRenderer:$.jqplot.CanvasAxisTickRenderer},
//                        tickOptions:{
//                            formatString:'%.0f',
//                     		fontSize:'7pt',
//                            fontFamily:'Tahoma',
//                            color: '#cccccc'
//                        },
//                         min: 0
//
//                    }
//                },
//                highlighter: {sizeAdjust: 7.5},
//                cursor: {show: false},
//                grid: {
//                    drawGridLines: true,        // wether to draw lines across the grid or not.
//                    gridLineColor: '#cccccc',    // *Color of the grid lines.
//                    background: '#ffffff',      // CSS color spec for background color of grid.
//                    borderColor: '#999999',     // CSS color spec for border around grid.
//                    borderWidth: 0,           // pixel width of border around grid.
//                    shadow: false,               // draw a shadow for grid.
//                    shadowAngle: 45,            // angle of the shadow.  Clockwise from x axis.
//                    shadowOffset: 1.5,          // offset from the line of the shadow.
//                    shadowWidth: 3,             // width of the stroke for the shadow.
//                    shadowDepth: 3,             // Number of strokes to make when drawing shadow.
//                                                // Each stroke offset by shadowOffset from the last.
//                    shadowAlpha: 0.07  ,         // Opacity of the shadow
//                    renderer: $.jqplot.CanvasGridRenderer,  // renderer to use to draw the grid.
//                    rendererOptions: {}         // options to pass to the renderer.  Note, the default
//                                                // CanvasGridRenderer takes no additional options.
//                }
//            }
//
//    }
//
//    this.show = function(){
//       this.plot = $.jqplot(this.element, [this.data], this.options);
//    }
//
//    this.reInitialize = function(data){
//       this.data = data;
//       this.show();
//    }
//}



/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr,doAlert){
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf(dtCh)
    var pos2=dtStr.indexOf(dtCh,pos1+1)
    var strMonth=dtStr.substring(0,pos1)
    var strDay=dtStr.substring(pos1+1,pos2)
    var strYear=dtStr.substring(pos2+1)
    doAlert = doAlert ? true : false;
    strYr=strYear
    if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
            if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
    }
    month=parseInt(strMonth)
    day=parseInt(strDay)
    year=parseInt(strYr)
    if (pos1==-1 || pos2==-1){
            if(doAlert) alert("The date format should be : mm/dd/yyyy");
            return false;
    }
    if (strMonth.length<1 || month<1 || month>12){
            if(doAlert) alert("Please enter a valid month");
            return false;
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
            if(doAlert) alert("Please enter a valid day");
            return false;
    }
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
            if(doAlert) alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
            return false;
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
            if(doAlert) alert("Please enter a valid date");
            return false;
    }
    return true
}

function validateDate(dtStr){
	return isDate(dtStr,false);
}



/*
 *  ************************ SECTION FOR THE FOOD TRACKER *****************************************************
 */
var foodTabDatepick;
var foodTabSelectedDate
var ateFoodDate;
var foodDatePick;

$(function() {
        foodTabDatepick = $("#hid-food-date").datepicker({
            /* - only work for input field -
             * altField: '#workoutDateDisplay',
             * altFormat: 'mm/dd/y', */
            dateFormat: 'yy-mm-dd',
            maxDate: today,
            onSelect: function(dateText, inst) {
                updateFoodTab('#date-foods',dateText);
                //Set a new var with different format to use
                var newFormat = $.datepicker.formatDate("M-d-y", $(this).datepicker('getDate'));
                $("#foodDateDisplay").html(newFormat);
                // create date object with selected date.
                foodTabSelectedDate = new Date($(this).datepicker('getDate'));
            }
        });

        var result_cnt;
        $("#foodselectinput").autocomplete({
                // TODO doesn't work when loaded from /demos/#autocomplete|remote
                // source: "/ajax/ajax.food_search.php",
                minLength: 3,
                selectFirst: true,
                extraParams: {bar: 4},
                select: function(event, ui) {
                    openFoodDialog(ui.item.id);
                       // openFoodDialog(ui.);
                },
                open:  function(event, ui){

                     var element = jQuery(this).autocomplete( "widget" );
                    
                    if(result_cnt==0){
                       var noResDiv = jQuery('<div></div>').html('no results found').attr('id', "autocomplete_noresults");
                        jQuery(element).append(noResDiv);
                        // jQuery(element).height( jQuery(noResDiv).height());
                    }else{
                        var newDv = jQuery('<div></div>').html('<a id="more_results">More Results ...</a>').attr('id', "autocomplete_footer");
                        jQuery(element).append(newDv); //.height(  jQuery(element).height()  +   jQuery(newDv).height()   );
                    }
                    
                },                
                source: function(req, add){
                     //pass request to server
                     $.getJSON("/ajax/ajax.food_search.php?action=autocomplete&callback=?", req, function(data) {
                         result_cnt = 0;
                         //create array for response objects
                         var suggestions = [];
                         if(data.result.total > 0){
                             //process response
                             $.each(data.result.foods, function(i, food){
                                result_cnt++;
                                var markup = food.name
                                    + (( food.description && food.description != null && food.description != '' ) ? " (" + food.description + ") " : "")
                                    + (( food.brand_name && food.brand_name != null && food.brand_name != '' ) ? " - " + food.brand_name : "");
                                suggestions.push({label: markup, value: markup, id: food.id});
                             });
                         }
                         //pass array to callback
                         add(suggestions);
                    });
                },
                close: function(){$(this).val('')}
        });


        $('#food-tracker-dialog').dialog({
            autoOpen: false,
            modal: true,
            width: 1000,
            draggable: true,
            resizable: false,
            zIndex: 9,
            open: function(){
                var ftoday = (today.getMonth() < 9 ? '0' : '') + (today.getMonth()+1) + '/' +
                             (today.getDate() < 10 ? '0' : '') + today.getDate() + '/' + today.getFullYear();
                $('#food-date').val(ftoday);
                $('#favs_chbk').checked = false;
            },
            beforeclose: function(){foodDatepick.datepicker('hide')},
            close: function(){$('#foodselectinput').val('');}
        });
		//setting up buttons in a function so that it can be redone after displaying confirmation without redundant code
		hg_setUpLogFoodButtons();
        $('#more-results-dialog').dialog({
            autoOpen: false,
            modal: true,
            width: 650,
            draggable: true,
            resizable: false,
            zIndex: 9,
            buttons: {
                "Cancel": function() {
                        $(this).dialog("close");
                }
            },
             open: function(){
                $('#foodselectinput').val('');
                $('#foodselectinput').autocomplete('close');
            },
            close: function(){$('#foodselectinput').val('');}
        });

        updateFoodTab('#todays-foods');
       // updateFoodTab('#yesterdays-foods',formatMysqlDate(yesterday));

        $("#more_results").live('click', openMoreResultsDialog)

});

function hg_setUpLogFoodButtons(){
	$('#food-tracker-dialog').dialog( "option", "buttons", 
		{
		 "Cancel": function() {
                        $(this).dialog("close");
                },
        "Log Food": function() {
                        if(!($("#food_tracker_dialog_qty").val() > 0) || !isNumeric($("#food_tracker_dialog_qty").val())){
                            alert("Please enter a numeric value for How Much.");
                            return false;
                        }
                        logAteFood();
						hg_verify();
						$("#foodselectinput").val('');
                }
        }
	 );
	if($('#food-tracker-dialog').next().children('button')){
		$('#food-tracker-dialog').next().children('button').each(
			function(){	
				if($(this).text().indexOf('Cancel')!= -1){
					$(this).addClass('hg_cancelButton');
				}
			}
		);
	}
}

function hg_verify(){
	
	$('#food-tracker-dialog').dialog( "option", "buttons", 
		{
			"Done": function(){
				return false; 
				}
				
								
		}
	 );
	if($('#food-tracker-dialog').next().children('button')){
		$('#food-tracker-dialog').next().children('button').each(
			function(){	
				if($(this).text().indexOf('Done')!= -1){
					$(this).addClass('hg_doneButton');
				}
			}
		);
	}
	//alert("out of loop, about to setTimeout");
	try{
		window.setTimeout(function(){$('.ui-dialog').fadeOut(1000, function() {window.setTimeout(function(){$('#food-tracker-dialog').dialog("close"); hg_setUpLogFoodButtons()}, 500);})}, 500);
	}
	catch(err){
		alert("error: " + err.description);
	}
	//window.setTimeout(function(){$('#food-tracker-dialog').dialog("close"); hg_setUpLogFoodButtons()}, 1000);
	//window.setTimeout(function(){$('#food-tracker-dialog').fadeOut('slow', function(){return false;});hg_setUpLogFoodButtons()}, 1000);

}

function openMoreResultsDialog() {    

    $("#more-results-dialog").load(
          "/ajax/ajax.food_search.php?action=more_results_dialog&keywords=" + escape($("#foodselectinput").val()),
          function(){               
                $(this).dialog('open');
          }
    );

    return false;
}

function openFoodDialogFromMoreResults(food_id) {
    $('#more-results-dialog').dialog('close');
    openFoodDialog(food_id);
}



function openFoodDialog(food_id) {
    if(!food_id)
        return;
    $("#food-tracker-dialog").load(
          "/ajax/ajax.my-diet.php",
          {action: 'get_food_dialog', food_id: food_id},
          function(){
				 foodDatepick = $("#food-date").datepicker({
                    maxDate: today,
                    showOn: 'both',
                    buttonImage: '/images/pic_calendar.png',
                    buttonImageOnly: true,
                    buttonText: 'Select the date you ate this food.',
                    onSelect: function(dateText, inst) {
                        ateFoodDate = new Date($(this).datepicker('getDate'));
                    }
                });
				$("#food-tracker-dialog").dialog('open');
          }
    );
}

// added this function for the "Choose This" page, so that when the user clicks "I Ate This", the default sizes in the dialog box are the ones of the chosen item  
function openFoodDialog_choose(food_id, qty, unit_id) {
    if(!food_id)
        return;
    $("#food-tracker-dialog").load(
          "/ajax/ajax.my-diet.php",
          {action: 'get_food_dialog_choose', food_id: food_id, qty: qty, unit_id: unit_id},
          function(){
				 foodDatepick = $("#food-date").datepicker({
                    maxDate: today,
                    showOn: 'both',
                    buttonImage: '/images/pic_calendar.png',
                    buttonImageOnly: true,
                    buttonText: 'Select the date you ate this food.',
                    onSelect: function(dateText, inst) {
                        ateFoodDate = new Date($(this).datepicker('getDate'));
                    }
                });
				$("#food-tracker-dialog").dialog('open');
          }
    );
}

function openRecipeDialog(recipe_id, qty) {
    if(!recipe_id)
        return;
    if(!qty)
       qty = 1;
	$('#food-tracker-dialog').dialog('option', 'title', 'Log Food');

    $("#food-tracker-dialog").load(
          "/ajax/ajax.my-diet.php",
          {action: 'get_recipe_dialog', recipe_id: recipe_id,  qty: qty},
          function(){
                foodDatepick = $("#food-date").datepicker({
                    maxDate: today,
                    showOn: 'both',
                    buttonImage: '/images/pic_calendar.png',
                    buttonImageOnly: true,
                    buttonText: 'Select the date you ate this food.',
                    onSelect: function(dateText, inst) {
                        ateFoodDate = new Date($(this).datepicker('getDate'));
                    }
                });
                $("#food-tracker-dialog").dialog('open');
          }
    );
}

function deleteAteFood(id, confirm_msg, element){
    confirmation_dialog.html(confirm_msg);  
    confirmation_dialog.dialog('option', 'buttons', {
            "No": function() {$(this).dialog("close");},
            "Yes": function(){
                    $.ajax({
                            type: "POST",
                            url: "/ajax/ajax.my-diet.php",
                            data: 'action=delete_ate_food&id=' + id,
                            dataType: 'json',
                            success: function(data) {
                                // $(element).parent(".TabbedPanelsContent").html(data);
                                $(element).parent().parent().parent().parent().html(data.html);
                                updateFoodChart(data.calories_ate);  
                            }
                        });
                    $(this).dialog("close");
             }
                    
    });
	if(confirmation_dialog.next().next().next().children('button')){
		confirmation_dialog.next().next().next().children('button').each(
			function(){	
				if($(this).text().indexOf('No')!= -1){
					$(this).addClass('hg_cancelButton');
				}
			}
		);
	}
    confirmation_dialog.dialog('open');   
}

function deleteAllFood(myDate, element){
    confirmation_dialog.html('You are about to delete all items for this day.<br/> Continue?');  
    confirmation_dialog.dialog('option', 'buttons', {
            "No": function() {$(this).dialog("close");},
            "Yes": function(){
                    $.ajax({
                            type: "POST",
                            url: "/ajax/ajax.my-diet.php",
                            data: 'action=delete_all_food&myDate=' + myDate,
                            dataType: 'json',
                            success: function(data) {
                                // $(element).parent(".TabbedPanelsContent").html(data);
                                $(element).parent().parent().parent().parent().html(data.html);
                                updateFoodChart(data.calories_ate);  
                            }
                        });
                    $(this).dialog("close");
             }
                    
    });
	if(confirmation_dialog.next().next().next().children('button')){
		confirmation_dialog.next().next().next().children('button').each(
			function(){	
				if($(this).text().indexOf('No')!= -1){
					$(this).addClass('hg_cancelButton');
				}
			}
		);
	}
    confirmation_dialog.dialog('open');   
}
function hg_deleteAteFoodMiniTracker(id, confirm_msg){
    confirmation_dialog.html(confirm_msg);  
    confirmation_dialog.dialog('option', 'buttons', {
            "No": function() {$(this).dialog("close");},
            "Yes": function(){
                    $.ajax({
                            type: "POST",
                            url: "/ajax/ajax.my-diet.php",
                            data: 'action=delete_ate_food_mini&id=' + id,
                            dataType: 'json',
                            success: function(data) {
                                // $(element).parent(".TabbedPanelsContent").html(data);
                                $('#hg_sidebar_mini_foodtracker').html(data.html);
                                updateFoodChart(data.calories_ate);  
                            }
                        });
                    $(this).dialog("close");
             }
                    
    });
	if(confirmation_dialog.next().children('button')){
		confirmation_dialog.next().children('button').each(
			function(){	
				if($(this).text().indexOf('No')!= -1){
					$(this).addClass('hg_cancelButton');
				}
			}
		);
	}
    confirmation_dialog.dialog('open');   
}
function hg_deleteAllFoodMiniTracker(){
    confirmation_dialog.html("You are about to delete all items for this day. <br/>Continue?");  
    confirmation_dialog.dialog('option', 'buttons', {
            "No": function() {$(this).dialog("close");},
            "Yes": function(){
                    $.ajax({
                            type: "POST",
                            url: "/ajax/ajax.my-diet.php",
                            data: 'action=delete_all_food_mini',
                            dataType: 'json',
                            success: function(data) {
                                // $(element).parent(".TabbedPanelsContent").html(data);
                                $('#hg_sidebar_mini_foodtracker').html(data.html);
                                updateFoodChart(data.calories_ate);  
                            }
                        });
                    $(this).dialog("close");
             }
                    
    });
	if(confirmation_dialog.next().children('button')){
		confirmation_dialog.next().children('button').each(
			function(){	
				if($(this).text().indexOf('No')!= -1){
					$(this).addClass('hg_cancelButton');
				}
			}
		);
	}
    confirmation_dialog.dialog('open');   
}

function logAteFood(){
     $.post(
         "/ajax/ajax.my-diet.php",
         $("#ate-food-form").serialize(),
         function(data){
             if(data.textcode =='today')
                 updateFoodTab('#todays-foods');
             else if(data.textcode =='yesterday')
                 updateFoodTab('#yesterdays-foods',formatMysqlDate(yesterday));
             else if(foodTabSelectedDate && ateFoodDate.getTime() == foodTabSelectedDate.getTime()){
                  updateFoodTab('#date-foods',formatMysqlDate(ateFoodDate));
             }
			 //if(typeof(hg_isFoodSearch) != 'undefined' || data.textcode == 'logged_meal'){
				 hg_updateMiniFoodTracker('#hg_sidebar_mini_foodtracker');
									
			 //}
			 
			// If HTML was returned, it is the updated Favorite Exercise list.
//            if(data.fav_exercise ){
//                $("#fav_exercise_ul").append('<li><a href="#" onclick="openExerciseDetailsDialog('+data.fav_exercise.fav_id+',\''+ data.fav_exercise.fav_name +'\'); return false;">'+
//                    data.fav_exercise.fav_name +'</a><a href="#" onclick="deleteFavExercise('+data.fav_exercise.fav_id+',\'You are about to delete '+ data.fav_exercise.fav_name +
//                    ' from your favorite exercises. <br> Are you sure?\'); return false;"><img src="/images/icon_del_x.png" alt="" width="15" height="15" /></li>');
//            }

            updateFoodChart(data.calories_ate);
         },
         'json'
     );
     return false;
}

function updateFoodChart(data){
    if(food_chart){
        food_chart.series[0].data = data;
        // food_chart.replot({resetAxes:["y2axis"]});
        food_chart.replot();
    }

}

function updateFoodTab(element, date){
    if(!date)
        date = '';
    $(element).load(
      "/ajax/ajax.my-diet.php",
      {action: 'update_food_tab',  date: date}
    );
}

function hg_updateMiniFoodTracker(element){
		if($(element).length == 0)
			return;
		$(element).load(
		 "/ajax/ajax.my-diet.php",
		  {action: 'update_mini_food_tracker'}
		);
	
}


function toggleNutritionCol(col,elem){
    $(elem).parents('.TabbedPanelsContent').find('.col'+col+'food').each( function(){
            $(this).hide();
            if($(this).hasClass(elem.value))
                $(this).show();
     });

     $(elem).parents('.TabbedPanelsContent').find('.cols5 > .col'+col).each( function(){
            $(this).hide();
            if($(this).hasClass(elem.value))
                $(this).show();
     });
}
/********************* END FOOD TRACKER SECTION **********************/

/*
 *  ************************ SECTION FOR THE EXERCISE TRACKER *****************************************************
 */

var exerciseDetailDatepick;
var workoutTabDatepick;
var today = new Date();
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
var tabSelectedDate;
var exerciseDetailDate;

function addExerciseDetail(){
     $.post(
         "/ajax/ajax.my-diet.php",
         $("#exercise-form").serialize(),
         function(data){        
             if(data.textcode =='today')
                 updateWorkoutTab('#todays-workouts');
             else if(data.textcode =='yesterday')
                 updateWorkoutTab('#yesterdays-workouts',formatMysqlDate(yesterday));
             else if(tabSelectedDate && exerciseDetailDate.getTime() == tabSelectedDate.getTime()){
                  updateWorkoutTab('#date-workouts',formatMysqlDate(exerciseDetailDate));                 
             }
            // If HTML was returned, it is the updated Favorite Exercise list.            
            if(data.fav_exercise ){               
//                $("#fav_exercise_ul").append('<li><a href="#" onclick="openExerciseDetailsDialog('+data.fav_exercise.fav_id+'); return false;">'+
//                    data.fav_exercise.fav_name +'</a><a href="#" onclick="deleteFavExercise('+data.fav_exercise.fav_id+',\'You are about to delete '+ data.fav_exercise.fav_name +
//                    ' from your favorite exercises. <br> Are you sure?\'); return false;"><img src="/images/delete_img.png" alt="" width="15" height="15" /></li>');
                $("#fav_exercise_ul").html(data.fav_exercise);
            }
            updateExerciseChart(data.calories_burned)
         },
         'json'
     );
     return false;
}


//function openDatepicker(){
//    exerciseDetailDatepick.datepicker('show');
//}

function openExerciseDialog(){
  $("#exercise-select-dialog").load(
      "/ajax/ajax.my-diet.php",
      {action: 'get_exercise_dialog'},
      function(){
          $("#exercise-select-dialog").dialog('open');
      }
    );  
}

function openExerciseDetailsDialog(id){ // , is_fav, minutes, intensity ){
    $("#exercise-select-dialog").dialog('close');

    $("#exercise-details-dialog").load(
        "/ajax/ajax.my-diet.php",
        {action: 'get_exercise_detail_dialog', id: id, name: name},
        function(){
            exerciseDetailDatepick = $("#exercise-date").datepicker({
                maxDate: today,
                showOn: 'both',
                buttonImage: '/images/pic_calendar.png',
                buttonImageOnly: true,
                buttonText: 'Select the date of your exercise.',
                onSelect: function(dateText, inst) {
                    exerciseDetailDate = new Date($(this).datepicker('getDate'));
                }
            });
          $("#exercise-details-dialog").dialog('open');
        }
    );

    // $("#exercise-details-dialog").dialog('open');
    // $("#hid-exercise-id").val(id);
    // $("#exercise-name").html(name);
}

function formatMysqlDate(date1) {
    return date1.getFullYear() + '-' +
        (date1.getMonth() < 9 ? '0' : '') + (date1.getMonth()+1) + '-' +
        (date1.getDate() < 10 ? '0' : '') + date1.getDate();
}

function updateWorkoutTab(element, date){
    if(!date)
        date = '';
    $(element).load(
      "/ajax/ajax.my-diet.php",
      {action: 'update_workout_tab',  date: date}
    );
}

function deleteWorkout(id, confirm_msg, element){
    confirmation_dialog.html(confirm_msg);   
    confirmation_dialog.dialog('option', 'buttons', {                    
                    "No": function() {$(this).dialog("close");},
                    "Yes": function(){
                            $.ajax({
                                    type: "POST",
                                    url: "/ajax/ajax.my-diet.php",
                                    data: 'action=delete_workout&id=' + id,
                                    dataType: 'json',
                                    success: function(data) {
                                        // $(element).parent(".TabbedPanelsContent").html(data);
                                        $(element).parent().parent().parent().parent().html(data.html);
                                        updateExerciseChart(data.calories_burned);
                                    }
                                });
                            $(this).dialog("close");
  		  }
    });
	if(confirmation_dialog.next().children('button')){
		confirmation_dialog.next().children('button').each(
			function(){	
				if($(this).text().indexOf('No')!= -1){
					$(this).addClass('hg_cancelButton');
				}
			}
		);
	}
    confirmation_dialog.dialog('open');   
}

function updateExerciseChart(data){
    burn_chart.series[0].data = data;
    // food_chart.replot({resetAxes:["y2axis"]});
    burn_chart.replot();

}

function deleteFavExercise(id, confirm_msg){
    confirmation_dialog.html(confirm_msg);    
    confirmation_dialog.dialog('option', 'buttons', {                    
                    "No": function() {$(this).dialog("close");},
                    "Yes": function(){
                            $('#fav_exercise_ul').load(
                                    "/ajax/ajax.my-diet.php",
                                    {action: 'delete_fav_exercise', exercise_id: id}
                            );
                            $(this).dialog("close");
                     }
    });
	if(confirmation_dialog.next().children('button')){
	
		confirmation_dialog.next().children('button').each(
			function(){	
				if($(this).text().indexOf('No')!= -1){
					$(this).addClass('hg_cancelButton');
				}
			}
		);
	}
    confirmation_dialog.dialog('open');
}

$(document).ready(function(){
    
    workoutTabDatepick = $("#hid-date-hold").datepicker({
        /* - only work for input field -
         * altField: '#workoutDateDisplay',
         * altFormat: 'mm/dd/y', */
        dateFormat: 'yy-mm-dd',
        maxDate: today,
        onSelect: function(dateText, inst) {
            updateWorkoutTab('#date-workouts',dateText);
            //Set a new var with different format to use
            var newFormat = $.datepicker.formatDate("M-d-y", $(this).datepicker('getDate'));
            $("#workoutDateDisplay").html(newFormat);    
            // create date object with selected date.
            tabSelectedDate = new Date($(this).datepicker('getDate'));           
        }
    });
 $('#exercise-select-dialog').dialog({
            autoOpen: false,
            modal: true,
            width: 1000,
            draggable: true,
            resizable: false,
            zIndex: 9
    });
 $('#exercise-details-dialog').dialog({
            autoOpen: false,
            modal: true,
            width: 800,
            draggable: true,
            resizable: false,
            zIndex: 9,
            open: function(){
                        var ftoday = (today.getMonth() < 9 ? '0' : '') + (today.getMonth()+1) + '/' +
                                     (today.getDate() < 10 ? '0' : '') + today.getDate() + '/' + today.getFullYear();
                        $('#exercise-date').val(ftoday);
                        $('#favs_chbk').checked = false;
            },
            beforeclose: function(){exerciseDetailDatepick.datepicker('hide')}

    });
	hg_setUpExerciseButtons();
    updateWorkoutTab('#todays-workouts');
    updateWorkoutTab('#yesterdays-workouts',formatMysqlDate(yesterday));

});

function hg_setUpExerciseButtons(){
	 $('#exercise-details-dialog').dialog("option", "buttons",{
		"Cancel": function() {
				$(this).dialog("close"); 
			},
        "Log Exercise":function(){  
						addExerciseDetail();
                        hg_verifyExercise();
				}
        }
	 );
	 $('#exercise-details-dialog').next().children('button').each(
					function()
					{	
						if($(this).text().indexOf('Cancel')!= -1){
							$(this).addClass('hg_cancelButton');
						}
					}
	);
}


function hg_verifyExercise(){
	$('#exercise-details-dialog').dialog( "option", "buttons", 
		{
			"Done": function(){
				return false; 
				}
		}
	 );
	if($('#exercise-details-dialog').next().children('button')){
		$('#exercise-details-dialog').next().children('button').each(
					function()
					{	
						if($(this).text().indexOf('Done')!= -1){
							$(this).css('background', onBackground);
							$(this).css('width', '100px');
							$(this).css('color', '#339933');
							$(this).css('border', 'none');
						}
						
					}
					);
	}
	try{
		window.setTimeout(function(){$('.ui-dialog').fadeOut(1000, function() {window.setTimeout(function(){$('#exercise-details-dialog').dialog("close"); hg_setUpExerciseButtons();}, 500);})}, 500);
	}
	catch(err){
		alert("error: " + err.description);
	}
}
/********************* END EXERCISE TRACKER SECTION **********************/

/********************* BMI CHART SECTION START ***************************/

function updateBmiPointer(pointer, percent){
    var element;
    if(pointer == "starting"){
        element = $("#bmi_red");
    }
    else if(pointer == "target"){
        element = $("#bmi_green");
    }
    else if(pointer == "current"){
        element = $("#bmi_yellow");
    }
    var placement;
    if(percent < 19){
       placement = (141/18.4) * percent;
    }else if(percent < 25){
       placement = ((141/6.5) * (percent-18.5 )) + 141;
    }
    else if(percent < 30){
       placement = ((141/4.9) * (percent-25)) + 282;
    }else{
       placement = ((141/10) * (percent-30)) + 423;
    }
    if(placement > 552)
        placement = 552;

    $(element).html(percent+"%");
    $(element).animate({left: placement+"px"},2000);

}


/********************* BMI CHART SECTION END ***************************/


//HADASSA GOLOVENSHITZ: STYLE CANCEL BUTTON ON LOG FOOD/EXCERSIZE TRACKERS DIFFERENTLY FROM THE LOG BUTTON



// choose functions
function choose_addToFavorites(vals){
    confirmation_dialog.html('Are you sure you wish to add the selected item to your favorites?');
    choose_hg_setUpFavoriteButtons(vals);
    confirmation_dialog.dialog('open');

    return false;
}

function choose_hg_setUpFavoriteButtons(vals){
	confirmation_dialog.dialog('option', 'buttons', {
                    "No": function() {$(this).dialog("close");},
                    "Yes": function(){
                         $.post(
                                "/ajax/ajax.my-diet.php" ,
                                "action=add_fav_food&" + vals
                         );
			 hg_verifyFavorites();
			 if ( document.getElementById('sidebar_favorites'))
			 {
			 	updateFavoritesSidebar();
			 }
			 
                         
                    }
    });
	var myHost = 'http://' + window.location.hostname;
				var onBackground  = 'url("' + myHost + '/css/custom-theme/images/ui-bg_highlight-hard_on_40_ff6633_1x100.png") repeat-x 50% 50%  #F0F0F0';
				var offBackground = 'url("' + myHost + '/css/custom-theme/images/ui-bg_glass_75_f0f0f0_1x400.png" ) repeat-x 50% 50% #FF6633';
				var offColor = "#666666";
				var onColor = "#FFFFFF";
				$('.ui-dialog-buttonpane :button')
				.each(
					function()
					{ 
						if($(this).text().indexOf('No') != -1)
						{
							$(this).hover(
								function(){ 
									$(this).addClass("ui-state-hover"); 
									
									$(this).css('background',onBackground);
									$(this).css('border', '1px solid #ff6633');
									$(this).css('color', onColor);
								},
								function(){ 
									$(this).removeClass("ui-state-hover");
									$(this).css('background',offBackground); 
									$(this).css('border', '1px solid #D0CFCF');
									$(this).css('color', offColor);
								}
							)
							$(this).css('background',offBackground); 
							$(this).css('color', offColor);
						}
					}
				);




}

