//
// If you want a menu to be open initially set the style display to
// "inline" in the subMenu class div like this:
// <div class="subMenu" style="display:inline;">
//
// The fading effect can be disabled by setting the doFading var to false.
//

var menuObjArray = new Array();
menuArray = new Array();                  // List of menus
menuItemArray = new Array();              // List of items
subMenuNumberOfItemsArray = new Array();  // List of corresponding item numbers
menuParentArray = new Array();            //
subMenuHeightArray = new Array();
subMenuIntervalArray = new Array();
subMenuIsVisibleArray = new Array();
subMenuArray = new Array();

var timerSlide = null;
var numberOfMenuItems = 0;
var slideDelay = 10;
var divHeight = 21;
var moveSlidePix = 5;
var isLocked = false;
var doFading = true;
var lastMenuIndex = -1;
var currMenuIndex = -1;
var makeRadioButton = true;

// Initialize this...
(document.addEventListener) ? window.addEventListener('load',InitAll,false)
                            : window.attachEvent('onload',InitAll);
//window.onload = InitAll;

function InitAll()
{
  // Calling all divs
  var divs = document.getElementsByTagName( "DIV" );
  menuStateAry = GetUserCookie("magnaMenuCookv1").split(",");

  // Spin through doument root level looking for looking for 'topItem' class divs,
  // in our case, tab buttons.
  aryNum = 0;
  for( dn = 0; dn < divs.length; dn++ )
  {
    // Once we have one...
    if( String(divs.item(dn).className).substring(0,7) == "topItem" )
    {
      // Restore its last known state
      // Need the menu's parent container, the menu container and the items container
      mainMenuDiv = divs.item(dn).parentNode;
      menuContainerDiv = mainMenuDiv.getElementsByTagName( "DIV" ).item(1);
      itemContainerDiv = menuContainerDiv.getElementsByTagName( "DIV" ).item(0);
//      alert ('Found topItem ' + mainMenuDiv.getElementsByTagName( "DIV" ).item(0).className );
// e.g. topItemVF750C-83

      // Restore height of drop-down menu (subMenu)
      if( "" != menuStateAry )
        itemContainerDiv.style.height = parseInt(menuStateAry[aryNum]) + "px";

      // Watch lights fade from every room...
      // Restore dipslay characteristics if not fading
      if( !doFading )
      {
        // Micro$uck Exploder
        if ( menuContainerDiv.filters )
          menuContainerDiv.style.filter = 'alpha(opacity=100)';

        // Everyone else
        else
          menuContainerDiv.style.opacity = 1;
      }

      // Restore display state of drop-down menu (subMenu)
      itemContainerDiv.style.display = ( "" == menuStateAry
                                      || parseInt(menuStateAry[aryNum]) == 0 )
                                        ? 'none' : 'inline';

      // Now initialize the individual subMenu items
      // and move on to the next menu, if any
      Init( divs.item(dn) );
      aryNum++;
    }
  }
}

function Init( objDiv )
{
  // I'm busy, go away!
  if( isLocked )
    return;

  // Look inside the list of stylesheets to ensure we loaded the proper style sheet
  // Get the rules so we can update them dynamically
  var sheets = document.styleSheets;
  var ruleIndex;
  for( ruleIndex = 0; ruleIndex < sheets.length &&
    (-1 != String(sheets[ruleIndex].href).indexOf("magnaMenu.css"));
      ruleIndex++ );

  // You have to know the rules to get around them (or modify them in this case)
  var styles = (sheets[ruleIndex].cssRules)
                  ? sheets[ruleIndex].cssRules : sheets[ruleIndex].rules;

  // This (objDiv) dropMenu's parent container and subMenu
  var mainMenuDiv, subMenuDiv, menuContainerDiv, itemContainerDiv;
  numberOfMenuItems = 0;
  mainMenuDiv = objDiv.parentNode;
  subMenuDiv = mainMenuDiv.getElementsByTagName( "DIV" ).item(0);

  //
  menuContainerDiv = mainMenuDiv.getElementsByTagName("DIV").item(1);
  itemContainerDiv = menuContainerDiv.getElementsByTagName("DIV").item(0);

  // Find the container div for the menus
  numMenus = menuArray.length;
  for( i = 0; i < numMenus &&
    ( menuArray[i] != menuContainerDiv ); i++ );

  // We didn't find our menu, so add it to the end of the array of menus, items, etc.
  if( i == numMenus )
  {
    // Save our work for later, no sense doing these finds over and over again
    // Set the onclick handler for the subMenu
    menuArray[i] = menuContainerDiv;
    menuItemArray[i] = itemContainerDiv;
    subMenuArray[i] = subMenuDiv;
    subMenuDiv.onclick = SetSlide;

    // Now find the subMenu items and set their style handlers for mouse events
    lastmenuNum = -1;
    for( itemIndex = 0; itemIndex < itemContainerDiv.childNodes.length; itemIndex++ )
    {
      if( itemContainerDiv.childNodes.item( itemIndex ).tagName == "SPAN" )
      {
        numberOfMenuItems++;
        itemContainerDiv.childNodes.item( itemIndex ).onmouseover = ChangeStyle;
        itemContainerDiv.childNodes.item( itemIndex ).onmouseout = ChangeStyle;
        lastmenuNum = itemIndex;
      }
    }

    // Is this subMenu item of the same class as the subMenu we're concerned with?
    // i.e. span class="subItem", etc.
    for( ruleIndex = 0; ruleIndex < styles.length; ruleIndex++ )
    {
      subMenuClass = String(styles[ruleIndex].selectorText);
      menuItemClass = String("." + itemContainerDiv.childNodes.item(lastmenuNum).className);
      if( subMenuClass == menuItemClass )
      {
        if( NaN != parseInt(styles[ruleIndex].style.height) )
        {
          divHeight = parseInt(styles[ruleIndex].style.height);
          break;
        }
      }
    }

    // Also store number of subMenu items to avoid calculating everytime
    // and save the parent container while we're at it
    subMenuNumberOfItemsArray[i] = numberOfMenuItems;
    menuParentArray[i] = mainMenuDiv;

    // Now set the style properly if subMenu is visible
    if( itemContainerDiv.style.display == "inline" )
    {
      // Set the subMenu composite (total) height (and remember it)
      subMenuHeightArray[i] = numberOfMenuItems * divHeight;
      menuArray[i].style.height = numberOfMenuItems * divHeight + "px";
      subMenuIsVisibleArray[i] = true;
      if( makeRadioButton )
        currMenuIndex = i;

      // Set the visibility if fading
      if( doFading )
      {
        // Micro$uck Exploder
        if( menuArray[i].filters )
          menuArray[i].style.filter = 'alpha(opacity=100)';

        // Everyone else
        else
          menuArray[i].style.opacity = 1.0;
      }
    }

    // Otherwise, subMenu is NOT visible
    else
    {
      // So change the class name to change the expand/collapse indicator
      // and set the heights to 0
      subMenuArray[i].className = subMenuArray[i].className + "Over";
      subMenuHeightArray[i] = 0;
      menuArray[i].style.height = 0 + "px";
      subMenuIsVisibleArray[i] = false;

      // Set the visibility if fading
      if( doFading )
      {
        // Micro$uck Exploder
        if( menuArray[i].filters )
          menuArray[i].style.filter = 'alpha(opacity=0)';

        // Everyone else
        else
          menuArray[i].style.opacity = .0;
      }
    }
  }//end if

  // Release the storage (eventually)
  mainMenuDiv = null;
  subMenuDiv =  null;
  menuContainerDiv = null;
  itemContainerDiv = null;
}

// Setup to expand/collapse the subMenu to/from its maximum height
function SetSlide()
{
  // I'm busy, go away!
  if( isLocked )
    return;

  // I wasn't busy, but I am now
  isLocked = true;
  hideTip();


  // Find our menu in the list of menus
  for( menuIndex = 0; menuIndex < menuArray.length; menuIndex++ )
  {
    // Match this menu's parent with the array of parents
    if( menuParentArray[menuIndex] == this.parentNode )
    {
      // If acting like a radio button
      if( makeRadioButton )
      {
        // Case 1: No menu currently expanded
        if( currMenuIndex == -1 )
          currMenuIndex = menuIndex;

        // Case 2: Currently expanded menu is selected menu - collapse
        else if( currMenuIndex == menuIndex )
          currMenuIndex = -1;

        // Case 3: Currently expanded menu is not selected menu
        // - collapse current and expand selected, but one at a time
        else
        {
          lastMenuIndex = currMenuIndex;
          currMenuIndex = menuIndex;
          menuIndex = lastMenuIndex;
        }
      }

      // Set up a timer to expand/collapse the menu
      if( subMenuIntervalArray[menuIndex] == null )
        subMenuIntervalArray[menuIndex]
          = setInterval( "RunSlide(" + menuIndex + ")", slideDelay );
      break;
    }
  }
}

// Expand/collapse the subMenu to/from its maximum height
function RunSlide( objIndex )
{
  // If the subMenu is visible, let's collapse to make invisible
  if( subMenuIsVisibleArray[objIndex] )
  {
    // If fading, set fade rate to correspond with collapse rate
    if( doFading )
    {
      // Micro$uck Exploder
      if ( menuArray[objIndex].filters )
      {
        opcVal = menuArray[objIndex].filters.alpha.opacity;
        opcVal -= 100/(((subMenuNumberOfItemsArray[objIndex] * divHeight) / moveSlidePix) + 1);
        menuArray[objIndex].filters.alpha.opacity = opcVal;
      }

      // Everyone else
      else
      {
//        opcVal = parseFloat(menuArray[objIndex].style.opacity);
//        opcVal -= .9/(((subMenuNumberOfItemsArray[objIndex] * divHeight) / moveSlidePix) + 1 );
//        menuArray[objIndex].style.opacity = opcVal;
        menuArray[objIndex].style.opacity
          -= .9/(((subMenuNumberOfItemsArray[objIndex] * divHeight) / moveSlidePix) + 1 );
      }
    }

    // Subtract the incremental height from total height and set style accordingly
    // until nothing left...
    menuItemArray[objIndex].style.display = 'none';
    subMenuHeightArray[objIndex] -= moveSlidePix;
    if ( subMenuHeightArray[objIndex] > 0 )
      menuArray[objIndex].style.height = subMenuHeightArray[objIndex] + "px";

    // ...when nothing left...
    else
    {
      // If fading, turn off subMenu
      if( doFading )
      {
        // Micro$uck Exploder
        if( menuArray[objIndex].filters )
          menuArray[objIndex].style.filter = 'alpha(opacity=0)';

        // Everyone else
        else
          menuArray[objIndex].style.opacity = 0;
      }

      // Set style to change expand/collapse indicator
      subMenuArray[objIndex].className = subMenuArray[objIndex].className+"Over";

      // Height is now 0
      subMenuHeightArray[objIndex] = 0;
      menuArray[objIndex].style.height = 0 + "px";

      // Clear the interval timer and associated tracking
      clearInterval(subMenuIntervalArray[objIndex]);
      subMenuIntervalArray[objIndex] = null;

      // Now invisible
      subMenuIsVisibleArray[objIndex] = false;

      // If acting like a radio button
      if( makeRadioButton )
      {
        // Case 3: Expanded menu was not selected, now collapsed
        // - setup to expand selected 
        if( currMenuIndex != -1 )
        {
          if( subMenuIntervalArray[currMenuIndex] == null )
            subMenuIntervalArray[currMenuIndex]
              = setInterval( "RunSlide(" + currMenuIndex + ")", slideDelay );

          // Still locked, don't update menu state until done expanding
          return 0;
        }
      }

      // Now no longer busy
      isLocked = false;

      // Update the current menu state and return
      UpdateUserCookie(objIndex);
      return 0;
    }
    return 0;
  }

  // If the subMenu is not visible, let's expand to make visible
  if( !subMenuIsVisibleArray[objIndex] )
  {
    // If fading, set fade rate to correspond with expansion rate
    if( doFading )
    {
      // Micro$uck Exploder
      if ( menuArray[objIndex].filters )
      {
        opcVal = menuArray[objIndex].filters.alpha.opacity;
        opcVal += 100/(((subMenuNumberOfItemsArray[objIndex] * divHeight) / moveSlidePix) + 1);
        menuArray[objIndex].filters.alpha.opacity = opcVal;
      }

      // Everyone else
      else
      {
        opcVal = parseFloat(menuArray[objIndex].style.opacity);
        opcVal += .9/((subMenuNumberOfItemsArray[objIndex] * divHeight) / moveSlidePix );
        menuArray[objIndex].style.opacity = opcVal;
// This does not decrease opacity, fails after completion with multiple console warnings?
//  perhaps menuArray[objIndex].style.opacity is undefined when first opened?        
//        menuArray[objIndex].style.opacity
//          += .9/((subMenuNumberOfItemsArray[objIndex] * divHeight) / moveSlidePix );
      }
    }

    // Add the incremental height to height and set style accordingly
    // up to total height ...
    subMenuHeightArray[objIndex] += moveSlidePix;
    if( subMenuHeightArray[objIndex] < (subMenuNumberOfItemsArray[objIndex] * divHeight) )
      menuArray[objIndex].style.height = subMenuHeightArray[objIndex] + "px";

    // ...when total height is reached...
    else
    {
      // If fading, adjust visibility
      if( doFading )
      {
        // Micro$uck Exploder
        if( menuArray[objIndex].filters )
          menuArray[objIndex].style.filter = 'alpha(opacity=100)';

        // Everyone else
        else
          menuArray[objIndex].style.opacity = 1;
      }

      // Set style to change expand/collapse indicator
      strClassName = String(subMenuArray[objIndex].className);
      subMenuArray[objIndex].className = strClassName.substring(0,strClassName.length - 4);

      // Height is now total height
      subMenuHeightArray[objIndex] = (subMenuNumberOfItemsArray[objIndex] * divHeight);
      menuArray[objIndex].style.height = (subMenuNumberOfItemsArray[objIndex] * divHeight)+ "px";

      // Clear the interval timer and associated tracking
      menuItemArray[objIndex].style.display = 'inline';
      clearInterval(subMenuIntervalArray[objIndex]);
      subMenuIntervalArray[objIndex] = null;

      // Now visible
      subMenuIsVisibleArray[objIndex] = true;

      // Now no longer busy
      isLocked = false;

      // Update the current menu state and return
      UpdateUserCookie(objIndex);
      return 0;
    }
    return 0;
  }
}

// Save Our Settings
function UpdateUserCookie( aryIndex )
{
  // Calculate a new expiration date (in milliseconds?) a month from now
  // and update the cookie
  date = new Date();
  date.setTime( date.getTime() + (1000 * 60 * 60 * 24 * 30) );
  document.cookie = "magnaMenuCookv1" + "=" + escape(subMenuHeightArray.toString()) + "; expires=" + date.toGMTString();
}

// Get Our Settings
function GetUserCookie( crumbName )
{
  // Find the desired cookie crumb, first splitting off the expiration date
  colCookie = document.cookie.split("; ");
  for( a = 0; a < colCookie.length; a++ )
  {
    // Either magnaMenuCookv1=... or expires=...
    colCrumb = colCookie[a].split("=");
    if( colCrumb[0] == crumbName )
      return unescape( colCrumb[1] );
  }
  return "";
}


function ChangeStyle()
{
  className = String(this.className);
  if( className.substring(className.length - 4, className.length) == "Over" )
    this.className = className.substring(0,className.length - 4);
  else
    this.className = this.className + "Over";
}

/* Last Updated: 28 July 2010 - Fixed Micro$uck fading and some init issues for non Micro$uck w/o Fading */




