// Get a XMLHttpRequest instance
function getXMLHttpRequest()
{
   try{ return new XMLHttpRequest() } catch(e){};
   try{ return new ActiveXObject("MSXML3.XMLHTTP") } catch(e){};
   try{ return new ActiveXObject("MSXML2.XMLHTTP.3.0") } catch(e){};
   try{ return new ActiveXObject("Msxml2.XMLHTTP") } catch(e){};
   try{ return new ActiveXObject("Microsoft.XMLHTTP") } catch(e){};
   throw new Error("Could not find an XMLHttpRequest alternative.");
};

// Start initializing of the menu
// menuLocation: The URL for the location of the menu.xml
// language: What language to match with in the menu.xml items tag attribute language
function initMenu(menuLocation, language)
{
   _language = language;
   loadMenu(menuLocation);
   //var xmlMenu = new ActiveXObject("MSXML2.DOMDocument");
   //xmlMenu.load(menuLocation);
   //loadMenuCompleted(xmlMenu);
}

// Load the menu XML
// menuLocation: The URL for the location of the menu.xml
function loadMenu(menuLocation)
{
   var request = getXMLHttpRequest();
   request.open("GET", menuLocation, true);
   request.onreadystatechange = function()
      {
         if (request.readyState == 4 && request.status == 200)
         {
            if (request.responseText)
            {
               loadMenuCompleted(request.responseXML);
            }
         }
      };
   request.send(null);
}

// Select single node that also works in firefox
// xmlDoc: Node to search from
// elementPath: The XPath
function selectSingleNode(xmlDoc, elementPath)
{
   if(window.ActiveXObject)
   {
      return xmlDoc.selectSingleNode(elementPath);
   }
   else
   {
      var xpe = new XPathEvaluator();
      var nsResolver = xpe.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
      var results = xpe.evaluate(elementPath,xmlDoc,nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
      return results.singleNodeValue; 
   }
}

// Select nodes, compatible with firefox
// xmlDoc: Node to search from
// elementPath: The XPath
function selectNodes(xmlDoc, elementPath)
{
   if(window.ActiveXObject)
   {
      return xmlDoc.selectNodes(elementPath);
   }
   else
   {
      var xpe = new XPathEvaluator();
      var nsResolver = xpe.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
      var results = xpe.evaluate(elementPath, xmlDoc, nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);    
	  
	   var nodes = new Array;
    
      if (results != null)
      {
         var element = results.iterateNext();
         while(element)
         {
            nodes.push(element);
            element = results.iterateNext();
         }
      }
    
      return nodes;
   }
};

// The menu XML
var _xmlMenu = null;
// Is still busy setting up the menu (will not allow loading of submenus or try to cancel timers
var _isLoading = true;
// Currently selected language to load
var _language = null;
// Where to put the main menu
var _menuAreaID = "menuArea";
// Where to put the sub menu
var _menuSubAreaID = "menuSubArea";
// Separator between menu items
var _menuAreaSeparator = "&nbsp;&nbsp;|&nbsp;&nbsp;"
// Separator between submenu items
var _menuSubAreaSeparator = "&nbsp;&nbsp;"
// Background color
var _backgroundColor = "#ffffff";
// Text color
var _textColor = "#000000";
// Fade steps
var _fadeSteps = 10;
// Fade delay in milliseconds
var _fadeDelay = 5;
// current timer value, can be used to cancel timer
var _currentTimer = null;
// Show the first submenu (if there is any) when loading menu for first time
var _showFirstSubMenuOnLoad = true;
// The font weight for inactive menu item
var _fontWeightInactive = 400;
// The font weight for active menu item
var _fontWeightActive = 700;
// Currently activated menu ID
var _activeMenuControlID = null;
// Currently activated submenu item ID
var _activeSubMenuControlID = null;
// Menu prefix
var _menuIdPrefix = "menuItem";
// Submenu prefix
var _subMenuIdPrefix = "subMenuItem";

// Extract the settings from the XML
// xmlMenu: The loaded XML menu
function getMenuSettings(xmlMenu)
{
   var value = null;
   var node = selectSingleNode(xmlMenu, "/menu/settings/backgroundcolor");
   if (node != null)
   {
      value = getAttributeValue(node, "value");
      if (node != null)
      {
         _backgroundColor = value;
      }
   }
   node = selectSingleNode(xmlMenu, "/menu/settings/textcolor");
   if (node != null)
   {
      value = getAttributeValue(node, "value");
      if (node != null)
      {
         _textColor = value;
      }
   }
   node = selectSingleNode(xmlMenu, "/menu/settings/fade");
   if (node != null)
   {
      value = getAttributeValue(node, "steps");
      if (node != null)
      {
         _fadeSteps = value;
      }
      value = getAttributeValue(node, "delay");
      if (node != null)
      {
         _fadeDelay = value;
      }
   }
   node = selectSingleNode(xmlMenu, "/menu/settings/menuArea");
   if (node != null)
   {
      value = getAttributeValue(node, "ID");
      if (node != null)
      {
         _menuAreaID = value;
      }
      value = getAttributeValue(node, "separator");
      if (node != null)
      {
         _menuAreaSeparator = value;
      }
   }
   node = selectSingleNode(xmlMenu, "/menu/settings/menuSubArea");
   if (node != null)
   {
      value = getAttributeValue(node, "ID");
      if (node != null)
      {
         _menuSubAreaID = value;
      }
      value = getAttributeValue(node, "separator");
      if (node != null)
      {
         _menuSubAreaSeparator = value;
      }
   }
}

// The menu has finished loading
// xmlMenu: The loaded XML for the menu
function loadMenuCompleted(xmlMenu)
{
   _xmlMenu = xmlMenu;
   // Get settings
   getMenuSettings(xmlMenu);
   // Ensure that text is same as background
   setColorAll(_menuAreaID, _backgroundColor);
   setColorAll(_menuSubAreaID, _backgroundColor);
   
   buildMenu(xmlMenu, _language, _menuAreaID);
   if (_showFirstSubMenuOnLoad == true)
   {
      var menuNodes = selectNodes(xmlMenu, "/menu/items[@language='" + _language + "']/item");
      if (menuNodes.length > 0)
      { 
        if(_activeMenuControlID)
          var id = parseInt(_activeMenuControlID.substr(9))-1;
        else
          var id = 0;
        
        buildSubMenu(xmlMenu, _language, _menuSubAreaID, getAttributeValue(menuNodes[id], "id"));
      }
   }
   
   var cmd = null;
   
   if (_showFirstSubMenuOnLoad == true)
   {
      cmd = "fadeText('" + _menuSubAreaID + "', '" + _backgroundColor + "', '" + _textColor + "', " +
         _fadeSteps + ", 0, " + _fadeDelay + ", 'loadingCompleted()')";
   }
   else
   {
      cmd = "loadingCompleted();"
   }
   // Start to fade in menu
   _currentTimer = fadeText(_menuAreaID, _backgroundColor, _textColor, _fadeSteps, 0, _fadeDelay, cmd);
   
   /*if(_activeMenuControlID && !_activeSubMenuControlID) 
   {
    setActiveSubMenuItem(_subMenuIdPrefix + "0");
   }*/
}

function transformWeight(inactivateControlID, activateControlID, weightActive, weightInactive, steps, currentStep, delays)
{
  if (currentStep == steps)
  {
    return;
  }

  var inactivateCtrl = document.getElementById(inactivateControlID);
  var activateCtrl = document.getElementById(activateControlID);
  
  steps++;
  
  var delta = (weightActive - weightInactive) * currentStep / steps;
  
  if (inactivateCtrl != null)
  {
    inactivateCtrl.style.fontWeight = weightActive - delta;
  }
  
  if (activateCtrl != null)
  {
    activateCtrl.style.fontWeight = weightInactive + delta;
  }
}


// Indicates loading completed and menu is ready to be used
function loadingCompleted()
{
   _isLoading = false;
}

// Build the menu
// xmlMenu: The loaded XML menu
// language: The language of the menu to load
// menuAreaID: The ID of the element to put the menu in
function buildMenu(xmlMenu, language, menuAreaID)
{
   var html = "";
   var menuNodes = selectNodes(xmlMenu, "/menu/items[@language='" + language + "']/item");
   var node = null;
   var name = null;
   var id = null;
   var href = null;
   var target = null;
   var menuItemID = 0;
   for (n = 0; n < menuNodes.length; n++)
   {
      //menuItemID++;
      
      node = menuNodes[n];
      
      name = getAttributeValue(node, "name");
      id = getAttributeValue(node, "id");
      
      // Only add href is defined in node
      href = getAttributeValue(node, "href");
      html += "<a href=\"" + href + "\" id=\"" + _menuIdPrefix + menuItemID + "\"";
      
      // Only add target if defined for the menu item node 
      target = getAttributeValue(node, "target");
      if (target != null)
      {
         html += " target=\"" + target + "\"";
      }
      
      //html += " onclick=\"setActiveMenuItem('" + _menuIdPrefix + menuItemID + "');\"";
      // Only add onclick if there are subitems
      var subItemNodes = selectNodes(node, "subitems/subitem");
      //if (subItemNodes.length > 0)
      //{
         html += " onclick=\"setActiveMenuItem('" + _menuIdPrefix + menuItemID + "'); showSubMenu('" + _menuIdPrefix + menuItemID + "', '" + id + "');\"";
      //}
      //else
      //{
      //   html += " onclick=\"this.blur();\"";
      //}
      html += " style=\"color: " + _backgroundColor + ";\">" + name + "</a>";
      
      // Add separator
      if (n < menuNodes.length - 1)
      {
         html += _menuAreaSeparator;
      }
      
      menuItemID++;
   }
   
   // Set HTML in area for menu
   var ctrl = document.getElementById(menuAreaID);
   if (ctrl != null)
   {
      ctrl.innerHTML = html;
   }
}

function clearSubMenu(ctrl)
{
}

// Fades out the current submenu and have switchSubMenu() called when
// faded out to change menu and fade it in      
// menuId: Name of menu to generate submenu for
function showSubMenu(activateControlID, menuId)
{
   if (_isLoading == true)
   {
      // Still loading, do nothing
      return;
   }
   // Remove focus
   var activateCtrl = document.getElementById(activateControlID);
   activateCtrl.blur();

   if (_activeMenuControlID == null)
   {
      // No active menu, no submenu = no need to fade out.
      var subMenu = document.getElementById(_menuSubAreaID);
      subMenu.style.color = _backgroundColor;
      switchSubMenu(menuId);
   }
   else
   {
      // Command to build the new submenu and fade it in.
      var cmd = "switchSubMenu('" + menuId + "')";

      // Fade out sub menu
      var startColor = _textColor;
      if (_currentTimer != null)
      {
         clearTimeout(_currentTimer);
         var ctrl = document.getElementById(_menuSubAreaID);
         startColor = ctrl.style.color;
      }
      _currentTimer = fadeText(_menuSubAreaID, startColor, _backgroundColor, _fadeSteps, 0, _fadeDelay, cmd);
   }
}

// Builds the submenu for a menu and fades it in
// menuId: Id of menu to generate submenu for
function switchSubMenu(menuId)
{
   buildSubMenu(_xmlMenu, _language, _menuSubAreaID, menuId);
   _currentTimer = fadeText(_menuSubAreaID, _backgroundColor, _textColor, _fadeSteps, 0, _fadeDelay, null);
   setActiveSubMenuItem(_subMenuIdPrefix + "0");
}

// Builds the submenu for a specified menu and sets it html in the area for the submenu
// xmlMenu: The loaded menu XML
// language: The language of menu to get 
// menuSubAreaID: The place to put the generated menu
// menuId: Name of menu to generate submenu for
function buildSubMenu(xmlMenu, language, menuSubAreaID, menuId)
{
   var html = "";
   var menuNodes = selectNodes(xmlMenu, "/menu/items[@language='" + language + "']/item[@id='" + menuId + "']/subitems/subitem");
   var node = null;
   var name = null;
   var href = null;
   var target = null;
   var subMenuId = 0;
   for (n = 0; n < menuNodes.length; n++)
   {
      node = menuNodes[n];
      
      name = getAttributeValue(node, "name");
      
      // Only add href is defined in node
      href = getAttributeValue(node, "href");
      html += "<a href=\"" + href + "\"";
      
      // Only add target if defined for the menu item node 
      target = getAttributeValue(node, "target");
      if (target != null)
      {
         html += " target=\"" + target + "\"";
      }
      
      html += " id=\"" + _subMenuIdPrefix + subMenuId++ + "\"";
      
      html += " onclick=\"setActiveSubMenuItem(this.id); this.blur();\"";
      
      html += " style=\"color: " + _backgroundColor + ";\">" + name + "</a>";

      // Add separator
      if (n < menuNodes.length - 1)
      {
         html += _menuSubAreaSeparator;
      }
   }
   
   // Set HTML in area for menu
   var ctrl = document.getElementById(menuSubAreaID);
   if (ctrl != null)
   {
      ctrl.innerHTML = html;
   }
}

// Gets the value of the named attribute for the node. Workaround!
// node: XML node
// attributeName: Name of attribute to get value for
function getAttributeValue(node, attributeName)
{
   for (i = 0; i < node.attributes.length; i++)
   {
      if (node.attributes[i].name == attributeName)
      {
         return node.attributes[i].value;
      }
   }
   
   return null;
}

// Fades the color of the control and all its children from begincolor to endcolor
// in the specified amount of steps with a delay between steps. When completed the
// following command will be called.
function fadeText(ctrlID, begincolor, endcolor, steps, currentStep, stepDelay, nextCmd)
{
   // Get the colors
   var bcol = new RGBColor(begincolor);
   var ecol = new RGBColor(endcolor);

   // Check if done
   if ((bcol.r == ecol.r &&
      bcol.g == ecol.g &&
      bcol.b == ecol.b) ||
      steps == currentStep)
   {
      // done, schedule next command
      _currentTimer = null;
      if (nextCmd != null)
      {
         _currentTimer = setTimeout(nextCmd, 0);
      }
      return;
   }

   // currentStep should always begin at 0 to have currentStep / steps work as a percentage
   // currentStep = 0, increased by 1 and divided by steps that is 100.
   // 1 / 100 = 0.001 = 1%
   currentStep++;
   // Calculate the current change in %
   var changed = currentStep / steps;

   // Holder of the new faded color
   var col = new RGBColor("");

   // RED
   var delta = bcol.r - ecol.r;
   col.r = Math.round(bcol.b - (delta * changed));
   // GREEN
   delta = bcol.g - ecol.g;
   col.g = Math.round(bcol.g - (delta * changed));
   // BLUE
   delta = bcol.b - ecol.b;
   col.b = Math.round(bcol.b - (delta * changed));

   // Set the new color
   setColorAll(ctrlID, col.toRGB());

   // Reschedule fader            
   var cmd = "fadeText(\"" + ctrlID + "\", \"" + bcol.toHex() + "\", \"" + ecol.toHex() + "\", " +
   steps + ", " + currentStep + ", " + stepDelay + ", \"" + nextCmd + "\")";
   _currentTimer = setTimeout(cmd, stepDelay);
}
      
// Sets the color of the control and all its children
// controlID: The ID of the control to set color in and all its child controls
// color: The color to set
function setColorAll(ctrlID, color)
{
   var ctrl = document.getElementById(ctrlID);
   if (ctrl != null)
   {
      ctrl.style.color = color;
      for (n = 0; n < ctrl.childNodes.length; n++)
      {
         // Entity nodes only
         if (ctrl.childNodes[n].nodeType == 1)
         {
            ctrl.childNodes[n].style.color = color;
         }
      }
   }
}

function setActiveMenuItem(activateControlID)
{
  var ctrl;
  if (_activeMenuControlID != null)
  {
    ctrl = document.getElementById(_activeMenuControlID);
    ctrl.style.fontWeight = _fontWeightInactive;
  }
  _activeMenuControlID = activateControlID;
  
  ctrl = document.getElementById(activateControlID);
  ctrl.style.fontWeight = _fontWeightActive;
}

function setActiveSubMenuItem(activateControlID)
{
  var ctrl;
  if (_activeSubMenuControlID != null)
  {
    ctrl = document.getElementById(_activeSubMenuControlID);
    if(ctrl) ctrl.style.fontWeight = _fontWeightInactive;
  }
  
  ctrl = document.getElementById(activateControlID);
  if(ctrl)
  {
    _activeSubMenuControlID = activateControlID;
    ctrl.style.fontWeight = _fontWeightActive;
  }
}

alert(document.getElementById("contentframe").document.body.contentHeight);
