1/******************************************************************************
*  NOMBRE --------->: menu.js                                                 *
*  AUTOR ---------->: David Trigo Pérez                                       *
*  LENGUAJE USADO ->: Javascript                                              *
*  DESCRIPCIÓN ---->: Funciones para el funcionamiento de menú desplegable.   *
******************************************************************************/
Event.observe(window,'load',function(){Inicio(MenuVertical)});

//*****************************************************************************
function Inicio(Menu){ //Muestra el menú
//*****************************************************************************
  cerrarTodas(Menu);
  Menu.style.visibility = 'visible';
}
//*****************************************************************************
function cambiarEstado(Elemento,Contenido,Tipo){ //Cambia el estado de una opción de menú (activo y desplegado / inactivo y no desplegado)
//*****************************************************************************
  //Valor por defecto para los parámetros
  Tipo = (typeof Tipo == 'undefined')?'htm':Tipo; // htm por defecto

  var ElementoContenedor = document.getElementById(Elemento.id + '.0');
  var OffsetTopMenu = document.getElementById('MenuVertical').offsetTop;
  var LIs, LI;
  var Hermano = proximoHermano(Elemento);
  DeseleccionarHermanos(Elemento);
  CerrarHermanos(Elemento);
  CerrarNietos(Elemento);
  //Si el elemento no está activo ni la imagen que pueda contener dentro (esto último para los de nivel 0)
  if(Elemento.className.search('Activo') == -1 && ((Elemento.firstChild.nodeName == 'IMG')?Elemento.firstChild.className.search('Activo'):-1) == -1){
    if(Contenido){
      if(Contenido == 2){ //Caso especial (2) para cuando no hay contenido expecífico
        var ImagenGenerica = padre(Elemento).id+'_A.jpg'; //La imagen genérica de la subsección
        PeticionAJAXaCapa (('contenidos/Generico.php?Titulo='+Elemento.title+'&Imagen='+ImagenGenerica),'capaContenido','ponerHash("t='+Elemento.title.gsub(' ', '-')+'&i='+ImagenGenerica+'&c=0");SeguimientoAnalytics()');//Se crea el hash en la URL para gestionar la recarga, botón atrás y enlace directo. El parámetro "c" indica si ha página propia de contenido (1) o no (0)
      }else{ //Caso normal
        PeticionAJAXaCapa (('contenidos/'+Elemento.id+'.'+Tipo),'capaContenido','ponerHash("t='+Elemento.title.gsub(' ', '-')+'&d='+Elemento.id+'.'+Tipo+'&c=1");SeguimientoAnalytics()');//Se crea el hash en la URL para gestionar la recarga, botón atrás y enlace directo. El parámetro "c" indica si ha página propia de contenido (1) o no (0)
      }
      window.FormularioActivo = 'FormularioPeq'; //Para que el enter ataque este formulario
    }
    //Se activa el botón
    if(Elemento.firstChild.nodeName != 'IMG'){ //Pestañas de 1er nivel
      Elemento.className = Elemento.className + 'Activo';
    }else{ //Pestañas de 2º nivel e inferiores
      Elemento.firstChild.src = Elemento.firstChild.src.replace('A.gif','B.gif') ;
      Elemento.firstChild.className = Elemento.firstChild.className + 'Activo';
    }
    //Se expande el botón
    if (ElementoContenedor != null){
      ElementoContenedor.style.display = 'block';
      if(Hermano){ //Si el elemento tiene un hermano siguiente
        if(nivel(Elemento)==0){
          fondoEspecial(Hermano,true); //Se el activa el fondo especial para este hermano
        }
      }
    }
  }
  if(Contenido){
    //Se coloca la flecha a la derecha del elemento seleccionado
    if(nivel(Elemento)==0){ //Si es elemento de 1er nivel
      if(Elemento.id != 'M6'){ //Si no es la última opción
        colocarFlecha(obtenerPosicion(Elemento).y+parseInt(Elemento.clientHeight)/2+4);
      }else{ //Si es el último elemento (del 1er nivel)
        colocarFlecha(obtenerPosicion(Elemento).y+parseInt(Elemento.clientHeight)/2-6);
      }
    }else{ //Si es un elemento de nivel mayor que 0
      colocarFlecha(obtenerPosicion(Elemento).y+parseInt(Elemento.clientHeight)/2+2);
    }
  }else{
    //Se oculta la flecha
      colocarFlecha(-1);
  }
}
//*****************************************************************************
function cerrarTodas(Menu){ //Cierra todas las pestañas desplegadas del menú
//*****************************************************************************
  DeseleccionarTodo(Menu);
  var LIs = Menu.getElementsByTagName('li');  
  for (var i=0;i<LIs.length; i++){
    var LI =LIs[i];
    if(esContenedor(LI)){
      LI.style.display = 'none';
    }
  }
}
//*****************************************************************************
function DeseleccionarTodo(Menu){ //Deselecciona las opciones del mismo nivel
//*****************************************************************************
  var LIs = Menu.getElementsByTagName('li');  
  colocarFlecha(-1);
  for (var i=0;i<LIs.length; i++){
  LI =LIs[i];
    if(LI.firstChild.nodeName != 'IMG'){
      LI.className = LI.className.replace('Activo','');
    }else{
      LI.firstChild.src = LI.firstChild.src.replace('B.gif','A.gif');
      LI.firstChild.className = '';
    }
  }
}
//*****************************************************************************
function DeseleccionarHermanos(Elemento){ //Deselecciona las opciones del mismo nivel
//*****************************************************************************
  var ElementoPadre = Elemento.parentNode;
  var LIs, LI;
  if (ElementoPadre != null){
    LIs = ElementoPadre.getElementsByTagName('li');  
    for (var i=0;i<LIs.length; i++){
      LI =LIs[i];
      if (LI.id != Elemento.id){
        if(LI.firstChild.nodeName != 'IMG'){
          LI.className = LI.className.replace('Activo','');
        }else{
          LI.firstChild.src = LI.firstChild.src.replace('B.gif','A.gif');
          LI.firstChild.className = '';
        }
      }
    }
  }
}
//*****************************************************************************
function CerrarNietos(Elemento){ //Cierra y desactiva las opciones inferiores a 1 nivel
//*****************************************************************************
  if(document.getElementById(Elemento.id + '.0')){
    if(document.getElementById(Elemento.id + '.0').firstChild.nodeName == 'UL'){ //Caso de IExplorer
      ElementoPadre = document.getElementById(Elemento.id + '.0').firstChild;
    }else{ //Caso de Firefox
      ElementoPadre = document.getElementById(Elemento.id + '.0').firstChild.nextSibling;
    }
  }else{
    return;
  }
  var LIs, LI;
  var nivelElemento = nivel(Elemento);
  var PadreDelContenedor;
  LIs = ElementoPadre.getElementsByTagName('li');  
  for (var i=0;i<LIs.length; i++){
    LI =LIs[i];
    if(esContenedor(LI)){ //Si es un elemento contenedor
      if(LI.style.display != "none"){
        LI.style.display = 'none'; //Se pliega el contenedor
      }
    }
  }
}
//*****************************************************************************
function CerrarHermanos(Elemento){ //Cierra y desactiva las opciones del mismo nivel
//*****************************************************************************
  var ElementoPadre = Elemento.parentNode;
  var LIs, LI;
  var nivelElemento = nivel(Elemento);
  var PadreDelContenedor;
  if (ElementoPadre != null){
    LIs = ElementoPadre.getElementsByTagName('li');  
    for (var i=0;i<LIs.length; i++){
      LI =LIs[i];
//      if(LI.id.search(Elemento.id) == -1){ //Si no es el propio elemento ni sus hijos
        if(esContenedor(LI) && LI.style.display == 'block'){ //Si es un elemento contenedor y está visible
          LI.style.display = 'none'; //Se pliega el contenedor
          //PadreDelContenedor = document.getElementById(LI.id.substr(0,Elemento.id.length));
          PadreDelContenedor = padre(LI);
          if(nivel(PadreDelContenedor) == 0){ //Se desactiva un posible fondo especial del hermano del padre
            if(proximoHermano(PadreDelContenedor)){
              fondoEspecial(proximoHermano(PadreDelContenedor),false);
            }
          }
        }
//      }
    }
  }
}
//*****************************************************************************
function proximoHermano(Elemento){ //Devuelve el elemento hermano siguiente
//*****************************************************************************
  var ElementoPadre = Elemento.parentNode;
  var LIs;
  var cogerSiguiente = false;
  var NivelElemento = nivel(Elemento);
  if (ElementoPadre != null){
    LIs = ElementoPadre.getElementsByTagName('li');  
    for (var i=0;i<LIs.length; i++){
      if(!esContenedor(LIs[i]) && NivelElemento == nivel(LIs[i])){ //Excluye los elementos contenedores o son de otro nivel
        if(cogerSiguiente){
          return LIs[i];
        }
        if(LIs[i].id == Elemento.id){
          cogerSiguiente = true;
        }
      }
    }
  }
  return false;
}
//*****************************************************************************
function fondoEspecial(Elemento,Activo){ //Pone o quita el fondo especial para hermano de elemento desplegado
//*****************************************************************************
  if(!Activo){
    if(Elemento.className.charAt(Elemento.className.length-1) == '2'){
      Elemento.className = Elemento.className.substr(0,Elemento.className.length-1);
    }
  }else{
    if(Elemento.className.charAt(Elemento.className.length-1) != '2'){
      Elemento.className = Elemento.className + '2';
    }
  }
}
//*****************************************************************************
function nivel(Elemento){ //Indica de qué nivel es el elemento (profundidad)
//*****************************************************************************
  return cuantasLetras(Elemento.id,'.');
}
//*****************************************************************************
function valorElemento(Elemento){ //Le asigna un valor al elemento para poder hacer comparaciones
//*****************************************************************************
  var ArrayTemp = Elemento.id.slice(1).split('.');
  var Valor = 0;
  for (var i=0;i<ArrayTemp.length; i++){
    Valor += parseInt(ArrayTemp[i])*Math.pow(10,(3-i));
  }
  return Valor;
}
//*****************************************************************************
function obtenerPosicion(Elemento){ //Obtiene la posición XY del elemento y lo devuelve en un objeto
//*****************************************************************************
  var curleft = 0;
  var curtop = 0;
  var border;
  var padding;
  if (Elemento.offsetParent){
    do{
      // XXX: If the element is position: relative we have to add borderWidth
      if (obtenerEstilo(Elemento, 'position') != 'absolute'){
        if (border = obtenerEstilo(Elemento, 'border-top-width')) curtop += parseInt(border);
        if (border = obtenerEstilo(Elemento, 'border-left-width')) curleft += parseInt(border);
        if (padding = obtenerEstilo(Elemento, 'padding-top')) curtop += parseInt(padding);
        if (padding = obtenerEstilo(Elemento, 'padding-left')) curleft += parseInt(padding);
      }
      curleft += Elemento.offsetLeft;
      curtop += Elemento.offsetTop;
    }
    while (Elemento = Elemento.offsetParent)
  }else if (Elemento.x){
    curleft += Elemento.x;
    curtop += Elemento.y;
  }
  return {'x': curleft, 'y': curtop};
}
//*****************************************************************************
function obtenerEstilo(Elemento, Propiedad){ //Devuelve el estilo del elemento
//*****************************************************************************
  if (Elemento.currentStyle)
    return Elemento.currentStyle[Propiedad];
  else if (window.getComputedStyle)
    return document.defaultView.getComputedStyle(Elemento,null).getPropertyValue(Propiedad);
}
//*****************************************************************************
function colocarFlecha(y){ //Coloca la flecha. (y = -1) la oculta.
//*****************************************************************************
  if(y == -1){
    document.getElementById('FlechaActiva').style.visibility = 'hidden';
  }else{
    var ie = navigator.userAgent.toLowerCase().indexOf('msie')!=-1; // Detectar si el navegador es Internet Explorer
    var offSet = 0;
    if(ie){
       offSet -= 120;
    }else{
       offSet -= 10;
       document.getElementById('FlechaActiva').style.left = 228;
    }
    document.getElementById('FlechaActiva').style.top = y + offSet;
    document.getElementById('FlechaActiva').style.visibility = 'visible';
  }
}
//*****************************************************************************
function cuantasLetras(Palabra, Letra){ //Cuenta las letras indicadas en la palabra
//*****************************************************************************
  var Encontradas = 0;
  for (var i=0;i<Palabra.length; i++){
    if(Palabra.charAt(i) == Letra){
      Encontradas += 1;
    }
  }
  return Encontradas;
}
//*****************************************************************************
function esContenedor(Elemento){ //Devuelve true si el elemento es contenedor (valor 0 al final)
//*****************************************************************************
  if(Number(ultimoIndice(Elemento)) == 0){
    return true;
  }else{
    return false;
  }
}
//*****************************************************************************
function ultimoIndice(Elemento){ //Devuelve el valor del último índice del id del elemento
//*****************************************************************************
  var Posicion=0;
  var ID = Elemento.id;
  for (var i=ID.length;i>0; i--){
    if(ID.charAt(i) == '.'){
      Posicion = i+1;
      break;
    }
  }
  return ID.substr(Posicion);
}
//*****************************************************************************
function padre(Elemento){ //Devuelve elemento padre
//*****************************************************************************
  var Posicion=0;
  var ID = Elemento.id;
  for (var i=ID.length;i>0; i--){
    if(ID.charAt(i-1) == '.'){
      Posicion = i-1;
      break;
    }
  }
  return document.getElementById(ID.substr(0,Posicion));
}
//*****************************************************************************
function ratonEncima(Objeto){ //Cambia el estilo para el evento MouseOver
//*****************************************************************************
  Objeto.className = Objeto.className+'Over';
}
//*****************************************************************************
function ratonFuera(Objeto, Estilo){ //Cambia el estilo para el evento MouseOut
//*****************************************************************************
  Objeto.className = Objeto.className.substring(0,Objeto.className.search('Over'));
}
//*****************************************************************************
