﻿var createFoodListRequest = null;
function createFoodList(url, panel, tablepager) {
    //Kopplar upp mot webbservice
    if (panel == "#PanelSearchFoodResult") {
        if ($("#ImageSearchFoodLoader").is(":hidden")) {

            $("#ImageSearchFoodLoader").show();
        }
    }
    
    if (createFoodListRequest && createFoodListRequest.abort) {
        createFoodListRequest.abort();

    }
    createFoodListRequest = $.ajax({
        type: "GET",
        url: url,
        dataType: "json", cache: false, data: {}, contentType: "application/json; charset=utf-8",
        //När webbservicen svarar
        success: function(data) {
            if (!data.d) {
                showNotification("servererror");
                return;
            }
            $("#ImageSearchFoodLoader").hide();
            $(panel).empty();
            $(tablepager).empty();

            //För varje food som hämtats
            var tableHtml = "<table class='TableFoodList' cellpadding='0' cellspacing='0'><tr><th></th></tr>";

            var dropdownType = getTypeDropDown();

            var foods = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
            for (var i = 0; i < foods.length; i++) {
                //Measurements-dropdown
                var dropdownMes = "<select class='DropDownList DropDownListMeasurement'>";
                var measurements = (typeof foods[i].measurements) == 'string' ? eval('(' + foods[i].measurements + ')') : foods[i].measurements;
                var amount = "";
                for (var y = 0; y < measurements.length; y++) {
                    var selected = "";
                    if (measurements[y].selected) {
                        selected = " selected";
                        //Tar ut standard amount
                        amount = measurements[y].amount;
                    }
                    dropdownMes = dropdownMes + "<option value='" + measurements[y].measurementid + "'" + selected + ">" + measurements[y].description + "</option>";
                }
                var dropdownMes = dropdownMes + "</select>";

                //Amount-textbox
                var textboxAmount = "<p>I've eaten</p><input type='text' maxlength='4' class='TextBox TextBoxFoodAmount' value=" + amount + " />";

                //Hidden fields
                var hiddenPcsInGram = "<input type='hidden' class='pcsingram' value=" + foods[i].pcsingram + " />";
                var hiddenMlInGram = "<input type='hidden' class='mlingram' value=" + foods[i].mlingram + " />";
                var hiddenTypeOfMeasurementid = "<input type='hidden' class='typeofmeasurementid' value=" + foods[i].measurementid + " />";
                var hiddenCalories = "<input type='hidden' class='calories' value=" + foods[i].calories + " />";
                var hiddenFoodid = "<input type='hidden' class='foodid' value=" + foods[i].id + " />";

                //Lägger in innehåll i divar
                var typeTitle = "your diary";
                var typeClass = "LinkAddFood";
                if ($("#HiddenFieldDate").length == 0) {
                    typeTitle = "meal";
                    typeClass = "LinkAddFood LinkAddMeal";
                }

                var divFoodContentLeft = "<div class='TableFoodContentLeft'>" + hiddenTypeOfMeasurementid + hiddenMlInGram + hiddenPcsInGram + hiddenCalories + hiddenFoodid + dropdownType + textboxAmount + dropdownMes + "</div>";
                var divFoodContentRight = "<div class='TableFoodContentRight'><a class='" + typeClass + " medium green awesome' href='#' title='Add this food to " + typeTitle + "'><img src='../images/buttons/checkicon.png' class='awesomeIcon' alt='Add This' />Add This</a></div>";

                //Titel
                var imageHeadImage = "<img src='../images/" + foods[i].headimage + ".png' class='Icon' alt='" + foods[i].title + "' />";
                var titleFood = "<h3>" + imageHeadImage + foods[i].title + "</h3>";

                //Calories
                titleFood += "<div class='FoodCalories'><strong>" + foods[i].caloriespermesaurement + " calories</strong> per " + foods[i].standardmeasurement + "</div>";

                //USDA, favorite, etc etc
                var usda = "";
                if (foods[i].usda) {
                    usda = "<label class='DivUsda'>USDA</label>";
                }


                var grade = "";
                if (foods[i].grade >= 0) {
                    grade = "<label class='LabelThumb'><img src='../images/thumb_up.png' class='ImageThumb' alt='thumb up' />" + foods[i].grade + "</label>";
                } else {
                    grade = "<label class='LabelThumb'><img src='../images/thumb_down.png' class='ImageThumb' alt='thumb down' />" + foods[i].grade + "</label>";
                }
                var favorite = "";
                if (foods[i].favorite) {
                    favorite = "<label class='LabelThumb'><img src='../images/star_mini.png' class='ImageFoodInfo' alt='favorite' /></label>";
                }
                var own = "";
                if (foods[i].owner) {
                    own = "<label class='LabelThumb'><img src='../images/user.png' class='ImageFoodInfo' alt='Your own food' /></label>";
                }

                var moreinfo = "<a class='LinkFoodDetails micro blue awesome' href='FoodItem.aspx?foodid=" + foods[i].id + "&type=" + getCurrentTab() + "&date=" + getCurrentDate() + "&mealid=" + queryString("mealid") + "&addedmealid=" + queryString("addedmealid") + "&addmeal=" + queryString("addmeal") + "&diarymeal=" + queryString("diarymeal") + "' title='See more details about this food'>More info &raquo;</a>"

                var uparrow = "<img class='ImageFoodListUpArrow' src='../images/bullet_arrow_up.png'>"
                var downarrow = "<img class='ImageFoodListDownArrow' src='../images/bullet_arrow_down.png'>";

                //Lägger in innehållet
                titleFood += "<p class='FoodInfo'>" + usda + favorite + own + grade + moreinfo + downarrow + "</p>";
                tableHtml += "<tr><td>" + titleFood + "</td></tr>";
                tableHtml += "<tr><td>" + divFoodContentLeft + divFoodContentRight + uparrow + "</td></tr>";
            }
            $(panel).append(tableHtml + "</table>");

            //Expander och Paging
            jQuery($(panel).find("tr:odd")).quickpaginate({ perpage: 5, showcounter: true, pager: $(tablepager) });
            $(panel).find("table").jExpand();

            //När listan med measurements ändrats
            $('.DropDownListMeasurement').change(function() {
                var sender = $(this);
                updateCalories(sender);
            });

            //När amount ändrats
            $('.TextBoxFoodAmount').keyup(function() {
                var sender = $(this);
                updateCalories(sender);
            });

            //När lägg till mat klickas
            $('.LinkAddFood').click(function() {

                var sender = $(this);
                var amount = sender.closest('div').prev('div').find(".TextBoxFoodAmount").val();
                var measurementid = sender.closest('div').prev('div').find(".DropDownListMeasurement").val();
                var type = "";
                if (sender.closest('div').prev('div').find(".DropDownListType").length != 0) {
                    type = sender.closest('div').prev('div').find(".DropDownListType").val();
                }
                var foodid = sender.closest('div').prev('div').find(".foodid").val();
                var date = getCurrentDate();
                var url = "http://www.shapeupclub.com/ShapeUpService.svc/addFood?foodid=" + foodid + "&mealid=" + queryString("mealid") + "&addedmealid=" + queryString("addedmealid") + "&date=" + date + "&amount=" + amount + "&measurementid=" + measurementid + "&type=" + type;
                $.ajax({
                    type: "GET",
                    url: url,
                    dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
                    //När webbservicen svarar
                    success: function(data) {
                        //Laddar om tab och visar popup
                        if (sender.closest('div').prev('div').find(".DropDownListType").length != 0) {
                            loadTab($(".DiaryTabs").tabs('option', 'selected'));
                        } else {
                            loadMealSummary(false);
                            loadMealFoodlist();
                        }
                        showNotification(data.d);
                    },
                    //Om det blir fel
                    error: function(data) {
                        showNotification("servererror");
                    }
                });
                return false;
            });
            createFoodListRequest = null;
        },
        //Om det blir fel
        error: function(data) {
            if (panel == "#PanelSearchFoodResult") {
                $("#ImageSearchFoodLoader").hide();
            }
            createFoodListRequest = null;
            showNotification("servererror");
        }
    });
    }




    //Updaterar fältet med kalorier
    function updateCalories(sender) {
        var amount;
        var measurementid;
        var textMeasurement;

        //Tar ut parametrar till anrop beroende på om det är listan eller om det är amount som ändrats
        if (sender.hasClass(".DropDownListMeasurement")) {
            amount = sender.prevAll(".TextBoxFoodAmount").val();
            measurementid = sender.val();
            textMeasurement = sender.find("option:selected").text().toLowerCase();
        } else {
            amount = sender.val();
            measurementid = sender.nextAll(".DropDownListMeasurement").val();
            textMeasurement = sender.nextAll(".DropDownListMeasurement").find("option:selected").text().toLowerCase()
        }
        var typeofmeasurementid = sender.prevAll(".typeofmeasurementid").val();
        var mlingram = sender.prevAll(".mlingram").val();
        var pcsingram = sender.prevAll(".pcsingram").val();
        var calories = sender.prevAll(".calories").val();
        var url = "http://www.shapeupclub.com/SearchService.svc/getMeasurementInSI?measurementid=" + measurementid + "&pcsingram=" + pcsingram + "&mlingram=" + mlingram + "&typeofmeasurementid=" + typeofmeasurementid;
        $.ajax({
            type: "GET",
            url: url,
            dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",

            //När webbservicen svarar
            success: function(data) {
                //Uppdaterar fältet med kalorier utifrån webbservice anropet
                var amountText;
                if (amount == 1) {
                    amountText = "";
                } else {
                    amountText = amount + " ";
                }
                sender.closest('tr').prev('tr').find('.FoodCalories').html("<strong>" + Math.round(calories * amount * data.d) + " calories</strong> per " + amountText + textMeasurement);
            },
            //Om det blir fel
            error: function(data) {
                showNotification("servererror");
            }
        });
    }


    function createMealList(url, panel, tablepager) {
        
        //Kopplar upp mot webbservice
        $.ajax({
            type: "GET",
            url: url,
            dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
            //När webbservicen svarar
            success: function(data) {
                if (!data.d) {
                    showNotification("servererror");
                    return;
                }
                $(panel).empty();
                $(tablepager).empty();
                //För varje meal som hämtats
                var tableHtml = "<table class='TableMealList' cellpadding='0' cellspacing='0'><tr><th></th></tr>";

                var dropdownType = getTypeDropDown();
                
                var meals = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
                for (var i = 0; i < meals.length; i++) {
                    //Amount-textbox
                    var textboxAmount = "<p>I've eaten</p><input maxlength='4' type='text' class='TextBox TextBoxMealAmount' value='1' />";

                    //Hidden fields
                    var hiddenCalories = "<input type='hidden' class='calories' value=" + meals[i].calories + " />";
                    var hiddenMealid = "<input type='hidden' class='mealid' value=" + meals[i].id + " />";

                    //Lägger in innehåll i divar
                    var divMealContentLeft = "<div class='TableMealContentLeft'>" + hiddenCalories + hiddenMealid + dropdownType + textboxAmount + "</div>";
                    var divMealContentRight = "<div class='TableMealContentRight'><a class='LinkAddMeal medium green awesome' href='#' title='Add meal to diary'><img src='../images/buttons/checkicon.png' class='awesomeIcon' alt='Add This' />Add This</a></div>";
                    

                    //Titel
                    var imageMealImage = "<img src='../images/" + meals[i].image + ".png' class='Icon' alt='" + meals[i].title + "' />";
                    var titleMeal = "<h3>" + imageMealImage + meals[i].title + "</h3>";

                    //Calories
                    titleMeal = titleMeal + "<p class='MealCalories'><strong>" + meals[i].calories + " calories</strong> per serving</p>";

                    var moreinfo = "<a class='LinkMealDetails micro blue awesome' href='AddMeal.aspx?mealid=" + meals[i].id + "&type=" + getCurrentTab() + "&date=" + getCurrentDate() + "&addmeal=True' title='See more details about this meal'>More Info &raquo;</a>"

                    var uparrow = "<img class='ImageFoodListUpArrow' src='../images/bullet_arrow_up.png'>"
                    var downarrow = "<img class='ImageFoodListDownArrow' src='../images/bullet_arrow_down.png'>";

                    //Lägger in innehållet
                    titleMeal = titleMeal + "<p class='MealInfo'>" + moreinfo + downarrow + "</p>";
                    tableHtml = tableHtml + "<tr><td>" + titleMeal + "</td></tr>";
                    tableHtml = tableHtml + "<tr><td>" + divMealContentLeft + divMealContentRight + uparrow + "</td></tr>";
                }
                $(panel).append(tableHtml + "</table>");
                //Expander och Paging
                jQuery($(panel).find("tr:odd")).quickpaginate({ perpage: 5, showcounter: true, pager: $(tablepager) });
                $(panel).find("table").jExpand();

                //När amount ändrats
                $('.TextBoxMealAmount').keyup(function() {
                    var sender = $(this);
                    var amount;

                    amount = sender.val();
                    var calories = sender.prevAll(".calories").val();
                    var amountText;
                    if (amount == 1) {
                        amountText = "";
                    } else {
                        amountText = amount + " ";
                    }
                    sender.closest('tr').prev('tr').find('.MealCalories').html("<strong>" + Math.round(calories * amount) + " calories</strong> per " + amountText + " serving");
                });

                //När lägg till mat klickas
                $('.LinkAddMeal').click(function() {

                    var sender = $(this);
                    var amount = sender.closest('div').prev('div').find(".TextBoxMealAmount").val();
                    var type = sender.closest('div').prev('div').find(".DropDownListType").val();
                    var mealid = sender.closest('div').prev('div').find(".mealid").val();
                    var date = getCurrentDate();
                    $.ajax({
                        type: "GET",
                        url: "http://www.shapeupclub.com/ShapeUpService.svc/addMeal?mealid=" + mealid + "&date=" + date + "&amount=" + amount + "&type=" + type,
                        dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
                        //När webbservicen svarar
                        success: function(data) {
                            //Laddar om tab och visar popup
                            loadTab($(".DiaryTabs").tabs('option', 'selected'));
                            showNotification(data.d);
                        },
                        //Om det blir fel
                        error: function(data) {
                            showNotification("servererror");
                        }
                    });
                    return false;
                });

            },
            //Om det blir fel
            error: function(data) {
                showNotification("servererror");
            }
        });
    }

    var createExerciseListRequest = null;
    function createExerciseList(url, panel, tablepager) {

        if (panel == "#PanelSearchExerciseResult") {
            if ($("#ImageSearchExerciseLoader").is(":hidden")) {

                $("#ImageSearchExerciseLoader").show();
            }
        }
    
        if (createExerciseListRequest && createExerciseListRequest.abort) {
            createExerciseListRequest.abort();
        }
        //Kopplar upp mot webbservice
        createExerciseListRequest = $.ajax({
            type: "GET",
            url: url,
            dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
            //När webbservicen svarar
            success: function(data) {
                if (!data.d) {
                    showNotification("servererror");
                    return;
                }

                if (panel == "#PanelSearchExerciseResult") {
                    $("#ImageSearchExerciseLoader").hide();
                }
                $(panel).empty();
                $(tablepager).empty();

                //För varje exercise som hämtats
                var tableHtml = "<table class='TableExerciseList' cellpadding='0' cellspacing='0'><tr><th></th></tr>";
                var exercises = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
                for (var i = 0; i < exercises.length; i++) {


                    //Amount-textbox
                    var textboxAmount = "<p>How many minutes?</p><input type='text' maxlength='4' class='TextBox TextBoxExerciseAmount' value='30' />";

                    //Hidden fields
                    var hiddenOwner = "<input type='hidden' class='owner' value=" + exercises[i].owner + " />";
                    var hiddenCalories = "<input type='hidden' class='calories' value=" + exercises[i].calories + " />";
                    var hiddenExerciseid = "<input type='hidden' class='exerciseid' value=" + exercises[i].id + " />";

                    //Lägger in innehåll i divar
                    var divExerciseContentLeft = "<div class='TableExerciseContentLeft'>" + hiddenOwner + hiddenCalories + hiddenExerciseid + textboxAmount + "</div>";
                    var divExerciseContentRight = "<div class='TableExerciseContentRight'><a class='LinkAddExercise medium green awesome' href='#' title='Add exercise to diary'><img src='../images/buttons/checkicon.png' class='awesomeIcon' alt='Add This' />Add This</a></div>";
                    
                    //Titel
                    var imageHeadImage = "<img src='../images/" + exercises[i].headimage + ".png' class='Icon' alt='" + exercises[i].title + "' />";
                    var titleExercise = "<h3>" + imageHeadImage + exercises[i].title + "</h3>";

                    //Calories
                    titleExercise = titleExercise + "<div class='ExerciseCalories'><strong>" + Math.round(exercises[i].calories * 30) + " calories</strong> per 30 minutes</div>";

                    //USDA, favorite, etc etc
                    var usda = "";

                    var own = "";
                    if (exercises[i].owner) {
                        own = "<label class='LabelThumb'><img src='../images/user.png' class='ImageExerciseInfo' alt='Your own exercise' /></label>";
                    }

                    var uparrow = "<img class='ImageFoodListUpArrow' src='../images/bullet_arrow_up.png'>"
                    var downarrow = "<img class='ImageFoodListDownArrow' src='../images/bullet_arrow_down.png'>";

                    var moreinfo = "<a class='LinkExerciseDetails micro blue awesome' href='ExerciseItem.aspx?exerciseid=" + exercises[i].id + "&date=" + getCurrentDate() + "' title='See more details about this exercise'>More Info &raquo;</a>"

                    //Lägger in innehållet
                    titleExercise += "<p class='ExerciseInfo'>" + usda + own + moreinfo + downarrow + "</p>";
                    tableHtml = tableHtml + "<tr><td>" + titleExercise + "</td></tr>";
                    tableHtml = tableHtml + "<tr><td>" + divExerciseContentLeft + divExerciseContentRight + uparrow + "</td></tr>";
                }
                $(panel).append(tableHtml + "</table>");

                //Expander och Paging
                jQuery($(panel).find("tr:odd")).quickpaginate({ perpage: 5, showcounter: true, pager: $(tablepager) });
                $(panel).find("table").jExpand();

                //När amount ändrats
                $('.TextBoxExerciseAmount').keyup(function() {
                    var sender = $(this);
                    var amount;

                    amount = sender.val();
                    var calories = sender.prevAll(".calories").val();
                    var amountText;
                    if (amount == 1) {
                        amountText = "";
                    } else {
                        amountText = amount + " ";
                    }
                    sender.closest('tr').prev('tr').find('.ExerciseCalories').html("<strong>" + Math.round(calories * amount) + " calories</strong> per " + amountText + " minute(s)");
                });

                //När lägg till exercise klickas
                $('.LinkAddExercise').click(function() {

                    var sender = $(this);
                    var amount = sender.closest('div').prev('div').find(".TextBoxExerciseAmount").val();
                    var exerciseid = sender.closest('div').prev('div').find(".exerciseid").val();
                    var owner = sender.closest('div').prev('div').find(".owner").val();
                    var date = getCurrentDate();
                    $.ajax({
                        type: "GET",
                        url: "http://www.shapeupclub.com/ShapeUpService.svc/addExercise?exerciseid=" + exerciseid + "&date=" + date + "&amount=" + amount + "&owner=" + owner,
                        dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
                        //När webbservicen svarar
                        success: function(data) {
                            //Laddar om tab och visar popup
                            loadTab($(".DiaryTabs").tabs('option', 'selected'));
                            showNotification(data.d);
                        },
                        //Om det blir fel
                        error: function(data) {
                            showNotification("servererror");
                        }
                    });
                    return false;
                });
                createExerciseListRequest = null;
            },
            //Om det blir fel
            error: function(data) {
                if (panel == "#PanelSearchExerciseResult") {
                    $("#ImageSearchExerciseLoader").hide();
                }
                createExerciseListRequest = null;
                showNotification("servererror");
            }
        });
    }




    function createHeadCategoryList(headcategorypanel, categorypanel, secondcategorypanel, foodpanel, foodpagerpanel) {
        $(".CategoryBackButton").hide();
        //Kopplar upp mot webbservice
        $.ajax({
            type: "GET",
            url: "http://www.shapeupclub.com/SearchService.svc/headCategory",
            dataType: "json", cache: false, data: {}, contentType: "application/json; charset=utf-8",
            //När webbservicen svarar
            success: function(data) {
                if (!data.d) {
                    showNotification("servererror");
                    return;
                }
                $(headcategorypanel).empty();

                var tableHtml = "<table class='TableHeadCategoryList' cellpadding='0' cellspacing='0'><tr><th></th></tr>";

                //För varje category som hämtats
                var categories = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
                for (var i = 0; i < categories.length; i++) {

                    //Titel, bild och id
                    var imageHeadImage = "<img src='../images/" + categories[i].image + ".png' class='Icon' alt='" + categories[i].title + "' />";
                    var titleHeadCategory = "<h3>" + categories[i].title + "</h3>";
                    var hiddenHeadCategoryId = "<input type='hidden' class='headcategoryid' value=" + categories[i].id + " />";

                    //Lägger in innehållet
                    tableHtml += "<tr><td>" + imageHeadImage + hiddenHeadCategoryId + "</td>";
                    tableHtml += "<td>" + titleHeadCategory + "</td></tr>";
                }
                $(headcategorypanel).append(tableHtml + "</table>");

                $(headcategorypanel).find("tr").click(function() {

                    createCategoryList(this, categorypanel, secondcategorypanel, foodpanel);
                    //$(headcategorypanel).hide("slide", { direction: "left" }, 200, function() { $(categorypanel).show("slide", { direction: "right" }, 200); $(".CategoryBackButton").show(); });
                    $(headcategorypanel).hide();
                    $(categorypanel).show();
                    $(".CategoryBackButton").show();
                });

                $(".CategoryBackButton").click(function() {
                    if (!$(foodpanel).is(":hidden")) {
                        if ($(secondcategorypanel).html() == "") {
                            //$(foodpanel).hide("slide", { direction: "right" }, 200, function() { $(categorypanel).show("slide", { direction: "left" }, 200); });
                            $(foodpanel).hide();
                            $(categorypanel).show();
                        } else {
                            //$(foodpanel).hide("slide", { direction: "right" }, 200, function() { $(secondcategorypanel).show("slide", { direction: "left" }, 200); });
                            $(foodpanel).hide();
                            $(secondcategorypanel).show();
                        }
                    } else if (!$(categorypanel).is(":hidden")) {
                        //$(categorypanel).hide("slide", { direction: "right" }, 200, function() { $(headcategorypanel).show("slide", { direction: "left" }, 200); });
                        $(categorypanel).hide();
                        $(headcategorypanel).show();
                        $(".CategoryBackButton").hide();
                    } else {
                        //$(secondcategorypanel).hide("slide", { direction: "right" }, 200, function() { $(categorypanel).show("slide", { direction: "left" }, 200); });
                        $(secondcategorypanel).hide();
                        $(categorypanel).show();
                        $(secondcategorypanel).empty();
                    }
                    $("#PanelCategoryFoodPager").empty();
                    return false;
                });
            },
            //Om det blir fel
            error: function(data) {
                showNotification("servererror");
            }
        });
    }

    function createCategoryList(sender, categorypanel, secondcategorypanel, foodpanel) {
        var headcategoryid = $(sender).find("td").find(".headcategoryid").val();
        $.ajax({
            type: "GET",
            url: "http://www.shapeupclub.com/SearchService.svc/category?headcategoryid=" + headcategoryid,
            dataType: "json", cache: false, data: {}, contentType: "application/json; charset=utf-8",
            //När webbservicen svarar
            success: function(data) {
                if (!data.d) {
                    showNotification("servererror");
                    return;
                }
                $(categorypanel).empty();

                var tableHtml = "<table class='TableHeadCategoryList' cellpadding='0' cellspacing='0'><tr><th></th></tr>";

                //För varje category som hämtats
                var categories = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
                for (var i = 0; i < categories.length; i++) {
                    //Titel, bild och id
                    var imageHeadImage = "<img src='../images/" + categories[i].image + ".png' class='Icon' alt='" + categories[i].title + "' />";
                    var titleHeadCategory = "<h3>" + categories[i].title + "</h3>";
                    var hiddenCategoryId = "<input type='hidden' class='categoryid' value=" + categories[i].id + " />";
                    //Lägger in innehållet
                    tableHtml += "<tr><td>" + imageHeadImage + hiddenCategoryId + "</td>";
                    tableHtml += "<td>" + titleHeadCategory + "</td></tr>";
                }
                $(categorypanel).append(tableHtml + "</table>");

                $(categorypanel).find("tr").click(function() {
                    var categoryid = $(this).find("td").find(".categoryid").val();
                    var headimage = $(this).find("td").find("img").attr("src");
                    var headtitle = $(this).find("td").next("td").find("h3").html();

                    if ((headcategoryid == "5" && categoryid > 15 && categoryid < 20) || headcategoryid == "15") {
                        createSecondCategoryList(this, secondcategorypanel, foodpanel);
                        $(categorypanel).hide();
                        $(secondcategorypanel).show();
                        //$(categorypanel).hide("slide", { direction: "left" }, 200, function() { $(secondcategorypanel).show("slide", { direction: "right" }, 200); });
                    }
                    else {
                        createFoodList("http://www.shapeupclub.com/SearchService.svc/categoryFood?categoryid=" + categoryid, foodpanel, "#PanelCategoryFoodPager");
                        //$(categorypanel).hide("slide", { direction: "left" }, 200, function() { $(foodpanel).show("slide", { direction: "right" }, 200); });
                        $(categorypanel).hide();
                        $(foodpanel).show();
                    }
                });
            },
            //Om det blir fel
            error: function(data) {
                showNotification("servererror");
            }
        });
    }

    function createSecondCategoryList(sender,secondcategorypanel, foodpanel) {
        
        var headcategoryid = $(sender).find("td").find(".categoryid").val();
        $.ajax({
            type: "GET",
            url: "http://www.shapeupclub.com/SearchService.svc/category?headcategoryid=" + headcategoryid,
            dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
            //När webbservicen svarar
            success: function(data) {
            if (!data.d) {
                showNotification("servererror");
                return;
            }
            $(secondcategorypanel).empty();

                var tableHtml = "<table class='TableHeadCategoryList' cellpadding='0' cellspacing='0'><tr><th></th></tr>";

                //För varje category som hämtats
                var categories = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
                for (var i = 0; i < categories.length; i++) {
                    //Titel, bild och id
                    var imageHeadImage = "<img src='../images/" + categories[i].image + ".png' class='Icon' alt='" + categories[i].title + "' />";
                    var titleHeadCategory = "<h3>" + categories[i].title + "</h3>";
                    var hiddenCategoryId = "<input type='hidden' class='categoryid' value=" + categories[i].id + " />";
                    //Lägger in innehållet
                    tableHtml += "<tr><td>" + imageHeadImage + hiddenCategoryId + "</td>";
                    tableHtml += "<td>" + titleHeadCategory + "</td></tr>";
                }
                $(secondcategorypanel).append(tableHtml + "</table>");

                $(secondcategorypanel).find("tr").click(function() {
                    var categoryid = $(this).find("td").find(".categoryid").val();
                    var headimage = $(this).find("td").find("img").attr("src");
                    var headtitle = $(this).find("td").next("td").find("h3").html();
                    createFoodList("http://www.shapeupclub.com/SearchService.svc/categoryFood?categoryid=" + categoryid, foodpanel, "#PanelCategoryFoodPager");
                    //$(secondcategorypanel).hide("slide", { direction: "left" }, 200, function() { $(foodpanel).show("slide", { direction: "right" }, 200); });
                    $(secondcategorypanel).hide();
                    $(foodpanel).show();
                });
            },
            //Om det blir fel
            error: function(data) {
                showNotification("servererror");
            }
        });
    }
    
    function loadTab(thistab) {
        if (thistab == 0) {
            $('#ExerciseTabs').hide();
            $('#FoodTabs').show();
            $.ajax({
                type: "GET",
                url: "http://www.shapeupclub.com/SearchService.svc/diary?date=" + getCurrentDate(),
                dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
                data: {},
                contentType: "application/json; charset=utf-8",
                //När webbservicen svarar
                success: function(data) {
                    if (!data.d) {
                        showNotification("servererror");
                        return;
                    }
                    //Returnerar ett diary objekt som innehåller alla värden
                    var diary = data.d;
                    $("#spanDiaryTotalCalories").html(Math.round(diary.calories));
                    $("#spanDiaryTargetCalories").html(Math.round(diary.target));
                    $("#spanDiaryLeftCalories").html(Math.round(diary.diff));
                    $("#imageCalorieMarker").attr("src", diary.caloriemarker);
                    $("#imageTrackIngram").attr("src", "../images/trackingram" + diary.trackingram + ".png");
                    

                    if (diary.caloriessnack1 == 0) {
                        $("#TableDiaryBreakDown tr:eq(1)").hide();
                    } else {
                        $("#TableDiaryBreakDown tr:eq(1)").show();
                    }

                    if (diary.caloriessnack2 == 0) {
                        $("#TableDiaryBreakDown tr:eq(3)").hide();
                    } else {
                        $("#TableDiaryBreakDown tr:eq(3)").show();
                    }

                    if (diary.caloriessnack3 == 0) {
                        $("#TableDiaryBreakDown tr:eq(5)").hide();
                    } else {
                        $("#TableDiaryBreakDown tr:eq(5)").show();
                    }

                    $("#TableDiaryBreakDown tr:eq(0) td:eq(1)").html(Math.round(diary.caloriesbreakfast) + " calories");
                    $("#TableDiaryBreakDown tr:eq(1) td:eq(1)").html(Math.round(diary.caloriessnack1) + " calories");
                    $("#TableDiaryBreakDown tr:eq(2) td:eq(1)").html(Math.round(diary.calorieslunch) + " calories");
                    $("#TableDiaryBreakDown tr:eq(3) td:eq(1)").html(Math.round(diary.caloriessnack2) + " calories");
                    $("#TableDiaryBreakDown tr:eq(4) td:eq(1)").html(Math.round(diary.caloriesdinner) + " calories");
                    $("#TableDiaryBreakDown tr:eq(5) td:eq(1)").html(Math.round(diary.caloriessnack3) + " calories");


                    $("#TableDiaryBreakDown tr:eq(6) td:eq(1)").html(Math.round(diary.caloriesexercise) + " calories");
                    $("#TableDiaryBreakDown tr:eq(7) td:eq(1)").html("<strong>" + Math.round(diary.caloriesfood - diary.caloriesexercise) + " calories</strong>");


                    $("#TableDiaryGrid tr:eq(0) td:eq(1), #TableDiaryNutritionSummary tr:eq(0) td:eq(1)").html(diary.protein);
                    $("#TableDiaryGrid tr:eq(0) td:eq(2), #TableDiaryNutritionSummary tr:eq(0) td:eq(2)").html(diary.recprotein);
                    $("#TableDiaryGrid tr:eq(1) td:eq(1), #TableDiaryNutritionSummary tr:eq(1) td:eq(1)").html(diary.carbs);
                    $("#TableDiaryGrid tr:eq(1) td:eq(2), #TableDiaryNutritionSummary tr:eq(1) td:eq(2)").html(diary.reccarbs);
                    $("#TableDiaryGrid tr:eq(2) td:eq(1), #TableDiaryNutritionSummary tr:eq(2) td:eq(1)").html(diary.fat);
                    $("#TableDiaryGrid tr:eq(2) td:eq(2), #TableDiaryNutritionSummary tr:eq(2) td:eq(2)").html(diary.recfat);

                    $("#TableDiaryCalorieSummary tr:eq(0) td:eq(1)").html(Math.round(diary.calories) + " calories");
                    $("#TableDiaryCalorieSummary tr:eq(1) td:eq(1)").html(Math.round(diary.caloriesfood) + " calories");
                    $("#TableDiaryCalorieSummary tr:eq(2) td:eq(1)").html(Math.round(diary.caloriesexercise) + " calories");

                    $("#TableDiaryNutritionSummary tr:eq(3) td:eq(1)").html(diary.sodium);
                    $("#TableDiaryNutritionSummary tr:eq(4) td:eq(1)").html(diary.fiber);
                    $("#TableDiaryNutritionSummary tr:eq(5) td:eq(1)").html(diary.saturatedfat);
                    $("#TableDiaryNutritionSummary tr:eq(6) td:eq(1)").html(diary.unsaturatedfat);
                    $("#TableDiaryNutritionSummary tr:eq(7) td:eq(1)").html(diary.sugar);
                    $("#TableDiaryNutritionSummary tr:eq(8) td:eq(1)").html(diary.cholesterol);
                    $("#TableDiaryNutritionSummary tr:eq(9) td:eq(1)").html(diary.potassium);
                    $("#PanelChartContent").html(diary.chart);
                },
                //Om det blir fel
                error: function(data) {

                }
            });
        }
        else if (thistab == 5) {
            $('#ExerciseTabs').show();
            $('#FoodTabs').hide();
            $.ajax({
                type: "GET",
                url: "http://www.shapeupclub.com/SearchService.svc/diaryExercise?date=" + getCurrentDate(),
                dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
                //När webbservicen svarar
                success: function(data) {
                    if (!data.d) {
                        showNotification("servererror");
                        return;
                    }
                    $("#DiaryTabContent").empty();

                    //För varje exercise som hämtats
                    var tableHtml = "<table class='TableDiaryFoodList' cellpadding='0' cellspacing='0'><tr><th></th></tr>";
                    var exercises = (typeof data.d.list) == 'string' ? eval('(' + data.d.list + ')') : data.d.list;
                    for (var i = 0; i < exercises.length; i++) {
                        var exerciselink = "exerciseitem.aspx?exerciseid=" + exercises[i].exerciseid + "&exerciseitemid=" + exercises[i].exerciseitemid + "&date=" + getCurrentDate();
                        if (exercises[i].custom) {
                            exerciselink = "CustomCaloriesExercise.aspx?exerciseid=" + exercises[i].exerciseid + "&exerciseitemid=" + exercises[i].exerciseitemid + "&date=" + getCurrentDate();
                        }
                    
                        tableHtml = tableHtml + "<tr><td><img class='Icon' src='../images/" + exercises[i].headimage + ".png' alt='" + exercises[i].title + "'/></td>";
                        tableHtml = tableHtml + "<td><div class='PanelDiaryFoodTitle'><a href='" + exerciselink + "' title='Edit this exercise'>" + exercises[i].title + "</a></div><div class='PanelDiaryFoodInfo'>" + Math.round(exercises[i].calories) + " calories</div></td>";
                        tableHtml = tableHtml + "<td><a class='mini yellow awesome' href='" + exerciselink + "' title='Edit this exercise'><img src='../images/buttons/penicon.png' class='awesomeIconNoSpace'></a></div></td>";
                        tableHtml = tableHtml + "<td><input type='hidden' class='exerciseid' value=" + exercises[i].exerciseid + " /><input type='hidden' class='exerciseitemid' value=" + exercises[i].exerciseitemid + " /><a class='ButtonDiaryExerciseDelete mini red awesome' href='#' title='Delete this exercise'>X</a></div></td></tr>";
                    }

                    var title = "<h3 class='DiaryTotalCalories'><img class='Icon' src='../images/iconexercise.png'>Exercise: " + Math.round(data.d.totalcalories) + " calories</h3>";
                    
                    $("#DiaryTabContent").append(title + tableHtml + "</table>");
                },
                //Om det blir fel
                error: function(data) {
                    showNotification("servererror");
                }
            });
        }
        else {
            $('.DropDownListType option:selected').removeAttr('selected');
            $('.DropDownListType option[value=' + thistab + ']').attr('selected', 'selected');

            $('#ExerciseTabs').hide();
            $('#FoodTabs').show();
            $.ajax({
                type: "GET",
                url: "http://www.shapeupclub.com/SearchService.svc/diaryFood?type=" + thistab + "&date=" + getCurrentDate(),
                dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
                //När webbservicen svarar
                success: function(data) {
                    if (!data.d) {
                        showNotification("servererror");
                        return;
                    }
                    
                    $("#DiaryTabContent").empty();

                    var tableHtml1 = "<table class='TableDiaryFoodList' cellpadding='0' cellspacing='0'><tr><th></th></tr>";
                    tableHtml2 = "";
                    tableHtml3 = "";

                    //Om snack-tabben måste tre olika tabeller användas
                    if (thistab == 4) {
                        tableHtml1 = "<h3 class='DiarySnackTitle'>Early Snack</h3><table class='TableDiaryFoodList' cellpadding='0' cellspacing='0'><tr><th></th></tr>";
                        tableHtml2 = "<h3 class='DiarySnackTitle'>Afternoon Snack</h3><table class='TableDiaryFoodList' cellpadding='0' cellspacing='0'><tr><th></th></tr>";
                        tableHtml3 = "<h3 class='DiarySnackTitle'>Other</h3><table class='TableDiaryFoodList' cellpadding='0' cellspacing='0'><tr><th></th></tr>";
                    }

                    var hasEarlySnack = false;
                    var hasAfternoonSnack = false;
                    var hasOther = false;
                    //För varje food som hämtats
                    var foods = (typeof data.d.list) == 'string' ? eval('(' + data.d.list + ')') : data.d.list;
                    for (var i = 0; i < foods.length; i++) {
                        var tableHtml = "";
                        var foodlink = "fooditem.aspx?fooditemid=" + foods[i].fooditemid + "&foodid=" + foods[i].foodid + "&date=" + getCurrentDate() + "&type=" + thistab;
                        if (foods[i].mealid != "") {
                            foodlink = "addedmeal.aspx?addedmealid=" + foods[i].addedmealid + "&mealid=" + foods[i].mealid + "&date=" + getCurrentDate() + "&type=" + thistab;
                        } else if (foods[i].custom) {
                            foodlink = "CustomCalories.aspx?fooditemid=" + foods[i].fooditemid + "&foodid=" + foods[i].foodid + "&date=" + getCurrentDate() + "&type=" + thistab;
                        }

                        tableHtml += "<tr><td><img class='Icon' src='../images/" + foods[i].headimage + ".png' alt='" + foods[i].category + "'/></td>";
                        tableHtml += "<td><div class='PanelDiaryFoodTitle'><a href='" + foodlink + "'>" + foods[i].title + "</a></div><div class='PanelDiaryFoodInfo'>" + Math.round(foods[i].calories) + " calories</div></td>";
                        tableHtml += "<td><a class='mini yellow awesome' href='" + foodlink + "' title='Edit this food'><img src='../images/buttons/penicon.png' class='awesomeIconNoSpace'></a></div></td>";
                        tableHtml += "<td><input type='hidden' class='foodid' value=" + foods[i].foodid + " /><input type='hidden' class='fooditemid' value=" + foods[i].fooditemid + " /><input type='hidden' class='mealid' value=" + foods[i].mealid + " /><input type='hidden' class='addedmealid' value=" + foods[i].addedmealid + " />";
                        tableHtml += "<a class='ButtonDiaryFoodDelete mini red awesome' href='#' title='Delete this food'>X</a></div></td></tr>";
                        if (thistab == 4) {
                            if (foods[i].type == 4) {
                                tableHtml1 += tableHtml;
                                hasEarlySnack = true;
                            } else if (foods[i].type == 5) {
                                tableHtml2 += tableHtml;
                                hasAfternoonSnack = true;
                            } else {
                                tableHtml3 += tableHtml;
                                hasOther = true;
                            }
                        } else {
                            tableHtml1 += tableHtml;
                        }
                    }

                    var title = "";
                    if (thistab == 1) {
                        title = "<h3 class='DiaryTotalCalories'><img class='Icon' src='../images/iconbreakfast.png'>Breakfast: ";
                    } else if (thistab == 2) {
                        title = "<h3 class='DiaryTotalCalories'><img class='Icon' src='../images/iconlunch.png'>Lunch: ";
                    } else if (thistab == 3) {
                        title = "<h3 class='DiaryTotalCalories'><img class='Icon' src='../images/icondinner.png'>Dinner: ";
                    }
                    else if (thistab == 4) {
                        title = "<h3 class='DiaryTotalCalories'><img class='Icon' src='../images/iconsnack.png'>Snacks: ";
                        if (!hasEarlySnack) {
                            tableHtml1 = "<table>";
                        }

                        if (!hasAfternoonSnack) {
                            tableHtml2 = "<table>";
                        }

                        if (!hasOther) {
                            tableHtml3 = "<table>";
                        }
                        tableHtml2 += "</table>";
                        tableHtml3 += "</table>";
                    }

                    title += Math.round(data.d.totalcalories) + " calories</h3>";

                    $("#DiaryTabContent").append(title + tableHtml1 + "</table>" + tableHtml2 + tableHtml3);
                },
                //Om det blir fel
                error: function(data) {

                }
            });
        }
    }


    function loadMealSummary(shouldUpdateTypeAndAmount) {
        var amount = "";
        if ($("#TextBoxAmount").length != 0) {
            amount = $("#TextBoxAmount").val().replace(/,/g, ".");
        } else {
            shouldUpdateTypeAndAmount = true;
        }
        $("#LabelServingAmount").html(amount);
        $.ajax({
        type: "GET",
        url: "http://www.shapeupclub.com/SearchService.svc/mealSummary?amount=" + amount + "&mealid=" + queryString("mealid") + "&addedmealid=" + queryString("addedmealid") + "&shouldUpdateTypeAndAmount=" + shouldUpdateTypeAndAmount,
            dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
            //När webbservicen svarar
            success: function(data) {
            if (!data.d) {
                showNotification("servererror");
                return;
            }
                //Returnerar ett meal objekt som innehåller alla värden
                var meal = data.d;
                if (shouldUpdateTypeAndAmount) {
                    $("#DDLType option:selected").removeAttr("selected");
                    $("#DDLType option[value=" + meal.type + "]").attr("selected", "selected");
                    $("#TextBoxAmount").val(meal.amount);
                    $("#LabelServingAmount").html(meal.amount);
                }
                $("#imageTrackIngram").attr("src", "../images/trackingram" + meal.trackingram + ".png");
                $("#TableNutrition tr:eq(0) td:eq(1)").html(meal.calories);
                $("#TableNutrition tr:eq(1) td:eq(1)").html(meal.protein);
                $("#TableNutrition tr:eq(2) td:eq(1)").html(meal.carbs);
                $("#TableNutrition tr:eq(3) td:eq(1)").html(meal.fiber);
                $("#TableNutrition tr:eq(4) td:eq(1)").html(meal.sugar);
                $("#TableNutrition tr:eq(5) td:eq(1)").html(meal.fat);
                $("#TableNutrition tr:eq(6) td:eq(1)").html(meal.saturatedfat);
                $("#TableNutrition tr:eq(7) td:eq(1)").html(meal.unsaturatedfat);
                $("#TableNutrition tr:eq(8) td:eq(1)").html(meal.cholesterol);
                $("#TableNutrition tr:eq(9) td:eq(1)").html(meal.sodium);
                $("#TableNutrition tr:eq(10) td:eq(1)").html(meal.potassium);
                $("#PanelAddMealSummaryGrid").html(meal.grid);
                $("#PanelAddMealSummaryChart").html(meal.chart);
                if (meal.calories == 0) {
                    $("#PanelAddMealSummaryGrid").hide();
                    $("#PanelAddMealSummaryChart").hide();
                } else {
                    $("#PanelAddMealSummaryGrid").show();
                    $("#PanelAddMealSummaryChart").show();
                }
            },
            //Om det blir fel
            error: function(data) {
                showNotification("servererror");
            }
        });
        }
    

    function loadMealFoodlist() {
        $.ajax({
            type: "GET",
            url: "http://www.shapeupclub.com/SearchService.svc/mealFood?mealid=" + queryString("mealid") + "&addedmealid=" + queryString("addedmealid"),
            dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
            //När webbservicen svarar
            success: function(data) {
            if (!data.d) {
                showNotification("servererror");
                return;
            }
                $("#MealFoodList").empty();

                var tableHtml = "<table class='TableMealFoodList' cellpadding='0' cellspacing='0'><tr><th></th></tr>";

                //För varje food som hämtats
                var foods = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;

                for (var i = 0; i < foods.length; i++) {
                    var typeofmeal = "&meal=True";
                    if ($("#TextBoxAmount").length != 0 && queryString("addedmealid") == "") {
                        typeofmeal = "&addmeal=True";
                    }

                    var foodlink = "fooditem.aspx?mealitemid=" + foods[i].mealitemid + "&addedmealitemid=" + foods[i].addedmealitemid + "&foodid=" + foods[i].foodid + "&mealid=" + queryString("mealid") + "&addedmealid=" + queryString("addedmealid") + "&date=" + queryString("date") + "&type=" + queryString("type") + typeofmeal;

                    tableHtml += "<tr><td><img class='Icon' src='../images/" + foods[i].headimage + ".png' alt='" + foods[i].category + "'/></td>";
                    tableHtml += "<td><div class='PanelMealFoodTitle'><a href='" + foodlink + "'>" + foods[i].title + "</a></div><div class='PanelMealFoodInfo'>" + Math.round(foods[i].calories) + " calories</div></td>";
                    tableHtml += "<td><a class='mini yellow awesome' href='" + foodlink + "' title='Edit this food'><img src='../images/buttons/penicon.png' class='awesomeIconNoSpace'></a></div></td>";
                    tableHtml += "<td><input type='hidden' class='foodid' value=" + foods[i].foodid + " /><input type='hidden' class='mealitemid' value=" + foods[i].mealitemid + " /><input type='hidden' class='addedmealitemid' value=" + foods[i].addedmealitemid + " />";
                    tableHtml += "<a class='ButtonMealFoodDelete mini red awesome' href='#' title='Delete this food'>X</a></div></td></tr>";
                }

                $("#MealFoodList").append(tableHtml + "</table>");
            },
            //Om det blir fel
            error: function(data) {
                showNotification("servererror");
            }
        });
    }

    function loadComment() {
        $.ajax({
            type: "GET",
            url: "http://www.shapeupclub.com/SearchService.svc/comment?date=" + getCurrentDate(),
            dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
            //När webbservicen svarar
            success: function(data) {
                if (data.d == "") {
                    $("#textfieldComment").val("Click here to enter comment");
                } else {
                    $("#textfieldComment").val(data.d);
                }
            }
        });
    }

    function loadWater() {
        $.ajax({
            type: "GET",
            url: "http://www.shapeupclub.com/SearchService.svc/water?date=" + getCurrentDate(),
            dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
            //När webbservicen svarar
            success: function(data) {
            if (!data.d) {
                showNotification("servererror");
                return;
            }
                $("#waterunit").html(data.d.ml);
                $("#waterslider").slider('destroy');
                $("#waterslider").slider({
                    range: "min",
                    min: 0,
                    max: data.d.recwater,
                    value: data.d.water,
                    step: data.d.waterstep,
                    slide: function(event, ui) {
                        if ($("#waterslider").slider('option', 'step') == 0.5) {
                            $("#wateramount").html(ui.value.toFixed(1));
                        } else {
                            $("#wateramount").html(ui.value);
                        }
                    },
                    stop: function(event, ui) {
                        //Tar ut vatten och baserar på cups/ml
                        var water = ui.value;
                        if ($("#waterslider").slider('option', 'step') == 0.5) {
                            water = water * 236.588237;
                        }
                        var date = getCurrentDate();
                        $.ajax({
                            type: "GET",
                            url: "http://www.shapeupclub.com/ShapeUpService.svc/addWater?date=" + date + "&water=" + water,
                            dataType: "json",cache: false, data: {}, contentType: "application/json; charset=utf-8",
                            //Om det blir fel
                            error: function(data) {
                                showNotification("servererror");
                            }
                        });
                    }

                });

                $("#wateramount").html($("#waterslider").slider("value"));
            }
        });
    }

    function updateTrackInGram() {
        $.ajax({
            type: "GET",
            url: "http://www.shapeupclub.com/ShapeUpService.svc/switchTrackInGram",
            dataType: "json", cache: false, data: {}, contentType: "application/json; charset=utf-8",
            //När webbservicen svarar
            success: function(data) {
                showNotification(data.d);
                if ($("#HiddenFieldDate").length == 0) {
                    loadMealSummary(false);
                } else {
                    loadTab(0);
                }
            },
            //Om det blir fel
            error: function(data) {
                showNotification("servererror");
            }
        });
    }


    function getCurrentDate() {
        //Tar ut nuvarande datum eller returnerar en tom sträng om det är ett meal
        if ($("#HiddenFieldDate").length != 0) {
            date = $("#HiddenFieldDate").datepicker("getDate");
            if (date == null) {
                date = new Date();
            }
            return date.format("yyyy-MM-dd");
        } else {
            return queryString("date");
        }
    }

    function getCurrentTab() {
        var currentTab = 1;
        if ($('.DiaryTabs').length != 0) {
            currentTab = $(".DiaryTabs").tabs('option', 'selected');
        }
        return currentTab;
    }

    function getTypeDropDown() {
        //Om meal ska inte denna användas
        if ($("#HiddenFieldDate").length == 0) {
            return "";
        }
            //Type-dropdown
            var dropdownType = "<p>Add this to</p><select class='DropDownList DropDownListType'>";
            var selected = getCurrentTab();
            if (selected == 0) {
                selected = 1;
            }

            for (var y = 1; y < 7; y++) {
                var title = "";
                var value = 1;
                if (y == 1) {
                    title = "Breakfast";
                    value = 1;
                } else if (y == 2) {
                    title = "Early Snack";
                    value = 4;
                } else if (y == 3) {
                    title = "Lunch";
                    value = 2;
                } else if (y == 4) {
                    title = "Afternoon Snack";
                    value = 5;
                } else if (y == 5) {
                    title = "Dinner";
                    value = 3;
                } else if (y == 6) {
                    title = "Other";
                    value = 6;
                }
                var stringSelected = "";
                if (selected == value) {
                    stringSelected = " selected";
                }
                dropdownType += "<option value='" + value + "'" + stringSelected + ">" + title + "</option>";
            }
            dropdownType += "</select>";
            return dropdownType;
    }

    function showNotification(message) {
        if (message == "error") {
            $.jGrowl("<img src='../images/kryss-diary.png' class='Icon' alt='Some fields were missing' />Some fields were missing");
        } else if (message == "denied") {
        var link = "<strong>Please see <a title='Problems with new diary' href='http://www.shapeupclub.com/Faq.aspx#33'>FAQ</a> for more information.</strong>";
        $.jGrowl("<img src='../images/kryss-diary.png' class='Icon' alt='Error' />Error validating user. You might need to login again.<br/><br/>" + link, { life: 10000 });
        } else if (message == "servererror") {
            var link = "<strong>Please see <a title='Problems with new diary' href='http://www.shapeupclub.com/Faq.aspx#33'>FAQ</a> for more information.</strong>";
            $.jGrowl("<img src='../images/kryss-diary.png' class='Icon' alt='Error' />Error when loading data<br/><br/>" + link, { life: 10000 });
        } else {
            $.jGrowl("<img src='../images/checkmark-dagbok.png' class='Icon' alt='" + message + "' />" + message);
        }
    }

    function queryString(query) {
        var returnString = getQueryString()[query];
        if (returnString) {
            return returnString;
        } else {
            return "";
        }
    }

    function getQueryString() {
        var assoc = new Array();
        var queryString = unescape(location.search.substring(1));
        var keyValues = queryString.split('&');
        for (var i in keyValues) {
            var key = keyValues[i].split('=');
            assoc[key[0]] = key[1];
        }
        return assoc;
    }


