/* Analysis Section */

function fillSpanValues(option) {
    spans = document.getElementsByTagName('span');
	for(i=0;i<spans.length;i++){
        if(spans[i].id != '') {
            setNutrientValue(spans[i], option);
            setNutrientUnit(spans[i], option);
            setServingSize(spans[i], option);
            computeKJValue(spans[i]);
            computeDailyValue(spans[i], option);
            setInflammationFactor(spans[i], option);
            setEstimatedGlycemicLoad(spans[i], option);
        }
	}
}

function setNutrientValue(span, option) {
    if(span.id.indexOf('NUTRIENT_') == 0){
        multiplier = option.value / 100;
        nutrientValue = eval('foodNutrients.' + span.id);
        if(typeof(nutrientValue) != 'undefined') {
            if(nutrientValue == '~') {
                span.innerHTML = nutrientValue;
            } else if (nutrientValue.indexOf('~') == 0){
                span.innerHTML = '~';
                span.innerHTML += sig4(parseFloat(scrubTilde(nutrientValue)) * multiplier);
            } else {
                span.innerHTML = sig4(parseFloat(nutrientValue) * multiplier);
            }
        }
    }
}

function setNutrientUnit(span, option) {
    if(span.id.indexOf('UNIT_NUTRIENT_') == 0){
        nutrientUnit = eval('foodNutrients.' + span.id);
        if(typeof(nutrientUnit) != 'undefined') {
            span.innerHTML = nutrientUnit;
        } else {
            span.innerHTML = '&nbsp;';
        }
    }
}

function setServingSize(span, option) {
    if(span.id.indexOf('servingsize') == 0) {
        span.innerHTML = option.text;
    }
}

function computeKJValue(span) {
    if(span.id.indexOf('KJ_NUTRIENT_') == 0){
        nutrientValue = scrubTilde(document.getElementById(span.id.substr(3)).innerHTML);
        if(!isNaN(nutrientValue)){
            num = sig4(nutrientValue * 4.1868);
            spans[i].innerHTML = '(' + num + ' kJ)';
        } else {
            span.innerHTML = '&nbsp;';
        }
    }
}

function computeDailyValue(span, option) {
    if(span.id.indexOf('DV_NUTRIENT_') == 0){
        value = calculateDailyValue(span.id, option.value);
        if(value == null){
            span.innerHTML = '&nbsp;';
        } else if (value == '~'){
            span.innerHTML = value;
        } else {
            span.innerHTML = value + '%';
        }
    }
}

function calculateDailyValue(id, weight) {
    dailyValue = eval('foodNutrients.' + id) || null;
    baseNutrientValue = eval('foodNutrients.' + id.substr(3)) || null;
    isApproximate = baseNutrientValue.match('~[0-9\.]+');
    baseNutrientValue = scrubTilde(baseNutrientValue);
    if(baseNutrientValue && dailyValue && dailyValue != '~'){
        dailyValue = scrubTilde(dailyValue);
        nutrientValue = parseFloat(baseNutrientValue) * weight / 100;
        value = dailyValue == 0 ? 0 : Math.round(100 * nutrientValue / dailyValue);
        if(isApproximate){
            value = '~' + value;
        }
    } else {
        value = dailyValue;
    }
    return value;
}

function wrapCalculateDailyValue(id, weight) {
    value = calculateDailyValue(id, weight);
    if(value) {
        return scrubTilde(value.toString());
    }
    return 0;
}

function scrubTilde(value) {
    if(value == null || typeof(value) == 'undefined') return null;
    return value == '~' ? 0 : value.indexOf('~') == 0 ? value.replace('~', '') : value;
}

function setEstimatedGlycemicLoad(span, option) {
	var EGLSlider = document.getElementById("egl_slider_on").style;
	
    if(span.id.indexOf('SCORE_ESTIMATED_GLYCEMIC_LOAD') == 0){
        multiplier = option.value / 100;
        scoreValue = eval('foodNutrients.' + span.id);
        scoreValue = isNaN(scoreValue) ? scoreValue : Math.round(parseFloat(scoreValue) * multiplier);
        span.innerHTML = scoreValue;
        setEstimatedGlycemicLoadDetails(scoreValue);
		
		EGLSlider.width = Math.round(scoreValue * 77/250) + 'px';
    }
}

function setEstimatedGlycemicLoadDetails(score) {
    textSpan = document.getElementById('egl_on');
    if (textSpan) {
        if(isNaN(score)) {
            textSpan.style.visibility = '0px';
        } else {
            textSpan.style.width = eval(score / 2.5) + 'px';
        }
    }
}

function setInflammationFactor(span, option) {
	
    if ( span.id.indexOf('SCORE_INFLAMMATION_FACTOR') == 0 ) {
        aifr = eval(foodNutrients.aifr);
        //determine if the 'serving' dropdown exists
        var scoreValue;
        servingSelect = document.getElementsByName("serving");
        if (servingSelect.length == 0) { //in TC
            scoreValue = aifr[aifr.length - 1];
        } else {   //in analysis
            scoreValue = aifr[option.index];
        }        
        score = !isNaN(scoreValue) ? Math.round(parseFloat(scoreValue)) : scoreValue;        
        span.innerHTML = score;
        setInflammationFactorDetails(score);
	}
}

function setInflammationFactorDetails(score) {
	var IFSliderPos = document.getElementById("if_slider_on").style;
	
    if ( isNaN(score)) {
		IFSliderPos.backgroundPosition = '0px 0px';
		return;
    }
    text = 'neutral';

    if(score != 0) {
        if (Math.abs(score) < 100) {
            text = 'mildly';
        } else if (Math.abs(score) > 250) {
            text = 'strongly';
        } else {
            text = 'moderately';
        }
    }

	if (score <= -500) {
		text += ' inflammatory';
		IFSliderPos.backgroundPosition = '0px -26px';
		IFSliderPos.width = '38px';
		IFSliderPos.marginLeft = '0px';
	}
	else if (score >= -499 && score < 0) {
        text += ' inflammatory';
		IFSliderPos.backgroundPosition = '0px -13px';
		IFSliderPos.width = Math.round(score * 38/500 * -1) + 'px';
		IFSliderPos.marginLeft = Math.round(score * 38/500 + 38) + 'px';
    } else if (score > 0) {
        text += ' anti-inflammatory';
		IFSliderPos.backgroundPosition = '39px -13px';
		IFSliderPos.width = Math.round(score * 38/500 + 38) + 'px';
    }
    textSpan = document.getElementById('DETAIL_INFLAMMATION_FACTOR');
    if (textSpan) {
        textSpan.innerHTML = text;
    }
}

function sig4(num){
    // round to 4 significant digits
    if(num<100){
        num=Math.round(num*10) / 10;
        if(num==Math.round(num)) {
            return num + '.0';
        } else {
            return num;
        }
    }
    return Math.round(num,3-Math.floor(Math.log(num)/Math.log(10)));
}

function buildAddToMyNdUrl(foodId, foodMeasureIdx) {
    buildGenericFoodServingUrl('/mynd/add/', foodId, foodMeasureIdx);
}

function buildAddToRecipeUrl(foodId, foodMeasureIdx) {
    buildGenericFoodServingUrl('/mynd/myrecipes/recipe-add/', foodId, foodMeasureIdx);
}

function buildAddToMyTrackingUrl(foodId, foodMeasureIdx) {
    buildGenericFoodServingUrl('/mynd/myfoods/mytracking-add/', foodId, foodMeasureIdx)
}

function generateLabel(foodId, foodMeasureIdx) {
    buildGenericFoodServingUrl('/generate-label/', foodId, foodMeasureIdx);
}

function buildGenericFoodServingUrl(uriPrefix, foodId, foodMeasureIdx) {
    url = uriPrefix;
    if (foodId > 0 ) {
        url += foodId + '/';
        if(typeof(foodMeasureIdx) != 'undefined'){
            url += foodMeasureIdx + '/';
        }
    } else {
        url += eval('foodNutrients.FOODSERVING_URI_' + foodMeasureIdx) + '.html';
    }
    window.location = url;
}

if(navigator.userAgent.indexOf("Mac") != -1 && navigator.userAgent.indexOf("Safari") != -1 && location.href.indexOf('print') != -1 ){
document.write('<style> body:last-child:not(:root:root) #forSafari {display: block; position: relative; top: -20px;}</style>');}

if(location.href.indexOf('print') != -1 ){
document.write('<style>#food-summary-container{margin-left: -8px;}#nutrition-info-container{margin-left: -8px;}/*IE6\*/* html .left{position: relative;}/*IE6*/ /*IE7*/ *:first-child+html #facebox .popup {top: 20px;} /*IE7*/ *:first-child+html a.facelink{display: none; visibility: hidden;}</style>');}

if(location.href.indexOf('total') != -1 ){
document.write('<style>body:last-child:not(:root:root) #food-summary-container{margin-left: 8px;} body:last-child:not(:root:root) #nutrition-info-container{margin-left: 8px;} body:last-child:not(:root:root) a.facelink{display: none;}/*IE7*/ *:first-child+html #food-summary-container{margin-left: 8px;} /*IE7*/ *:first-child+html #nutrition-info-container{margin-left: 8px;} /*IE7*/ *:first-child+html a.facelink{display: none; visibility: hidden;} /*IE7*/ *:first-child+html #facebox .popup {top: 0px;} a.facelink{display: none; visibility: hidden;}</style>');}
   
function SafariPrint(){

    $('#forSafari').click(function(){
    $('.infoe').fadeIn('fast');
    });

    $('.close_image').click(function(){
    $('.infoe').fadeOut('fast');
    
    });
}
