// Determine browser type for different layer drawing methods
var browser;
var text_div = '';
var yposLastItem=0;
var layeractive = false;

if (document.layers) {
    browser = "n4";
    layerStyleRef = "layer.";
    layerRef = "document.layers";
    styleSwitch = "";
    pixelRef = "";
    layerTag = "LAYER";
}
if (document.all) {
    browser = "i4";
    layerStyleRef = "";
    layerRef = "document.all";
    styleSwitch = ".style";
    pixelRef = "";
    layerTag = "DIV";
}
if (document.getElementById) {
    browser = "dom";
    layerTag = "DIV";
}

//alert(browser);

// Initialization of global variables
var handle = 0;
var level1 = 0;
var level2 = 0;
var level3 = 0;
var last = false;

// Variables added for multiline menu items
var lastItem = -1;
var lastItemImageWidth  = 0;
var defaultImageHeight  = 16;  // default height of menu images
var defaultLineHeight   = 16;  // default height of menu lines

var cutOffChar     = "-";  // character at which menu item string will be cut off
var startAtChar    = 10;   // cut off a menu item string at first space after startAtChar
var maxTextLength  = 15;   // max length of menu item string

// Get top level URL because of framebased embedded applications
var myUrl = top.location.href;

// Find parameter part
var URLParam = myUrl.lastIndexOf('?')
if (URLParam < 1) {URLParam = myUrl.length;}

// Remove parameter part
var myFileName1 = myUrl.substring(0,URLParam);

// Remove directory part
var myFileName = myFileName1.substring((myFileName1.lastIndexOf('/') + 1), myFileName1.length);

// Variable to hold the number of lines for each item
var Lines=1;

//
// Function: GetCharPos
//Description:  Get the position of the first found 'strChar2Find' in the string 'strInput', starting at 'iStart'
//
// By: M. de Brouwer (DELT ICT Services)
// Date: 30-06-2004
//
function GetCharPos(strChar2Find, strInput, iStart)
{
   var bEnd = false;

   var iPos = 0;

   var strChar = "";

   // Loop trough the entire string 'strInput' and get the position of 'strChar2Find'
   while(bEnd == false)
   {
      // Get the character
      strChar = strInput.charAt(iStart);

      // Investigate the character
      if (strChar == strChar2Find)
      {
         bEnd = true;
      }else
      {
         iPos += 1;
      }

      // Check if the entire string 'strInput' is handled and exit the while loop if so
      if (iStart < strInput.length)
      {
         iStart += 1;
      }else
      {
         bEnd = true;
         iPos = -1;
      }
   }

   return(iPos);
}

//
// Function: ReplaceString
// Description: Replaces 'strOld' with 'strNew' in the string 'strInput'
//
// By: M. de Brouwer (DELT ICT Services)
// Date: 30-06-2004
//
function ReplaceString(strOld, strNew, strInput)
{
   for (var i = 0; i < strInput.length; i++)
   {
      // Check if the string is found
      if (strInput.substring(i, i + strOld.length) == strOld)
      {
         // Replace the old string with the new one
         strInput = strInput.substring(0, i) + strNew + strInput.substring(i + strOld.length, strInput.length);
      }
   }

   // Return the result
   return(strInput);
}

//
// Function: StripWeirdChars
// Description: Replaces all the character references (i.e.: &amp;), with a temporary character (#) with length 1 to correct the length of the original input string
//
// By: M. de Brouwer (DELT ICT Services)
// Date: 30-06-2004
//
function StripWeirdChars(strInput)
{
   var iPosS = -1;
   var iPosE = -1;
   var iStart = 0;

   var bExitLoop = false;

   var strChar = "";
   var strCharRefStart = "&";
   var strCharRefEnd = ";";

   // Replace any ampersands (&) characters with a temporary character with the same length
   strInput = ReplaceString(" & ", " # ", strInput);

   while (bExitLoop == false)
   {
      // Get the character reference start position
      iPosS = GetCharPos(strCharRefStart, strInput, iStart);

      // Check if something is found
      if (iPosS >= 0)
      {
         // Get the character
         strChar = strInput.charAt(iPosS);

         // Investigate the character
         if (strInput.charAt(iPosS + 1) == "  ")
         {
            iStart += 1;
         }else
         {
            // Get the character reference end position
            iPosE = GetCharPos(strCharRefEnd, strInput, iPosS);

            // Extract the character reference from the 'strInput' string
            strChar = strInput.substr(iPosS, (iPosE + strCharRefStart.length));

            // Replace the character reference with a temporary character with length 1
            strInput = ReplaceString(strChar, "#", strInput);
         }
      }else
      {
         bExitLoop = true;
      }
   }

   // Return the result
   return(strInput);
}

// Create tree of item objects
function item(level, text, ref) {
    this.handle = handle++;
    this.level = level;
    /* this.text= cutOffAtChar(cutOffChar,text,startAtChar,maxTextLength); */
    this.text = text;
    this.lines=Lines;    //holds the number of textlines for this item

   // The reason for this extra function is that the new implemented navigation template (june 2004) generates character references (i.e. &amp; or &#233;) instead of
   //     the actual characters like '&' and 'é'. Because of this the length of the menu item text is longer than what is actually displayed on screen.
   //     The 'StripWeirdChars' function removes these references so the length of the menu item text is really what is should be.
   //
   //     Example:
   //
   //     Before: Caf&#233; (length = 9)
   //     After: Café (length = 4)
   //

   var strTemp = "";

   if (this.text.length > maxTextLength)
   {
      strTemp = StripWeirdChars(this.text);
   }

   //if ((this.text.length > maxTextLength) && (this.level != 3) && (this.level != 0))
   if ((strTemp.length > maxTextLength) && (this.level != 3) && (this.level != 0))
   {
      //alert("TEXT= "+items[this].text);
      this.lines +=1;
   }

    this.fullref = ref;
    this.ref = ref.substring((ref.lastIndexOf('/') + 1), ref.length);
    //createDiv(this.handle, this.level, this.text, this.fullref, this.lines);
    this.status = getInitialStatus(this.level);//show level 0 and 1 items, hide level 2 items by default
    this.xpos = 5;  // position from the left side of the page
    this.ypos;
    this.show = show;
    this.hide = hide;
    this.click = click;
    this.expanded = getInitialExpanded(this.level, this.ref);
    this.parent = getParent(this.level,this.handle);
    this.Count = Count;
    this.last = false;
    Lines=1;
}

// Retrieve initial status; true to show item, false not to show
function getInitialStatus(level) {
    var stat;
    if ((level == 0) || (level == 1)) {
        stat = true;
    } else {
        stat = false;
    }
    return stat;
}

// Set initial view status of items in expanded folder
function calculateInitialStatus() {
    var i = 0;
    var totalChildren; // level 2 and level 3 children: goes through the whole handle counter array tree
    for (i; i < handle; i++) {
        if ((items[i].level == 1) && (items[i].expanded == true)) {
            // set status of level 2 children to true, all level 1 items have a true status by default
            var myNextSibling = getNextSibling(i);
            totalChildren = (myNextSibling - i) - 1; // determine amount of children (level 2 and level 3)
            if (totalChildren > 0) { // has children
                var j = 1;
                for (j; j <= totalChildren; j++) {
                    if (items[i+j].level == 2) {// only set level 2 items to true
                        items[i+j].status = true;
                    }
                }
            }
        } else if ((items[i].level == 2) && (items[i].expanded == true)) {
            // set status of siblings in this folder to true, all level 1 items have a true status by default
            var myParent = items[i].parent;
            items[myParent].expanded = true;
            var myPaNeSi = getNextSibling(myParent);
            totalChildren = (myPaNeSi - myParent) - 1; // determine amount of children (level 2 and level 3)
            var j = 1;
            for (j; j <= totalChildren; j++) {
                if (items[myParent+j].level == 2) {// only set level 2 items to true
                    items[myParent+j].status = true;
                }
            }
        } else if ((items[i].level == 3) && (items[i].expanded == true)) {
            // set status of level 2 parent and all siblings in parents folder to true
            var myParent = items[i].parent;
            var myParentsParent = items[myParent].parent;
            items[myParentsParent].expanded = true;
            var myPaPaNeSi = getNextSibling(myParentsParent);
            totalChildren = (myPaPaNeSi - myParentsParent) - 1; // determine amount of children (level 2 and level 3)
            var j = 1;
            for (j; j <= totalChildren; j++) {
                if (items[myParentsParent+j].level == 2) {// only set level 2 items to true
                    items[myParentsParent+j].status = true;
                }
            }
        }
    }
}

// Gets next level 1 sibling
function getNextSibling(n) {
    var nextSibling;
    var i = n + 1;
    for (i; i < handle; i++) {
        if (items[i].level == 1) {
            nextSibling = i;
            return nextSibling;
        }
        if (i == (handle - 1)) { // no next sibling available
            nextSibling = handle;// create imaginary next sibling to calculate amount of children and grandchildren
            return nextSibling;
        }
    }
}

// Checks if the url of the loaded page equals the reference url of an item
function getInitialExpanded(level, ref) {
    if (((level == 1) || (level == 2) || (level == 3)) && (ref == myFileName)) {
        return true;
    }
    return false;
}

// Get the handle of the parent item of level 2 items, -1 for level 0 or level 1 items
function getParent(level, handle) {
    var par=0;
    if (level == 0) { par = -1; }
    if (level == 1) { par = -1; }
    if (level == 2) { par = level1; }
    if (level == 3) { par = level2; }
    if (level == 1) { level1 = handle; }
    if (level == 2) { level2 = handle; }
    if (level == 3) { level3 = handle; }
    return par;
}

// Draw method, only show items with status == true, check image status to show the right images
function drawMenu() {
    var i = 0;
    var children = 0;
    // first loop to determine the last item (for swopping images)
    var l = 0;
    var lastcount = 0;
    for (l; l < handle; l++) {
        if (items[l].status == true) {
            lastcount = l;
        }
    }
    items[lastcount].last = true;
    // second loop to either show or hide items
    var p = -1;
    var totalOfLines=1;
    var teller=0;
    for (i; i < handle; i++) {
        if ((items[i].ref == myFileName) && (items[i].level == 3)) {// for 3rd level items viewing status will never be true
            changeFontToBold(items[i].parent);          // check if parent item needs to have a bold font
        }

        if (items[i].status == true) {
            {
                if (top.location != location) {
                    items[i].ypos = 9 + (defaultLineHeight * totalOfLines);
                } // 9 is y position in left frame
                else {
                    // first element -- 10 is y position from top of block, stylesheet defines distance of top of page
                    items[i].ypos = 10 + (defaultLineHeight * totalOfLines);
                }
                totalOfLines+=items[i].lines;
            };

            // change font to bold if active page else show normal font
            if ((items[i].ref == myFileName) && ((items[i].level == 0) || (items[i].level == 1) || (items[i].level==2))) {
                if (p > -1) { //check if there is a another (parent) item with the same url, then only the cild item should be displayed in bold
                    changeFontToNormal(p);
                }
                changeFontToBold(i);
                p = i;
            }
            else {
                changeFontToNormal(i);
            }
            // level 1
            if (items[i].level == 1) {
                children = items[i].Count();
                if (children > 0) { // has children
                    if (items[i].expanded == true) { // expanded, show level 1 expanded image instead of level 1 default image
                        changeImage(items[i].handle, imgpath+'menu1E_'+color+'.gif', items[i].level);
                    } else { // collapsed, show level 1 collapsed image instead of level 1 default image
                        if (items[i].last == true){ // show last item
                            changeImage(items[i].handle, imgpath+'menu1CL_'+color+'.gif', items[i].level);
                            hideImages(items[i].handle,items[i].lines);
                        } else { // show normal collapsed item
                            changeImage(items[i].handle, imgpath+'menu1C_'+color+'.gif', items[i].level);
                        }
                    }
                } else if (items[i].last == true) {
                    changeImage(items[i].handle, imgpath+'menu1L_'+color+'.gif', items[i].level); // last item
                    hideImages(items[i].handle,items[i].lines);
                } // else default item
            }
            // level 2
            if (items[i].level == 2) {
                if (items[i].last == true) {
                    changeImage(items[i].handle, imgpath+'menu2L_'+color+'.gif', items[i].level); // last item
                    hideImages(items[i].handle,items[i].lines);
                } // else default item
            }
            items[i].show();
            teller=i;
        } else {
            items[i].hide();
        }
    }

    //extendnavigation     hide, change ypos, show;
    yposLastItem = items[teller].ypos+32;
    if (layeractive==false) {
      text_div = '<'+layerTag+' id=en1 name=en2 style="position: absolute; top: '+yposLastItem+'px; left: 5px;">';
      text_div = text_div + '<table width="150" border="0" cellpadding="0" cellspacing="0" class="terms-box">';
      text_div = text_div + '<tr>';
      text_div = text_div + '<td valign="top" scope="row" class="terms-icon">&#160;</td>';
      text_div = text_div + '<td><a href="http://www.dsm.com/en_US/html/about/user_terms.htm" class="underNav" target="_blank">User Terms and Conditions</a></td>';
      text_div = text_div + '</tr><tr>';
      text_div = text_div + '<td colspan="2" align="left" valign="top" scope="row"><img src="../../../static/common/images/empty.gif" width="100" height="3"></td>';
      text_div = text_div + '</tr><tr>';
      text_div = text_div + '<td align="left" valign="top" scope="row" class="terms-icon">&#160;</td>';
      text_div = text_div + '<td><a href="http://www.dsm.com/en_US/html/about/privacy_cookie_statement.htm" class="underNav" target="_blank">Privacy and Cookie Statement</a></td>';
      text_div = text_div + '</tr>';
      text_div = text_div + '</table>';
      text_div = text_div + '</'+layerTag+'>';
      document.writeln(text_div);
      text_div = '';
      layeractive=true;
    }
    if (browser == "n4" || browser == "i4") {
      //eval(layerRef+'["en1"]'+this.handle+'"]'+styleSwitch+'.visibility="hidden"');
      eval(layerRef+'["en1"]'+styleSwitch+'.visibility="hidden"');
      eval(layerRef+'["en1"]'+styleSwitch+'.top='+yposLastItem);
      eval(layerRef+'["en1"]'+styleSwitch+'.visibility="visible"');
    } else if (browser == "dom") {
      document.getElementById('en1').style.visibility = "hidden";
      document.getElementById('en1').style.top = yposLastItem+'px';
      document.getElementById('en1').style.visibility = "visible";
    }

}

// Change font of div/layer to bold
function changeFontToBold(h) {
    if (browser == "i4") {// Font weight can't be changed by NS4
        eval(layerRef+'["font'+h+'"]'+styleSwitch+'.fontWeight="bold"');
    } else if (browser == "dom") {
        document.getElementById('font'+h).style.fontWeight="bold";
    }
}

// Change font of div/layer to normal
function changeFontToNormal(h) {
    if (browser == "i4") {
        eval(layerRef+'["font'+h+'"]'+styleSwitch+'.fontWeight="normal"');
    } else if (browser == "dom") {
        document.getElementById('font'+h).style.fontWeight="normal";
    }
}

// Show object DIV or LAYER
function show() {
    if (browser == "n4" || browser == "i4") {
        eval(layerRef+'["handle'+this.handle+'"]'+styleSwitch+'.top='+this.ypos+pixelRef);
        eval(layerRef+'["handle'+this.handle+'"]'+styleSwitch+'.left='+this.xpos+pixelRef);
        eval(layerRef+'["handle'+this.handle+'"]'+styleSwitch+'.visibility="visible"');
    } else if (browser == "dom") {
        document.getElementById('handle'+this.handle).style.top = this.ypos+'px';
        document.getElementById('handle'+this.handle).style.left = this.xpos+'px';
        document.getElementById('handle'+this.handle).style.visibility = "visible";
    }
}

// Hide object DIV or LAYER
function hide() {
    if (browser == "n4" || browser == "i4") {
        eval(layerRef+'["handle'+this.handle+'"]'+styleSwitch+'.visibility="hidden"');
    } else if (browser == "dom") {
        document.getElementById('handle'+this.handle).style.visibility = "hidden";
    }
}

// Click on level 1 folder and determine wether to expand or collapse
function click() {
    // if this folder is collapsed
    if (this.expanded == false) {
        var i = 0;
        for (i; i < handle; i++) {
            // collapse all; only one folder at a time can be expanded
            items[i].expanded = false;
            if ((items[i].level == 0) || (items[i].level == 1)) {
                items[i].status = true;
            } else {
                items[i].status = false;
            }
            // expand only this folder
            if (items[i].parent == this.handle) {
                items[i].status = true;
            }
        }
        this.expanded = true;
    } else { // if this folder is already expanded
        var i = 0;
        for (i; i < handle; i++) {
            // collapse all
            items[i].expanded = false;
            if ((items[i].level == 0) || (items[i].level == 1)) {
                items[i].status = true;
            } else {
                items[i].status = false;
            }
        }
    }
    drawMenu();
}

// Count the amount of children for level 1 items
function Count() {
    var i=0;
    var c=0;
    for (i; i < handle; i++)
        if (items[i].parent == this.handle)
            c++;
    return c;
}

// Change existing image to another image
function changeImage(handle, img, level) {
    if (browser == "dom" || browser == "i4" ) {
        //alert('img'+handle);
        document.images['img'+handle].src = img;
    } else if (browser == "n4") {
        eval(layerRef+'["handle'+handle+'"].document.images["img'+handle+'"].src="'+img+'"');
    }
}

//Cut off menu item strings according to the following rules:
//1.  If the length of the string is shorter than or equal to <cutoff> characters it is displayed on 1 single line;
//2.  If the string has a <character> after the <space>th character it will be cut up immediately after <character>;
//3.  If the string has no <character> it will be cut up at the last space before the <cutoff>th character;
//4.  When none of the above applies the string will be displayed as is.
function cutOffAtChar(character,text,space,cutoff)
{
   /*
    //character     : character where to cut in string
    //text          : string to investigate
    //space         : position from where to look for spaces
    //cutoff        : position for absolute cut
    var outText = "";
    var first="";
    var last="";
    var charlocation = findChar(character,text,space,cutoff);
    var cut=cutoff;
    if (text.length <= cutoff) { //the length of text is smaller than the maximum allowed length -> do nothing
        outText=text;
    }
    else {//the length of text is greater than the maximum allowed length
        if((charlocation != -1)&&(charlocation > space)&&(charlocation < cutoff)) {//the cutoff character (eg. '-') exists
            //alert("cutoff exists");
            cut = charlocation + 2;
            first = text.substr(0,charlocation + 1);
            last = text.substr(charlocation + 1,text.length);
            if(last.indexOf(" ")==0) {
                last=last.substr(1,last.length);
            }
            outText = first + "<br>&nbsp;&nbsp;" + cutOffAtChar(character,last,space,cutoff);
            Lines++;
        }
        else if(text.indexOf(" ")!=-1) {//string is longer than cutoff characters.
            //now find the best suitable space to cut up the string
            var spacePosition=-1;
            spacePosition=findChar(" ",text,0,text.length);
            first = text.substr(0,spacePosition);
            last = text.substr(spacePosition,text.length);
            if(last.indexOf(" ")==0) {//if line starts with space, take that space away
                last=last.substr(1,last.length);
            }
            outText = first;
            if (last!="") {
                outText+="<br>&nbsp;&nbsp;" + cutOffAtChar(character,last,space,cutoff);
                Lines++;
            }
            else {
                outText=text;
            }
        }
        else {
            outText=text;
        }
    }
    return(outText);
    */
}

//Finds the last char character before max
function findChar(myChar,text,start,max)
{
    var pos   = start;
    var place = start;
    var ok = true;
    while(ok) {
        pos = text.indexOf(myChar,place+1);
        if((pos < max) && (pos != -1)) {
            place = pos;
        }
        else {
            ok = false;
        }
    }
    return(place);
}

// Hide menu images for last item + show images for previous last item
function hideImages(handle,lines)
{
    //reset images for previous lastItem
    if(lastItem!=-1) {
        for(i=1;i<items[lastItem].lines;i++) {
            if (browser == "dom" || browser == "i4" ) {
                document.images['img'+lastItem+'-'+i].width = lastItemImageWidth;
                document.images['img'+lastItem+'-'+i].height = defaultImageHeight;
            } else if (browser == "n4") {
                eval(layerRef+'["handle'+lastItem+'"].document.images["img'+lastItem+'-'+i+'"].width=lastItemWidth');
                eval(layerRef+'["handle'+lastItem+'"].document.images["img'+lastItem+'-'+i+'"].height=defaultImageHeight');
            }
        }
    }

    // 'hide' images for current lastItem (by making dimensions 0x0)
    for(i=1;i<lines;i++)
    {
        if (browser == "dom" || browser == "i4" ) {
            // alert('img'+handle+'-'+i);
            document.images['img'+handle+'-'+i].width=0;
            document.images['img'+handle+'-'+i].height=0;
            lastItemImageWidth=document.images['img'+handle+'-'+i].width;
        }
        else if (browser == "n4") {
            eval(layerRef+'["handle'+handle+'"].document.images["img'+handle+'-'+i+'"].width=0');
            eval(layerRef+'["handle'+handle+'"].document.images["img'+handle+'-'+i+'"].height=0');
            lastItemImageWidth=eval(layerRef['"handle'+handle+'"'].document.images['"img'+lastItem+'-'+i+'"'].width);
        }
    }
    lastItem=items[handle].handle;
}
