// global menu state
var menuReady = false;

// pre-cache menubar image pairs
if (document.images) {
    var imagesNormal = new Array();
    imagesNormal["products"] = new Image(26, 100);
    imagesNormal["products"].src = "Navigation_Bar_r2_c1.gif";
    imagesNormal["aboutTixana"] = new Image(26, 100);
    imagesNormal["aboutTixana"].src  = "Navigation_Bar_r2_c2.gif";
    imagesNormal["aboutSoy"] = new Image(26, 100);
    imagesNormal["aboutSoy"].src  = "Navigation_Bar_r2_c3.gif";
    imagesNormal["recipes"] = new Image(26, 98);
    imagesNormal["recipes"].src = "Navigation_Bar_r2_c4.gif";
    imagesNormal["whereToBuy"] = new Image(26, 102);
    imagesNormal["whereToBuy"].src  = "Navigation_Bar_r2_c5.gif";
    imagesNormal["links"] = new Image(26, 93);
    imagesNormal["links"].src  = "Navigation_Bar_r2_c6.gif";
    
    
		
    var imagesHilite = new Array();
    imagesHilite["products"] = new Image(26, 100);
    imagesHilite["products"].src = "Navigation_Bar_r2_c1_f2.gif";
    imagesHilite["aboutTixana"] = new Image(26, 100);
    imagesHilite["aboutTixana"].src  = "Navigation_Bar_r2_c2_f2.gif";
    imagesHilite["aboutSoy"] = new Image(26, 100);
    imagesHilite["aboutSoy"].src  = "Navigation_Bar_r2_c3_f2.gif";
    imagesHilite["recipes"] = new Image(26, 98);
    imagesHilite["recipes"].src = "Navigation_Bar_r2_c4_f2.gif";
    imagesHilite["whereToBuy"] = new Image(26, 102);
    imagesHilite["whereToBuy"].src  = "Navigation_Bar_r2_c5_f2.gif";
    imagesHilite["links"] = new Image(26, 93);
    imagesHilite["links"].src  = "Navigation_Bar_r2_c6_f2.gif";
	
}

function getElementStyle(elem, IEStyleProp, CSSStyleProp) {
    if (elem.currentStyle) {
        return elem.currentStyle[IEStyleProp];
    } else if (window.getComputedStyle) {
        var compStyle = window.getComputedStyle(elem, "");
        return compStyle.getPropertyValue(CSSStyleProp);
    }
    return "";
}

// carry over some critical menu style sheet attribute values
var CSSRuleValues = {menuItemHeight:"20px",
                     menuItemLineHeight:"2.0em",
                     menuWrapperBorderWidth:"2px",
                     menuWrapperPadding:"8px",
                     defaultBodyFontSize:"12px"
                    };

// specifications for menu contents and menubar image associations
var menus = new Array();
menus[0] = {mBarImgId:"menuImg_1",
            mBarImgNormal:imagesNormal["products"],
            mBarImgHilite:imagesHilite["products"],
            menuItems:[ {text:"Snack foods", href:"SoyaKingSnacks.htm"},
                        {text:"Tofu", href:"Tofu.htm"},
						{text:"Soy Milk", href:"SoyaMilk.htm"},
                        {text:"Sauces", href:"Sauces.htm"},
						{text:"Marinades", href:"Marinades.htm"},
						{text:"Piranha", href:"Piranha.htm"}
                      ],
            elemId:""
           };
menus[1] = {mBarImgId:"menuImg_2",
            mBarImgNormal:imagesNormal["aboutTixana"],
            mBarImgHilite:imagesHilite["aboutTixana"],
            menuItems:[ {text:"History", href:"AboutTixana_History.htm"},
                        {text:"Innovation", href:"AboutTixana_Innovation.htm"},
                        {text:"Food Safety", href:"AboutTixana_FoodSafety.htm"},
						{text:"Values", href:"AboutTixana_Values.htm"}
                      ],
            elemId:""
           };
menus[2] = {mBarImgId:"menuImg_3", 
            mBarImgNormal:imagesNormal["aboutSoy"],
            mBarImgHilite:imagesHilite["aboutSoy"],
            menuItems:[ {text:"Soyfoods", href:"Soyfoods.htm"},
                        {text:"Soy & Health", href:"Soy&Health.htm"},
                        {text:"Soy Research", href:"SoyResearch.htm"},
						{text:"Fact sheets", href:"FactSheets.htm"},
						{text:"Industry Trends", href:"IndustryTrends.htm"}
                      ],
            elemId:""
           };

menus[3] = {mBarImgId:"menuImg_4", 
            mBarImgNormal:imagesNormal["recipes"],
            mBarImgHilite:imagesHilite["recipes"],
            menuItems:[ {text:"Tofu Recipes", href:"TofuRecipes.htm"},
						{text:"Recipe Links", href:"LifestyleMenu.htm"},
						{text:"Recipe Books", href:"RecipeBooks.htm"}
                      ],
            elemId:""
           };

menus[4] = {mBarImgId:"menuImg_5", 
            mBarImgNormal:imagesNormal["whereToBuy"],
            mBarImgHilite:imagesHilite["whereToBuy"],
            menuItems:[ {text:"Snackfoods", href:"WhereToBuy_Snackfoods.htm"},
                        {text:"Tofu", href:"WhereToBuy_Tofu.htm"},
                        {text:"Soymilk", href:"WhereToBuy_Soymilk.htm"},
						{text:"Piranha", href:"WhereToBuy_Piranha.htm"},
						{text:"Sauces", href:"WhereToBuy_Sauces.htm"},
						{text:"NZ stockists", href:"WhereToBuy_NZ.htm"},
						{text:"UK stockists", href:"WhereToBuy_UK.htm"}
                      ],
            elemId:""
           };
menus[5] = {mBarImgId:"menuImg_6", 
            mBarImgNormal:imagesNormal["links"],
            mBarImgHilite:imagesHilite["links"],
            menuItems:[ {text:"Food Regulation", href:"Links_FoodRegulation.htm"},
                        {text:"Soyfood Sites", href:"Links_SoyfoodSites.htm"},
                        {text:"Vegetarian links", href:"Links_VegetarianLinks.htm"},
						{text:"On-line Grocers", href:"Links_OnlineGrocers.htm"},
						{text:"Your Health", href:"Links_YourHealth.htm"}
                      ],
            elemId:""
           };
		   
// create hash table-like lookup for menu objects with id string indexes
function makeHashes() {
    for (var i = 0; i < menus.length; i++) {
        menus[menus[i].elemId] = menus[i];
        menus[menus[i].mBarImgId] = menus[i];
    }
}

// assign menu label image event handlers
function assignLabelEvents() {
    var elem;
    for (var i = 0; i < menus.length; i++) {
        elem = document.getElementById(menus[i].mBarImgId);
        elem.onmouseover = swap;
        elem.onmouseout = swap;
    }
}

// invoked from init(), generates the menu div elements and their contents.
// all this action is invisible to user during construction
function makeMenus() {
    var menuDiv, menuItem, itemLink, mbarImg, textNode, offsetLeft, offsetTop;
    
    // determine key adjustment factors for the total height of menu divs
    
    var menuItemH = 0;
    var bodyFontSize = parseInt(getElementStyle(document.body, "fontSize", "font-size"));
    // test to see if browser's font size has been adjusted by the user
    // and that the new size registers as an applied style property
    if (bodyFontSize == parseInt(CSSRuleValues.defaultBodyFontSize)) {
        menuItemH = (parseFloat(CSSRuleValues.menuItemHeight));
    } else {
        // works nicely in Netscape 7
        menuItemH = parseInt(parseFloat(CSSRuleValues.menuItemLineHeight) * bodyFontSize);
    }
    var heightAdjust = parseInt(CSSRuleValues.menuWrapperPadding) + 
        parseInt(CSSRuleValues.menuWrapperBorderWidth);
    if (navigator.appName == "Microsoft Internet Explorer" && 
        navigator.userAgent.indexOf("Win") != -1 && 
        (typeof document.compatMode == "undefined" || 
        document.compatMode == "BackCompat")) {
        heightAdjust = -heightAdjust;
    }
    
    // use menus array to drive div creation loop
    for (var i = 0; i < menus.length; i++) {
        menuDiv = document.createElement("div");
        menuDiv.id = "popupmenu" + i;
        // preserve menu's ID as property of the menus array item
        menus[i].elemId = "popupmenu" + i;
        menuDiv.className = "menuWrapper";
        if (menus[i].menuItems.length > 0) {
            //menuDiv.style.height = (menuItemH * menus[i].menuItems.length) - 
            //heightAdjust + "px";
        } else {
            // don't display any menu div lacking menu items
            menuDiv.style.display = "none";
        }
        // define event handlers
        menuDiv.onmouseover = keepMenu;
        menuDiv.onmouseout = requestHide;

        // set stacking order in case other layers are around the page
        menuDiv.style.zIndex = 1000;
		
		//var menuWidth = 0;
		
        // assemble menu item elements for inside menu div
        for (var j = 0; j < menus[i].menuItems.length; j++) {

   			var mWidth = document.getElementById(menus[0].mBarImgId);

			var menuWidth = mWidth.width;
			
			//var mWidth = document.getElementById(menus[i].menuItems[j]);
			
			//var menuWidth = mWidth.width + 50;

    		//var textL = document.getElementById(menus[i].menuItems[j].text);

			//mW += textL.length;

            //textLength = menus[i].menuItems[j].text;
			
			//menuWidth += textLength.length;

            menuItem = document.createElement("div");
            menuItem.id = "popupmenuItem_" + i + "_" + j;
            menuItem.className = "menuItem";
            menuItem.onmouseover = toggleHighlight;
            menuItem.onmouseout = toggleHighlight;
            menuItem.onclick = hideMenus;
            menuItem.style.top = 0;		
            menuItem.style.left = (menuWidth + 10) /*menuItemH*/* j + "px";
            itemLink = document.createElement("a");
            itemLink.href = menus[i].menuItems[j].href;
            itemLink.className = "menuItem";
            itemLink.onmouseover = toggleHighlight;
            itemLink.onmouseout = toggleHighlight;
            textNode = document.createTextNode(menus[i].menuItems[j].text);			
            itemLink.appendChild(textNode);
            menuItem.appendChild(itemLink);
			
			//menuDiv.style.left = j * 1000/*mBarImg.width*/;
            
			menuDiv.appendChild(menuItem);
        }
        // append each menu div to the body
        document.body.appendChild(menuDiv);
    }
    makeHashes();
    assignLabelEvents();
    // pre-position menu
    for (i = 0; i < menus.length; i++) {
        positionMenu(menus[i].elemId);
    }
    menuReady = true;
}

// initialize global that helps manage menu hiding
var timer;

// invoked from mouseovers inside menus to cancel hide
// request from mouseout of menu bar image et al.
function keepMenu() {
    clearTimeout(timer);
}

function cancelAll() {
    keepMenu();
    menuReady = false;
}

// invoked from mouseouts to request hiding all menus
// in 1/4 second, unless cancelled
function requestHide() {
    timer = setTimeout("hideMenus()", 2000);
}

// "brute force" hiding of all menus and restoration
// of normal menu bar images
function hideMenus() {
    for (var i = 0; i < menus.length; i++) {
       document.getElementById(menus[i].mBarImgId).src = menus[i].mBarImgNormal.src;
       var menu = document.getElementById(menus[i].elemId)
       menu.style.visibility = "hidden";
    }
}

// set menu position just before displaying it
function positionMenu(menuId){

    // use the menu bar image for position reference of related div
    var mBarImg = document.getElementById(menus[menuId/*0*/].mBarImgId);
	
	
	if(menus[menuId].mBarImgId == "menuImg_1") {
	var offsetLeft = 0;
	} 
	else if(menus[menuId].mBarImgId == "menuImg_2") {
	var offsetLeft = -mBarImg.width;
	} 
	else if(menus[menuId].mBarImgId == "menuImg_3") {
	var offsetLeft = -mBarImg.width*2;
	} 
	else if(menus[menuId].mBarImgId == "menuImg_4") {
	var offsetLeft = -mBarImg.width*1 - 2;
	} 
	else if(menus[menuId].mBarImgId == "menuImg_5") {
	var offsetLeft = -mBarImg.width*4 + 10;
	} 
	else if(menus[menuId].mBarImgId == "menuImg_6") {
	var offsetLeft = -mBarImg.width*3 - 22;
	} 
	else if(menus[menuId].mBarImgId == "menuImg_7") {
	var offsetLeft = -mBarImg.width*2+20;
	} 
	
	
	
	else {
	var offsetLeft = -mBarImg.width;//0;
	}
	
    var offsetTrail = mBarImg;
	
	//POSITIONS THE DROP DOWN BAR LEFT OR RIGHT ^
	

	
	var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && 
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    var menuDiv = document.getElementById(menuId);
    menuDiv.style.left = offsetLeft + "px";
    menuDiv.style.top = offsetTop + mBarImg.height + "px";
}

// display a particular menu div
function showMenu(menuId) {
    if (menuReady) {
        keepMenu();
        hideMenus();
        positionMenu(menuId);
        var menu = document.getElementById(menuId);
        menu.style.visibility = "visible";
    }
}

// menu bar image swapping, invoked from mouse events in menu bar
// swap style sheets for menu items during rollovers
function toggleHighlight(evt) {
    evt = (evt) ? evt : ((event) ? event : null);
    if (typeof menuReady != "undefined") {
        if (menuReady && evt) {
            var elem = (evt.target) ? evt.target : evt.srcElement;
            if (elem.nodeType == 3) {
                elem = elem.parentNode;
            }
            if (evt.type == "mouseover") {
                keepMenu();
                elem.className ="menuItemOn";
            } else {
                elem.className ="menuItem";
                requestHide();
            }
            evt.cancelBubble = true;
        }
    }
}

function swap(evt) {
    evt = (evt) ? evt : ((event) ? event : null);
    if (typeof menuReady != "undefined") {
        if (evt && (document.getElementById && document.styleSheets) && menuReady) {
            var elem = (evt.target) ? evt.target : evt.srcElement;
            if (elem.className == "menuImg") {
                if (evt.type == "mouseover") {
                    showMenu(menus[elem.id].elemId);
                    
					//Image Rollover
					
					elem.src = menus[elem.id].mBarImgHilite.src;
                } else if (evt.type == "mouseout") {
                    requestHide();
                }
                evt.cancelBubble = true;
            }
        }
    }
}

// create menus only if key items are supported
function initMenus() {
    if (document.getElementById && document.styleSheets) {
        setTimeout("makeMenus()", 5);
        window.onunload=cancelAll;
    }
}
