/** Class for retrieving and processing menu XML documents.

\code
  var myMenu = new WTCRFMenu( "menuMain","milS","../HandlersMenuHandler.ashx?","myMenu","navBar",null,null );
                                      
  <body onload="myMenu.initialise()">
\endcode

@param menuID The ID of the menu to obtain from the server
@param linkID The ID of the link to set as the selected menu item when the menu is loaded
@param handlerURL The URL to send the HTTP request to
@param menuName The name to be given to the menu, should be the same as the variable name
@param holderID The ID of the element which will contain the menu
@param uniqueID Used to indicate a menu tailored to a specific object (determined by the application handling the request)
@param onMenuLoaded The function called after the menu has loaded (no parameters)
*/
function WTCRFMenu( menuID,linkID,handlerURL,menuName,holderID,uniqueID,onMenuLoaded )
{
  var mName;
  var uID;
  var menuXML;
  var menuSectionLink;
  var menuLink;
  var menuVisible;
  var menuActiveLink;
  var menuHolderID;
  var mainMenuID;
  var selectedMenuLinkID;
  var defaultLinkID;
  var menuHandlerURL;
  var menuRequest;
  var onLoaded;

  mName = menuName;
  menuXML = getXMLDocument();
  menuSectionLink = "<a href=\"#\" onclick=\"" + mName + ".onmenuSectionClick(this)\"></a>";
  menuLink = "<a href=\"#\" onclick=\"" + mName + ".onmenuLinkClick(this)\"></a>";
  menuVisible = null;
  menuActiveLink = null;
  menuHolderID = holderID;
  selectedMenuLinkID=null;
  menuHandlerURL = handlerURL;
  mainMenuID = menuID;
  defaultLinkID = linkID;
  uID = uniqueID;
  onLoaded = onMenuLoaded;

  this.initialise = initialise;
  this.requestMenu = requestMenu;
  this.loadMenu = loadMenu;
  this.setMenuLink = setMenuLink;
  this.refreshMenu = refreshMenu;
  this.changeMenuSelection = changeMenuSelection;
  this.onmenuSectionClick = onmenuSectionClick;
  this.onmenuLinkClick = onmenuLinkClick;
  this.getSelectedItemID = getSelectedItemID;
  this.setMenuLinkModified = setMenuLinkModified;
  this.setMenuLoadedEvent = setMenuLoadedEvent;


  /** initialise the menu */
  function initialise()
  {
    requestMenu();
  }


  /*  request the menu document from the server */
  function requestMenu()
  {
    menuRequest = getXMLHTTPRequest();
    menuRequest.open( "GET",menuHandlerURL,true );
    menuRequest.setRequestHeader( "mnuid",mainMenuID );

    if ( ( uID != null ) & ( uID != undefined ) )
    {               
      menuRequest.setRequestHeader( "uid",uID );
    }

    menuRequest.onreadystatechange=
      function()
      {
        if ( menuRequest.readyState==4 )
        {         
          menuXML = getXMLDocument( menuRequest.responseText );
          
          if ( menuXML == null )
          {
            alert( "The menu document \"" + menuID + "\" has not been returned by the server." );
          }
          else
          {
            loadMenu();
          }
        }
      }
    menuRequest.send( null );
  }



  /* load the menu from the XML document */
  function loadMenu()
  {
    var menuHolder = document.getElementById( menuHolderID );

    if ( menuHolder != null )
    { 
      menuHolder.innerHTML = "";

      var itemsNode = null;

      itemsNode = menuXML.documentElement.getElementsByTagName("items")[0];

      var newMenuHolder = getMenuItems( itemsNode,"sectionLinks","",true,null );

      menuHolder.appendChild( newMenuHolder );

      /* reselect active link */
      if ( defaultLinkID != null )
      {
        openMenuLink( defaultLinkID );
        defaultLinkID = null;
      }
      else
      if ( selectedMenuLinkID != null )
      {
        setMenuLink( selectedMenuLinkID,true );
      }
    }

    try
    {
      onLoaded();
    }
    catch( err )
    {

    }
  }


  /** sets the on menu loaded event handler */
  function setMenuLoadedEvent( eventHandler )
  {
    onLoaded = eventHandler;
  }


  /* recursively converts <items/> in itemNode to a menu list in <div/> */
  function getMenuItems( itemsNode,menuName,cssClass,visible,parentID )
  {
    if ( itemsNode.childNodes.length > 0 )
    {
      var nodeCount = itemsNode.childNodes.length;
      var menuHolder = document.createElement( "div" );
      var menuSection = menuHolder.appendChild( document.createElement( "ul" ) );

      if ( !visible )
      {
        menuHolder.style.visibility = "hidden";
      }

      menuHolder.setAttribute( "name",menuName );
      menuHolder.id = menuName;
      menuHolder.className = cssClass;

      var newMenuItem;
      var newMenuTitle;

      for( var index=0;index < nodeCount; index++ )
      {
        var itemNode = null;

        itemNode = itemsNode.childNodes.item( index );

        if (itemNode.nodeType == 3)
        {
          continue;
        }

        var newLink;

        newMenuItem = menuSection.appendChild( document.createElement( "li" ) );

        if ( itemNode.childNodes.length > 0 )
        {
          newMenuItem.innerHTML = menuSectionLink;
          newLink = newMenuItem.childNodes[ 0 ];
          newLink.id = itemNode.getAttribute( "id" );

          var titleAttrib = itemNode.getAttribute( "title" );

          if ( titleAttrib != null )
          {
            newLink.setAttribute( "title",titleAttrib );
          }

          /* mc attribute is for identifying the modified count of sub-items */
          newLink.setAttribute( "mc","0" );

          var tempNode = itemNode.getElementsByTagName("items");
          newSubMenu = getMenuItems( tempNode[ 0 ],"subMenu","submenu",false,newLink.id );

          if ( newSubMenu != null )
          {
            newMenuItem.appendChild( newSubMenu );
          }
        }
        else
        {
          var typeAttrib = itemNode.getAttribute( "type" );
          
          var widthAttrib = itemNode.getAttribute( "dlgwidth" );
          var heightAttrib = itemNode.getAttribute( "dlgheight" );
            
          newMenuItem.innerHTML = menuLink;
          newLink = newMenuItem.childNodes[ 0 ];

          newLink.setAttribute( "url",itemNode.getAttribute( "url" ) );
          newLink.id = itemNode.getAttribute( "id" );

          var titleAttrib = itemNode.getAttribute( "title" );

          if ( titleAttrib != null )
          {
            newLink.setAttribute( "title",titleAttrib );
          }

          if ( typeAttrib != null )
          {
            newLink.setAttribute( "type",typeAttrib );
          }

          if ( widthAttrib != null )
          {
            newLink.setAttribute( "dlgwidth",widthAttrib );
          }

          if ( heightAttrib != null )
          {
            newLink.setAttribute( "dlgheight",heightAttrib );
          }

          if ( parentID != null )
          {
            newLink.setAttribute( "parentid",parentID );
          }

          if ( itemNode.getAttribute( "target" ) != null )
          {
            newLink.setAttribute( "href",itemNode.getAttribute( "url" ) );
            newLink.setAttribute( "target",itemNode.getAttribute( "target" ) );
          }
        }
        newLink.appendChild( document.createTextNode( itemNode.getAttribute( "name" ) ) );
      }

      return menuHolder;
    }
    else
    {
      return null;
    }
  }


  /* event for when a section title is selected in the menu */
  function onmenuSectionClick( control )
  {
    if ( control != null )
    {
      var itemParent = getXMLParentNode( control );

      if ( itemParent.childNodes.length > 1 )
      {
        var subMenu = itemParent.childNodes[ 1 ];
        var newVisibility;

        switch( subMenu.style.visibility )
        {
          case ( "hidden" ) : newVisibility = "visible";
          if ( menuVisible != null )
          {
            menuVisible.style.visibility = "hidden";
          }
          menuVisible = subMenu; break;
          case ( "visible" ) : newVisibility = "hidden"; break;
        }
        subMenu.style.visibility = newVisibility;
      }
    }
  }


  /* menu link is selected */
  function onmenuLinkClick( control )
  {
    if ( control != null )
    {
      var linkURL = control.getAttribute( "url" );
      var linkType = parseInt( control.getAttribute( "type" ) );
      
      var dlgWidth = parseInt( control.getAttribute( "dlgwidth" ) );
      var dlgHeight = parseInt( control.getAttribute( "dlgheight" ) );
        
        
      switch( linkType )
      {
        case( 0 ) :
          OpenPage( linkURL,"",50,50,false,false,false );
        break;
        case( 1 ) :
          OpenPage( linkURL,"",50,50,true,false,false );
        break;
        case( 2 ) :
          OpenPage( linkURL,"",dlgWidth,dlgHeight,false,false,false,1 );
        break;
        case( 3 ) :
          OpenPage( linkURL,"",dlgWidth,dlgHeight,false,false,false,2 );
        break;
        default :
          if ( parent.frameContent != null )
          {          
              parent.frameContent.location.href = linkURL;
          }
          setMenuLink( menuActiveLink,false );
          setMenuLink( control.id,true );

          menuActiveLink = control.id;

          selectedMenuLinkID = control.id;
          changeMenuSelection( selectedMenuLinkID );

          break;
      }

      if ( menuVisible != null )
      {
        menuVisible.style.visibility = "hidden";
      }
    }
    else
    {
      alert( "Invalid call to onmenuLinkClick" );
    }
  }


  /* change visibility of active menu etc. */
  function setMenuLink( controlID,active )
  {
    if ( controlID != null )
    {
      var control = document.getElementById( controlID );

      if ( control != null )
      {
        if ( active )
        {
          control.className = "menuitemactive";
        }
        else
        {
          control.className = "";
        }

        /* change the parent menu link */
        var parentID = control.getAttribute( "parentid" );

        if ( parentID != null )
        {
          setMenuLink( parentID,active );
        }
      }
    }
  }


  /* refreshes the menu page and selects the link if given */
  function refreshMenu( aselectedLinkID )
  {
    if ( menuRequest != null )
    {
      if ( ( aselectedLinkID != undefined ) & ( aselectedLinkID != null ) )
      {
        selectedMenuLinkID = aselectedLinkID;
      }
      
      requestMenu();
    }
  }


  /* sets a menu link highlight for modified content */
  function setMenuLinkModified( linkID,modified )
  {                                       
    if ( linkID == null )
    {
      linkID = selectedMenuLinkID;
    }

    var control = document.getElementById( linkID );

    if ( control != null )
    {
      var parentID = control.getAttribute( "parentid" );

      if ( ( control.childNodes.length < 2 ) && modified )
      {
        var highlightNode = document.createElement("span");
        highlightNode.className = "modtext";
        highlightNode.innerText = "*";
        control.appendChild( highlightNode );

        if ( parentID != null )
        {
          setMenuParentModified( parentID,modified );
        }
      }
      else
      if ( ( control.childNodes.length > 1 ) && !modified )
      {
        control.removeChild( control.childNodes[ 1 ] );

        if ( parentID != null )
        {
          setMenuParentModified( parentID,modified );
        }
      }
    }
    else
    {
      alert( "Control ID " + linkID + " is not a valid menu item" );
    }
  }


  /* displays the "modified" state of the parent menu link
     depending on whether the sub-items have been modified.
     This is done by keeping a reference count of the
     number of modifications in the attribute "mc" */
  function setMenuParentModified( parentID,modified )
  {
    var control = document.getElementById( parentID );

    if ( control != null )
    {
      var modCount = parseInt( control.getAttribute( "mc" ) );

      if ( modified )
      {
        modCount++;
      }
      else
      {
        modCount--;
      }

      control.setAttribute( "mc",modCount.toString() );

      if ( modCount > 0 )
      {
        var highlightNode;

        if ( control.childNodes.length > 1 )
        {
          highlightNode = control.childNodes[ 1 ];
        }
        else
        {
          highlightNode = document.createElement( "sup" );
          highlightNode.className = "modtext";
          control.appendChild( highlightNode );
        }

        highlightNode.innerText = modCount.toString();
        highlightNode.setAttribute( "title",modCount + " items have changes within this section" );
      }
      else
      if ( control.childNodes.length > 1 )
      {
        control.removeChild( control.childNodes[ 1 ] );
      }
    }
    else
    {
      alert( "Parent menu " + parentID + " is not a valid menu item" );
    }
  }


  /* called when the menu selection has changed */
  function changeMenuSelection( newID )
  {
    var cnIDCTRL = document.getElementById( "cnID" );

    if ( cnIDCTRL != null )
    {
      cnIDCTRL.value = newID;
    }
  }

  /** returns the ID of the currently selected menu item */
  function getSelectedItemID()
  {
    return selectedMenuLinkID;
  }


  /* open a specific link and set it as the active item */
  function openMenuLink( linkID )
  {
    var newLink = document.getElementById( linkID );

    if ( newLink != null )
    {
      onmenuLinkClick( newLink );
    }
  }
}





/* initialise the menu */
function InitialiseMenu( menuID,adefaultLinkID,handlerURL )
{
  alert( "WTCRFMenu is now implemented as a class. Use WTCRFMenu( menuID,linkID,handlerURL,menuName,holderID,uniqueID )." );
}


/* initialise the menu from the file */
function InitialiseMenuFromURL( menuURL,menuID,adefaultLinkID )
{
  alert( "WTCRFMenu is now implemented as a class. Use WTCRFMenu( menuID,linkID,handlerURL,menuName,holderID,uniqueID )." );
}



