//---------------------------------//
//                                 //
// DETERMINAR EXPLORADOR Y VERSIÓN //
//                                 //
//---------------------------------//

function Browser() {

  var ua, s, i;

  this.isIE    = false;  // Internet Explorer
  this.isOP    = false;  // Opera
  this.isNS    = false;  // Netscape
  this.version = null;

  ua = navigator.userAgent;

  s = "Opera";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isOP = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Tratar el explotador "Gecko" como Netscape 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }

  s = "MSIE";
  if ((i = ua.indexOf(s))) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }
}

var browser = new Browser();

//------------------------------------------------//
//                                                //
// MANEJO DE LA BARRA DE MENÚS Y DEL BOTON ACTIVO //
//                                                //
//------------------------------------------------//

var activeButton = null;

// Detectar clics en la página para desactivar los botones que esten activos.

if (browser.isIE)
  document.onmousedown = pageMousedown;
else
  document.addEventListener("mousedown", pageMousedown, true);

//Detectar el evento mouseover para inicializar el menu al salir de el.
  
if (browser.isIE)
  document.onmouseover = pageMousedown;
else
  document.addEventListener("mouseover", pageMousedown, true);
  
function pageMousedown(event) {

  var el;

  // Si no hay ningún boton activo, salir.

  if (activeButton == null)
    return;

  // Encontrar el elemento sobre el que se ha hecho clic.

  if (browser.isIE)
    el = window.event.srcElement;
  else
    el = (event.target.tagName ? event.target : event.target.parentNode);

  // Si ha sido sobre el boton activo, salir.

  if (el == activeButton)
    return;

  // Si no es parte del menú, inicializar el boton activo.

  if (getContainerWith(el, "DIV", "menu") == null) {
    resetButton(activeButton);
    activeButton = null;
  }
}

function buttonClick(event, menuId) {

  var button;

  // Detectar el botón pulsado.

  if (browser.isIE)
    button = window.event.srcElement;
  else
    button = event.currentTarget;

  // Asociar el menú correspondiente al botón (en caso de no estar ya asociado).
  // Además, inicializar la activación del menú.

  if (button.menu == null) {
    button.menu = document.getElementById(menuId);
    if (button.menu.isInitialized == null)
      menuInit(button.menu);
  }

  // Desactivar el boton activo actual, en caso de haberlo.

  if (activeButton != null)
    resetButton(activeButton);

  // Activar el botón, en caso de que no lo estuviera ya.

  if (button != activeButton) {
    depressButton(button);
    activeButton = button;
  }
  else
    activeButton = null;

  return false;
}

function buttonMouseover(event, menuId) {

  var button;

  // Detectar el botón.

  if (browser.isIE)
    button = window.event.srcElement;
  else
    button = event.currentTarget;

  // Si hay algún otro botón activo, activar este también.

  if (activeButton != null && activeButton != button)
    buttonClick(event, menuId);
}

function depressButton(button) {

  var x, y;

  // Actualizar el estilo del botón para que parezca pulsado.

  button.className += " menuButtonActive";

  // Colocar y mostrar el menú desplegable asociado a este botón.

  x = getPageOffsetLeft(button);
  y = getPageOffsetTop(button) + button.offsetHeight;

  // Para IE, ajustar posición.

  if (browser.isIE) {
    //x += button.offsetParent.clientLeft;
    //y += button.offsetParent.clientTop;
    x += 2;
    y += 2;
  }
  
  button.menu.style.left = x + "px";
  button.menu.style.top  = y + "px";
  button.menu.style.visibility = "visible";

  // Para IE; size, position and show the menu's IFRAME as well.

  if (button.menu.iframeEl != null)
  {
    button.menu.iframeEl.style.left = button.menu.style.left;
    button.menu.iframeEl.style.top  = button.menu.style.top;
    button.menu.iframeEl.style.width  = button.menu.offsetWidth + "px";
    button.menu.iframeEl.style.height = button.menu.offsetHeight + "px";
    button.menu.iframeEl.style.display = "";
  }
}

function resetButton(button) {

  // Restaurar el estilo de los botones.

  removeClassName(button, "menuButtonActive");

  // Ocultar el menú desplegable asociado al boton, 
  // Primero cerrar posibles submenús.

  if (button.menu != null) {
    closeSubMenu(button.menu);
    button.menu.style.visibility = "hidden";

    // Para IE, ocultar tambien el iframe del menú.

    if (button.menu.iframeEl != null)
      button.menu.iframeEl.style.display = "none";
  }
}

//----------------------------//
//                            //
// MANEJO DE MENÚS Y SUBMENÚS //
//                            //
//----------------------------//

function menuMouseover(event) {

  var menu;

  // Encontrar el menú determinado.

  if (browser.isIE)
    menu = getContainerWith(window.event.srcElement, "DIV", "menu");
  else
    menu = event.currentTarget;

  // Cerrar cualquier submenú activo.

  if (menu.activeItem != null)
    closeSubMenu(menu);
}

function menuItemMouseover(event, menuId) {

  var item, menu, x, y;

  // Encontrar el menuItem y su menuButton padre.

  if (browser.isIE)
    item = getContainerWith(window.event.srcElement, "A", "menuItem");
  else
    item = event.currentTarget;
    
  menu = getContainerWith(item, "DIV", "menu");

  // Cerrar cualquier submenú activo y marcar este como activo.

  if (menu.activeItem != null)
    closeSubMenu(menu);
        
  menu.activeItem = item;

  // Resaltar el menuItem.

  item.className += " menuItemHighlight";

  // Inicializar el submenú, si no lo estaba.

  if (item.subMenu == null) {
    item.subMenu = document.getElementById(menuId);
    if (item.subMenu.isInitialized == null)
      menuInit(item.subMenu);
  }

  // Obtener la posición del submenú a partir del menuItem.

  x = getPageOffsetLeft(item) + item.offsetWidth;
  y = getPageOffsetTop(item);

  // Ajustar la posición para mejor visualización.

  var maxX, maxY;

  if (browser.isIE) {
    maxX = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft) +
      (document.documentElement.clientWidth != 0 ? document.documentElement.clientWidth : document.body.clientWidth);
    maxY = Math.max(document.documentElement.scrollTop, document.body.scrollTop) +
      (document.documentElement.clientHeight != 0 ? document.documentElement.clientHeight : document.body.clientHeight);
  }
  if (browser.isOP) {
    maxX = document.documentElement.scrollLeft + window.innerWidth;
    maxY = document.documentElement.scrollTop  + window.innerHeight;
  }
  if (browser.isNS) {
    maxX = window.scrollX + window.innerWidth;
    maxY = window.scrollY + window.innerHeight;
  }
  maxX -= item.subMenu.offsetWidth;
  maxY -= item.subMenu.offsetHeight;

  if (x > maxX)
    x = Math.max(0, x - item.offsetWidth - item.subMenu.offsetWidth
      + (menu.offsetWidth - item.offsetWidth));
  y = Math.max(0, Math.min(y, maxY));

  // Posiciona y muestra el submenú.

  item.subMenu.style.left       = x + "px";
  item.subMenu.style.top        = y + "px";
  item.subMenu.style.visibility = "visible";

  // Para IE; determinar tamaño, posición and mostrar el iframe de los menús también.

  if (item.subMenu.iframeEl != null)
  {
    item.subMenu.iframeEl.style.left    = item.subMenu.style.left;
    item.subMenu.iframeEl.style.top     = item.subMenu.style.top;
    item.subMenu.iframeEl.style.width   = item.subMenu.offsetWidth + "px";
    item.subMenu.iframeEl.style.height  = item.subMenu.offsetHeight + "px";
    item.subMenu.iframeEl.style.display = "";
  }

  // Detener el evento del bubbling.

  if (browser.isIE)
    window.event.cancelBubble = true;
  else
    event.stopPropagation();
}

function closeSubMenu(menu) {

  if (menu == null || menu.activeItem == null)
    return;

  // Cerrar todos los subMenús.

  if (menu.activeItem.subMenu != null) {
    closeSubMenu(menu.activeItem.subMenu);


    // Ocultar los submenús.
    menu.activeItem.subMenu.style.visibility = "hidden";

    // Para IE, ocultar el iframe de los submenús también.

    if (menu.activeItem.subMenu.iframeEl != null)
      menu.activeItem.subMenu.iframeEl.style.display = "none";

    menu.activeItem.subMenu = null;
  }

  // Desactivar el menuItem que este activo.

  removeClassName(menu.activeItem, "menuItemHighlight");
  menu.activeItem = null;
}

//-------------------//
//                   //
// INICIALIZAR MENÚS //
//                   //
//-------------------//

function menuInit(menu) {

  var itemList, spanList;
  var textEl, arrowEl;
  var itemWidth;
  var w, dw;
  var i, j;

  // Para IE, recolola las flechas de los menús.

  if (browser.isIE) {
    menu.style.lineHeight = "2.5ex";
    spanList = menu.getElementsByTagName("SPAN");
    for (i = 0; i < spanList.length; i++)
      if (hasClassName(spanList[i], "menuItemArrow")) {
        spanList[i].style.fontFamily = "Webdings";
        spanList[i].firstChild.nodeValue = "4";
      }
  }

  // Determinar la anchura del MenuItem

  itemList = menu.getElementsByTagName("A");
  if (itemList.length > 0)
    itemWidth = itemList[0].offsetWidth;
  else
    return;

  // Los MenuItems que tengan flecha, se agrega 'padding' para alinearlas a la derecha.

  for (i = 0; i < itemList.length; i++) {
    spanList = itemList[i].getElementsByTagName("SPAN");
    textEl  = null;
    arrowEl = null;
    for (j = 0; j < spanList.length; j++) {
      if (hasClassName(spanList[j], "menuItemText"))
        textEl = spanList[j];
      if (hasClassName(spanList[j], "menuItemArrow")) {
        arrowEl = spanList[j];
      }
    }
    if (textEl != null && arrowEl != null) {
      textEl.style.paddingRight = (itemWidth 
        - (textEl.offsetWidth + arrowEl.offsetWidth)) + "px";

      // Para Opera, borrar el margen derecho negativo.

      if (browser.isOP)
        arrowEl.style.marginRight = "0px";
    }
  }

  // Arreglar el proble de 'hover' de  IE hover estableciendo un ancho especifico
  // al primer elemento del menú.

  if (browser.isIE) {
    w = itemList[0].offsetWidth;
    itemList[0].style.width = w + "px";
    dw = itemList[0].offsetWidth - w;
    w -= dw;
    itemList[0].style.width = w + "px";
  }

  // Arreglar el problema de visualización de IE (SELECT elementos y otros elemenos
  // superpuestos) añadiendo un iframe debajo del menú.

  if (browser.isIE) {
    var iframeEl = document.createElement("IFRAME");
    iframeEl.frameBorder = 0;
    iframeEl.src = "javascript:;";
    iframeEl.style.display = "none";
    iframeEl.style.position = "absolute";
    iframeEl.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
    menu.iframeEl = menu.parentNode.insertBefore(iframeEl, menu);
  }

  // Marcar el menú como inicializado.

  menu.isInitialized = true;
}

//-------------------------------//
//                               //
// FUNCIONES DE UTILIDAD GENERAL //
//                               //
//-------------------------------//

function getContainerWith(node, tagName, className) {

  // Empezando desde el nodo enviado, encontrar el elemento contenedor mas cercano
  // con un determinado tag tagName y className.

  while (node != null) {
    if (node.tagName != null && node.tagName == tagName &&
        hasClassName(node, className)) {
      return node;
      }
    node = node.parentNode;
  }

  return node;
}

function hasClassName(el, name) {

  var i, list;

  // Devuelve true si el elemeno enviado tiene el nombre de clase enviado

  list = el.className.split(" ");
  for (i = 0; i < list.length; i++)
    if (list[i] == name)
      return true;

  return false;
}

function removeClassName(el, name) {

  var i, curList, newList;

  if (el.className == null)
    return;

  // Quitar los nombres de clase añadidos a la propiedad className.

  newList = new Array();
  curList = el.className.split(" ");
  for (i = 0; i < curList.length; i++)
    if (curList[i] != name)
      newList.push(curList[i]);
  el.className = newList.join(" ");
}

function getPageOffsetLeft(el) {

  var x;

  // Obtener la coordenada X de un elemento en relación a la página.

  x = el.offsetLeft;
  if (el.offsetParent != null)
    x += getPageOffsetLeft(el.offsetParent);

  return x;
}

function getPageOffsetTop(el) {

  var y;

  // Obtener la coordenada Y de un elemento en relación a la página.

  y = el.offsetTop;
  if (el.offsetParent != null)
    y += getPageOffsetTop(el.offsetParent);

  return y;
}