
/**
 * Nutrition-class
 * @class Nutrition
 * @property {array} foods IDs of the selected foods
 * @property {string} nutrisource Source of nutritional information
 * @property {string} foodlistname Inline-edited foodlist name
 */
function Nutrition(){

    that = this;
    this.foods = new Array;
    this.nutrisource = "usda";
    this.foodlistname = "Foodlist name (click to edit)";
    
    /** Have initializations been made, once?
     * @private
     * @type boolean
     */
    var firstcontentLoaded = false;
    
    /** Searches for foods containing given searchstring in their name
     * @function searchFoods
     * @param {string} searchstring
     */
    this.searchFoods = function(searchstring){
    
        searchstring = escape(search.checkSearchstring(searchstring));
        
        var indnutr = document.getElementById('indnutr').options[document.getElementById('indnutr').selectedIndex].value;
        var indoper = document.getElementById('indoper').options[document.getElementById('indoper').selectedIndex].value;
        var indval = document.getElementById('indval').value;
        
        if (indnutr > 0 && indval > 0) {
        
            $('#foodnamesgroup').load("nutritiontactician/loadcontent.php", {
                action: "searchfoodnames",
                nutrisource: this.nutrisource,
                searchstring: searchstring,
                indnutr: indnutr,
                indoper: indoper,
                indval: indval
            });
            
        }
        
        else {
        
            indnutr = "";
            indoper = "";
            indval = "";
            
            $('#foodnamesgroup').load("nutritiontactician/loadcontent.php", {
                action: "searchfoodnames",
                nutrisource: this.nutrisource,
                searchstring: searchstring
            });
            
        }
        
        document.getElementById('foodgroup').selectedIndex = 0;
        
    };
    
    /** Searches for foods containing given searchstring in their name (standalone -version)
     * @function searchFoods_SA
     * @param {string} searchstring
     * @param {string} nutrisource
     */
    this.searchFoods_SA = function(searchstring, nutrisource, firstrow){
    
        searchstring = escape(search.checkSearchstring(searchstring));
        
        $('#nutrition').load("nutritiontactician/loadcontent.php", {
            action: "searchfoodnames",
            nutrisource: nutrisource,
            searchstring: searchstring,
            firstrow: firstrow,
            standalone: 'true',
            clienttype: 'desktopbrowser'
        });
        
    };
    
    /**
     * List nutrition levels (standalone -version)
     * @function listNutritionLevels_SA
     * @param {string} nutrition
     * @param {string} nutrisource
     */
    this.listNutritionLevels_SA = function(nutrition, nutrisource, firstrow){
    
        $('#nutrition').load("nutritiontactician/loadcontent.php", {
            action: "listnutritionlevels",
            nutrisource: nutrisource,
            nutrition: nutrition,
            firstrow: firstrow,
            standalone: 'true',
            clienttype: 'desktopbrowser'
        });
        
    };
    
    /**
     * Shows foods for a given foodgroup
     * @function showFoodNames
     * @param {int|String} foodgroup
     */
    this.showFoodNames = function(foodgroup){
    
        var indnutr = document.getElementById('indnutr').options[document.getElementById('indnutr').selectedIndex].value;
        var indoper = document.getElementById('indoper').options[document.getElementById('indoper').selectedIndex].value;
        var indval = document.getElementById('indval').value;
        
        if (indnutr > 0 && indval > 0) {
        
            $('#foodnamesgroup').load("nutritiontactician/loadcontent.php", {
                action: "showfoodgroup",
                nutrisource: this.nutrisource,
                foodgroup: foodgroup,
                indnutr: indnutr,
                indoper: indoper,
                indval: indval
            });
            
        }
        
        else {
        
            indnutr = "";
            indoper = "";
            indval = "";
            
            $('#foodnamesgroup').load("nutritiontactician/loadcontent.php", {
                action: "showfoodgroup",
                nutrisource: this.nutrisource,
                foodgroup: foodgroup
            });
            
        }
        
    };
    
    /**
     * Shows foods for a given foodgroup
     * @function showFoodNames_SA
     * @param {int|String} foodgroup
     */
    this.showFoodNames_SA = function(foodgroup, firstrow){
    
        if (foodgroup == "none") {
        
            $("#nutrition").empty();
            
        }
        
        else {
        
            $('#nutrition').load("nutritiontactician/loadcontent.php", {
                action: "showfoodgroup",
                nutrisource: 'usda',
                foodgroup: foodgroup,
                firstrow: firstrow,
                standalone: true,
                clienttype: 'desktopbrowser'
            });
            
        }
        
    };
    
    /**
     * Shows nutritions for selected foods
     * @function showNutritions
     */
    this.showNutritions = function(){
    
        var foodids = this.foods.join('_AND_');
        var command = document.getElementById('command').options[document.getElementById('command').selectedIndex].value;
        
        $('#resultsgroup').load("nutritiontactician/loadcontent.php", {
            action: "shownutrition",
            nutrisource: this.nutrisource,
            command: command,
            foodids: foodids
        });
        
    };
    
    /**
     * Shows nutritions for selected foods (standalone -version)
     * @function showNutritions_SA
     * @param {string} element
     * @param {command} command
     * @param {string} foodids
     * @param {string} nutrisource
     */
    this.showNutritions_SA = function(element, command, foodids, nutrisource){
    
        $('#' + element).load("nutritiontactician/loadcontent.php", {
            action: "shownutrition",
            nutrisource: nutrisource,
            command: command,
            foodids: foodids,
            standalone: 'true',
            clienttype: 'desktopbrowser'
        });
        
    };
    
    /**
     * Shows edit table for selected foods (standalone -version)
     * @function showEditTable_SA
     * @param {string} element
     * @param {string} foodids
     * @param {string} nutrisource
     */
    this.showEditTable_SA = function(element, foodids, nutrisource){
    
        $('#' + element).load("nutritiontactician/loadcontent.php", {
            action: "showfoodeditable",
            nutrisource: nutrisource,
            foodids: foodids,
            standalone: 'true',
            clienttype: 'desktopbrowser'
        });
        
    };
    
    /**
     * Adds a food to the foodlist
     * @function addFoodToList
     * @param {int} foodid
     * @param {string} foodname
     */
    this.addFoodToList = function(foodid, foodname){
    
        $('#selectedfoodsinner').append("<li onclick=\"$(this).remove(); nutrition.foods.splice(nutrition.foods.findPlace('" + foodid + "'),1)\" onmouseout=\"$(this).css('background-color',''); $(this).css('color','#5AA2A5');\" onmouseover=\"$(this).css('background-color','#CEE6BF'); $(this).css('color','black'); $(this).css('cursor','pointer')\" style=\"color: #5AA2A5; margin: 0px; padding: 0px;\">" + foodname + "</li>");
        this.foods.push(foodid);
        
    };
    
    /**
     * Adds a food to the basket
     * @function addToBasket
     * @param {string} foodid
     */
    this.addToBasket = function(foodid){
    
        var basket = $.cookie('foodbasket');
        
        if (basket != null) {
        
            var foods = basket.split("_AND_");
            if (foods.length == 20) 
                foods.shift();
            
            $.cookie('foodbasket', foods.join("_AND_") + "_AND_" + foodid);
            $(document.body).append('<div id="foodadded">Added...</div>');
            $('#foodadded').css({
                padding: "2px",
                fontSize: "9pt",
                position: "fixed",
                top: "0",
                left: "0",
                background: "green",
                color: "white"
            }).fadeOut("slow", function(){
            
                $('#foodadded').remove();
                
            });
            
        }
        else {
        
            $.cookie('foodbasket', foodid);
            
        }
        
    };
    
    /**
     * Adds multiple foodids to the basket.
     * Will replace earlier basket-cookie
     * @function addStraightToBasket
     * @param {string} foodids
     */
    this.addStraightToBasket = function(foodids){
    
        var foods = foodids.split("_AND_");
        if (foods.length > 20) 
            foods = foods.slice(0, 20);
        if (foods.length > 0) 
            $.cookie('foodbasket', foods.join("_AND_"));
        
    };
    
    /**
     * Removes a food from the basket
     * @function removeFromBasket
     * @param {string} foodid
     */
    this.removeFromBasket = function(foodid, pos){
    
        var basket = $.cookie('foodbasket');
        if (basket != null) {
        
            var basketfoods = basket.split("_AND_");
            
            if (basketfoods.length === 1) 
                $.cookie('foodbasket', null);
            else {
                basketfoods.splice(basketfoods.findPlace(foodid), 1);
                basket = basketfoods.join("_AND_");
                $.cookie('foodbasket', basket);
            }
            $("#" + pos + foodid).remove();
            
            if ($("#multifoodtable > tbody > tr:first-child > td[class^='foodcolumn']").length === 1) 
                $("#nutrition").empty();
            else 
                $("#multifoodtable > tbody > tr > td[class = 'foodcolumn" + pos + "']").remove();
            
        }
        //		else $.cookie('foodbasket', foodid);
    
    };
    
    /**
     * Show nutrition for foods in the basket
     * @function showBasket
     */
    this.showBasket = function(){
    
        var basket = $.cookie('foodbasket');
        if (basket != null) 
            window.location.href = "index.php?foodids=" + basket + "&nutrisource=usda&toolname=nutritiontactician&command=showbasket";
        
    };
    
    /**
     * Loads foods in the basket into table
     * @function editBasket
     */
    this.editBasket = function(){
    
        var basket = $.cookie('foodbasket');
        if (basket != null) 
            window.location.href = "index.php?editfoodids=" + basket + "&nutrisource=usda&toolname=nutritiontactician";
        
    };
    
    
    /**
     * Changes source of nutritional information (either USDA or Fineli)
     * @function changeNutriSourceSelection
     */
    this.changeNutriSourceSelection = function(nutrisource){
    
        if (nutrisource) 
            var nsfunc = nutrisource;
        else 
            var nssel = $('#nutrisourceform').find('input[@checked]').val();
        
        if (((!nutrisource) && (nssel != this.nutrisource)) ||
        ((nutrisource) && (nsfunc != this.nutrisource))) {
        
            $('#foodgroups').load("nutritiontactician/loadcontent.php", {
                action: "foodgroups",
                nutrisource: nsfunc || nssel
            });
            
            if ((nsfunc || nssel) == "usda") {
            
                $('#indicatorgroup').show();
                
                $('#indicator').load("nutritiontactician/loadcontent.php", {
                    action: "indicatornutr",
                    nutrisource: "usda"
                });
                
            }
            
            else {
            
                $('#indicatorgroup').hide();
                
            }
            
            this.nutrisource = nsfunc || nssel;
            
            if (!nsfunc) {
            
                $('#selectedfoodsinner').empty();
                $('#resultsgroup').empty();
                $("#foodnamesgroup").html("<div id='foodnamesgrouparea'></div>");
                this.foods = new Array();
                
            }
            
        }
        
    };
    
    /**
     * Copies a foodlist in a clipboard to the list of selected foods
     * @function editFoodlist
     * @param {int} foodlistclipid
     */
    this.editFoodlist = function(foodlistclipid){
    
        // should there be an alert before overwriting other list?
        
        $('#selectedfoodsinner').load("nutritiontactician/loadcontent.php", {
            action: "getfoodlist",
            foodlistclipid: foodlistclipid
        });
        
        $.post("nutritiontactician/loadcontent.php", {
            action: "getfoodlistids",
            foodlistclipid: foodlistclipid
        }, function(data){
        
            $('#resultsgroup').empty();
            $("#foodnamesgroup").html("<div id='foodnamesgrouparea'></div>");
            nutrition.foods = new Array();
            
            var source = $(data).find("idlist>nutrisource").text();
            
            $(data).find("idlist>foods>food>id").each(function(i){
            
                that.foods.push($(this).text());
                
            });
            
            if (source == 9) {
                that.changeNutriSourceSelection('fineli');
                $("#nutrisourcesform>input[value=fineli]").attr('checked', 'checked');
                $("#nutrisourcesform>input[value=usda]").attr('checked', '');
            }
            else {
                that.changeNutriSourceSelection('usda');
                $("#nutrisourcesform>input[value=usda]").attr('checked', 'checked');
                $("#nutrisourcesform>input[value=fineli]").attr('checked', '');
            }
            
        });
        
    };
    
    /*    
     this.loadSelectedFoods = function(listnumber){
     
     $('#selectedfoods').load("nutritiontactician/loadcontent.php", {
     action: "getsavedlist",
     listnumber: listnumber
     });
     
     };
     */
    /**
     * Saves inline-edited foodlist's title
     * @function saveFoodlistTitle
     * @param {int} id
     * @param {string} value
     */
    this.saveFoodlistTitle = function(id, value){
    
        var clipid = id.substr(id.indexOf('_') + 1);
        
        $.post('clipboard/handleclips.php', {
            action: 'foodlisttitlechange',
            clipid: clipid,
            foodlistname: escape(search.checkSearchstring(value))
        });
        
    };
    
    /**
     * Fills once certain elements with content from server
     * @function loadFirstContent
     */
    this.loadFirstContent = function(){
    
        if (!firstcontentLoaded) {
        
            $('#foodgroups').load("nutritiontactician/loadcontent.php", {
                action: "foodgroups",
                nutrisource: this.nutrisource
            });
            
            if (this.nutrisource == "usda") {
            
                $('#indicator').load("nutritiontactician/loadcontent.php", {
                    action: "indicatornutr",
                    nutrisource: this.nutrisource
                });
                
            }
            
            firstcontentLoaded = true;
            
        }
        
    };
    
    /**
     * Loads foodgroups
     * @function loadFoodgroups_SA
     */
    this.loadFoodgroups_SA = function(){
    
        $('#selectlist_foodgroups').load("nutritiontactician/loadcontent.php", {
            action: "foodgroups",
            nutrisource: 'usda',
            standalone: true,
            clienttype: 'desktopbrowser'
        });
        
    };
    
    /**
     * Loads nutritions
     * @function loadNutritions_SA
     */
    this.loadNutritions_SA = function(){
    
        $('#selectlist_nutritions').load("nutritiontactician/loadcontent.php", {
            action: "nutritions",
            nutrisource: 'usda',
            standalone: true,
            clienttype: 'desktopbrowser'
        });
        
    };
    
    /**
     * Toggle visibility of Nutrition -search form
     * @function toggleNutritionSearchForm
     */
    this.toggleNutritionSearchForm = function(){
    
        $("#nutrition_search_hideout").show();
        
    }
    
}
