/* NUTRITION DATA GLOBAL.JS */

var dartCalls = new Array();
var dartCounter = 0;

/* Navigation*/
var initNavStates = [];
var pagePath = window.location.pathname;

initNavStates['ndhome'] = pagePath == '/' ? '0px -44px' : '0px -22px';
initNavStates['toolsnav'] = pagePath.indexOf('/tools') == 0 ? '0px -44px' : '0px -22px';
initNavStates['topicsnav'] = pagePath.indexOf('/topics') == 0 ? '0px -44px' : '0px -22px';
//initNavStates['pantrynav'] = pagePath.indexOf('/mynd') == 0 ? '0px -44px' : '0px -22px';

if((pagePath.indexOf('/mynd')== 0) || pagePath.indexOf('/prestockedpantries') == 0){
initNavStates['pantrynav'] = '0px -44px';
}
else{
initNavStates['pantrynav'] = '0px -22px';
}
 
initNavStates['helpnav'] = pagePath.indexOf('/help') == 0 ? '0px -44px' : '0px -22px';

function mouseOverTopNavState(divId) {
    var div = document.getElementById(divId);
    if(div){
        div.style.backgroundPosition = '0px 0px';
    }
}

function mouseOutTopNavState(divId) {
    var div = document.getElementById(divId);
    if(div){
        div.style.backgroundPosition = initNavStates[divId];
    }
}

function startList() {
    for(i in initNavStates) {
        topNavItem = document.getElementById(i);
        if(topNavItem) {
            topNavItem.style.backgroundPosition = initNavStates[i];
        }
    }

    var navLists = [];
    navLists[0] = document.getElementById('nav');
    navLists[1] = document.getElementById('tools_subnav');
    navLists[2] = document.getElementById('topics_subnav');
    navLists[3] = document.getElementById('help_subnav');
    navLists[4] = document.getElementById('pantry_subnav');
    
    for (x = 0; x < navLists.length; x++) {
        for (i = 0; i < navLists[x].childNodes.length; i++) {
            node = navLists[x].childNodes[i];
            if (node.nodeName == "LI") {
                node.onmouseover = function() {
                    this.className = "over";
                    if (document.getElementById(this.id + '_iframe')) {
                        document.getElementById(this.id + '_iframe').style.display = "block";
                    }
                }
                node.onmouseout = function() {
                    this.className = "";
                    if (document.getElementById(this.id + '_iframe')){
                        document.getElementById(this.id + '_iframe').style.display = "none";
                   }
                }
            }
        }
    }
}


function showIframe() {
    document.getElementById("help").style.display = "block";
}
/* Navigation*/

/* Conversion Tool */
function convert(n) {
    if (n == 2)
        document.formcon.q0.value = document.formcon.q1.value * (document.formcon.m1.value.substring(1)) / (document.formcon.m0.value.substring(1));
    if (n == 1) {
        var j = document.formcon.m0.value.substring(0, 1);
        if (!j) {
            document.formcon.m0.selectedIndex = 0;
            j = document.formcon.m0.value.substring(0, 1);
        }
        if (j != document.formcon.m1.value.substring(0, 1)) {
            document.formcon.m1.length = 0;
            for (var i = 0; i < document.formcon.m0.length; i++) {
                if (document.formcon.m0.options[i].value.substring(0, 1) == j) {
                    document.formcon.m1.options[document.formcon.m1.length] = new Option(document.formcon.m0.options[i].text, document.formcon.m0.options[i].value);
                }
            }
            document.formcon.m1.selectedIndex = 0;
        }
    }
    document.formcon.q1.value = document.formcon.q0.value * (document.formcon.m0.value.substring(1)) / (document.formcon.m1.value.substring(1));
}

// Function for Custom Food Categories drop down
function categoryOption(target_field, category_id, display_category_id, title, selected_category_id) {
    category_cookie = getCookie("categories");
    if (category_cookie) {
        categories = category_cookie.split(",");
        for (i = 0; i < categories.length; i++) {
            if (categories[i] == parseInt(category_id)) {
                createCategoryOption(target_field, display_category_id, title, selected_category_id);
            }
        }
    } else {
        createCategoryOption(target_field, display_category_id, title, selected_category_id);
    }
}

function createCategoryOption(target_field, category_id, title, selected_category_id) {
    target_field.options[target_field.options.length] = new Option(title, category_id);
    if (selected_category_id == category_id) {
        target_field.selectedIndex = target_field.options.length-1;
    }
}

// Get Cookie Function
function getCookie(name) {
    var start = document.cookie.indexOf(name + "=");
    var len = start + name.length + 1;
    if (( !start ) && ( name != document.cookie.substring(0, name.length) )) {
        return null;
    }
    if (start == -1) return null;
    var end = document.cookie.indexOf(";", len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len, end));
}

function categoryRedirect() {
    if (self.location.pathname.indexOf('/foods-') >= 0 && getCookie('categories') && self.location.toString().indexOf('categories') == -1) {
        window.location = addCategory(window.location.toString());
    }
}

function categoryLink(str) {
    window.location = addCategory(str);
}

function addCategory(str) {
    var category_cookie = getCookie('categories');
    if (str && category_cookie) {
        str += (str.indexOf("?") == -1) ? '?' : '&';
        str += 'categories=' + category_cookie;
    }
    return str;
}

function deleteCookie(cookie_name) {
    if (getCookie(cookie_name)) {
        var now = new Date();
        document.cookie = cookie_name + '=; expires=' + now.toGMTString();
    }
}

/* cache css bg images for IE6 */
if (document.all) {
    try {
        document.execCommand("BackgroundImageCache", false, true);
    } catch(err) {
    }
}

function isLoggedIn() {
    return getCookie("amg_user_info") != null;
}

function displayUserName(userNameDivId, logInControlDivId) {
    if (isLoggedIn()) {
        div = document.getElementById(userNameDivId);
        if (div) {
            var userName = getCookie('amg_user_info');
            div.innerHTML = '<a href=\"/user/logout\"><img border=\"0\" src=\"/images/global/signOut.gif\" /></a>'+'<a href=\"/user/profile_update\"><img class=\"out\" border=\"0\" src=\"/images/global/myprofile.gif\" /></a>';
            setVisibility(userNameDivId, true);
        }
    } else {
        div = document.getElementById(logInControlDivId);
        if (div) {
            setVisibility(logInControlDivId, true);
        }
    }
}

function displayUserControls(loggedInDivId, loggedOutDivId) {
    setVisibility(loggedInDivId, isLoggedIn());
    setVisibility(loggedOutDivId, !isLoggedIn());
}

function setVisibility(divID, showBool) {
    var div = document.getElementById(divID);
    if (div) {
        div.style.display = showBool ? 'inline' : 'none';
    }
}

function contentpick() {}

// Daily Needs
function manageExercise(source, target, targetIndex){
    if(source.value < 0) {
        source.selectedIndex=0;
    } else {
        target.value = source.options[source.selectedIndex].text;
        targetIndex.value = source.selectedIndex;
    }
}

function setSelectedOption(select, selectedIndex) {
    select.selectedIndex = selectedIndex;
}

function toggleVisibility(bool,divId) {
    div = document.getElementById(divId);
    if(div){
        div.style.display = bool ? "block" : "none";
    }
}
function toggleVisibility2(bool,divId) {
    div = document.getElementById(divId);
    if(div){
        div.style.display = bool ? "inline" : "none";
    }
}

function clearDefault(ndtext) {
    if (ndtext.defaultValue==ndtext.value) {
        ndtext.value = "";
    }
}

function randomHeaderImg(imageId){
    var image = document.getElementById(imageId);
    var imgs = [];
    imgs[imgs.length] = '/images/global/header/redyelgreenmix.jpg';
    imgs[imgs.length] = '/images/global/header/greenyellow.jpg';
    imgs[imgs.length] = '/images/global/header/naturemix.jpg';
    imgs[imgs.length] = '/images/global/header/primemix.jpg';
    var i = Math.floor(Math.random() * imgs.length);
    if(image){
        image.src = imgs[i];
    }
}

/**** Shared Onload Event Handler Registration ****/
function runOnLoad(f){
	if(runOnLoad.loaded) f( );
	else runOnLoad.funcs.push(f);
}
runOnLoad.funcs = [];
runOnLoad.loaded = false;
runOnLoad.run = function( ) {
	if (runOnLoad.loaded) return;
	for(var i = 0; i < runOnLoad.funcs.length; i++){
		try{runOnLoad.funcs[i]( );}
		catch(e) {}
	}
	runOnLoad.loaded = true;
	delete runOnLoad.funcs;
	delete runOnLoad.run;
};
if(window.addEventListener) window.addEventListener("load", runOnLoad.run, false);
else if (window.attachEvent) window.attachEvent("onload", runOnLoad.run);
else window.onload = runOnLoad.run;
/*************************************************/

/**** Microsoft Audience Extension ****/
function writeMicrosoftAudienceTag() {
    MSEXT_domain = document.location.host.split('.');
    MSEXT_domain = MSEXT_domain[(MSEXT_domain.length - 2)];
    MSEXT_path = document.location.pathname.split('/');
    MSEXT_request = document.location.protocol + "//view.atdmt.com/action/MSFT_CondeNet_AE_ExtData/v3/atc1." + MSEXT_domain;
    MSEXT_request += (MSEXT_path[1] != '') && (MSEXT_path[1] != undefined) ? "/atc2." + MSEXT_path[1] : '';
    MSEXT_request += (MSEXT_path[2] != '') && (MSEXT_path[2] != undefined) ? "/atc3." + MSEXT_path[2] : '';
    MSEXT_request += '/';
    var footerId = document.getElementById("footerNew");
    var newElem = document.createElement("img");
    newElem.src = MSEXT_request;
    newElem.height = "1";
    newElem.width = "1";
    if(footerId)
        footerId.appendChild(newElem);
}
runOnLoad(writeMicrosoftAudienceTag);
/**************************************/
