
/*
  Fichero de Herramientas del Menú
*/


/*Descripción de la estructura del Menú
  El menú se basa en la adición de atributos a cada uno de los elementos que lo componen.
  Al menos se necesitan tres atributos para ayudar a estructurar el menú
  y un conjunto extra de atributos que le añaden funcionalidad.

  Estructurales
  id:        Identificador único de elemento.
  father_id: Identificador de elemento padre. Determina bajo qué elemento del menú
             se va a situar el elemento.
  att_list:  Listado de los atributos de funcionalidad anexados al elemento
             del menú. Se separan entre sí por el carácter de la variable 'delimiter'

  Funcionales
  div_class: Clase que identifica y define al elemento del menú en el archivo 'menu.css'
  menu_name: Nombre que aparecerá en el elemento cuando se imprima el menú por pantalla.
  section:   URI al que dirige el elemento del menú al pinchar sobre él.
*/

// Define el separador de atributos en la propiedad att_list
var delimiter = '|';

// Definen el 'id' de tag HTML UL y LI. La lógica de construcción del menú
// les va añadiendo un número incremental (0..n).
var root_ul = 'root_';
var root_li = 'leafroot_';
var leaf_li = 'leaf_';
var element_li = 'element_';
var link_li = 'link_';

// Define el id del elemento HTML del que va a colgar el menú.
var father_element = 'ContenedorMenu';

// Define el id del Menú
var menuId = 'div_menu';

// Indica el nombre visible que tendrá el elemento raiz del arbol de menú.
var root_txt = '';

var url_pattern = 'http';
var fex_pattern = 'FEX';
var jsc_pattern = ');';


var mainElement = null;
var treeMenu = [];
var paramMenu = [];
var user_focus = 0;

/*mainMenu[mainMenu.length] = {id:'1',father_id:'0',att_list:'div_class|menu_name',div_class:'fclose',menu_name:'Elemento Ppal 1'};
mainMenu[mainMenu.length] = {id:'2',father_id:'1',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento Sec 1.1',section:'INFORME1.FEX'};
mainMenu[mainMenu.length] = {id:'3',father_id:'1',att_list:'div_class|menu_name',div_class:'fclose',menu_name:'Elemento Sec 1.2'};
mainMenu[mainMenu.length] = {id:'4',father_id:'3',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento Sec 1.2.1',section:'http://www.google.es'};
mainMenu[mainMenu.length] = {id:'5',father_id:'0',att_list:'div_class|menu_name',div_class:'fclose',menu_name:'Elemento Sec 2'};
mainMenu[mainMenu.length] = {id:'6',father_id:'5',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento Sec 2.1',section:'INFORME2.FEX'};
mainMenu[mainMenu.length] = {id:'7',father_id:'0',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento Ppal 3',section:'INFORME3.FEX'};

mainMenu[mainMenu.length] = {id:'1',father_id:'0',att_list:'div_class|menu_name',div_class:'fclose',menu_name:'Elemento Ppal 1'};
mainMenu[mainMenu.length] = {id:'2',father_id:'1',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento Sec 1.1',section:'INFORME1.FEX'};
mainMenu[mainMenu.length] = {id:'3',father_id:'1',att_list:'div_class|menu_name',div_class:'fclose',menu_name:'Elemento Sec 1.2'};
mainMenu[mainMenu.length] = {id:'4',father_id:'3',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento Sec 1.2.1',section:'http://www.google.es'};
mainMenu[mainMenu.length] = {id:'5',father_id:'0',att_list:'div_class|menu_name',div_class:'fclose',menu_name:'Elemento Sec 2'};
mainMenu[mainMenu.length] = {id:'6',father_id:'5',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento Sec 2.1',section:'INFORME2.FEX'};
mainMenu[mainMenu.length] = {id:'7',father_id:'0',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento Ppal 3',section:'INFORME3.FEX'};
mainMenu[mainMenu.length] = {id:'8',father_id:'5',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba1',section:'INFORME4.FEX'};
mainMenu[mainMenu.length] = {id:'9',father_id:'5',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba2',section:'INFORME5.FEX'};
mainMenu[mainMenu.length] = {id:'10',father_id:'5',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba3',section:'INFORME6.pdf'};
mainMenu[mainMenu.length] = {id:'11',father_id:'3',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba4',section:'INFORME7.xls'};
mainMenu[mainMenu.length] = {id:'12',father_id:'0',att_list:'div_class|menu_name',div_class:'fclose',menu_name:'Elemento de Prueba5'};
mainMenu[mainMenu.length] = {id:'13',father_id:'12',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba6',section:'INFORME9.FEX'};
mainMenu[mainMenu.length] = {id:'14',father_id:'12',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba7',section:'INFORM10.FEX'};
mainMenu[mainMenu.length] = {id:'15',father_id:'12',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba8',section:'INFORM11.FEX'};
mainMenu[mainMenu.length] = {id:'16',father_id:'12',att_list:'div_class|menu_name',div_class:'fclose',menu_name:'Elemento de Prueba9'};
mainMenu[mainMenu.length] = {id:'17',father_id:'16',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba10',section:'http://barrapunto.com'};
mainMenu[mainMenu.length] = {id:'18',father_id:'16',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba11',section:'INFORM12.FEX'};
mainMenu[mainMenu.length] = {id:'19',father_id:'16',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba12',section:'INFORM13.pdf'};
mainMenu[mainMenu.length] = {id:'20',father_id:'16',att_list:'div_class|menu_name',div_class:'fclose',menu_name:'Elemento de Prueba13'};
mainMenu[mainMenu.length] = {id:'21',father_id:'20',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba14',section:'INFORM14.FEX'};
mainMenu[mainMenu.length] = {id:'22',father_id:'20',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba15',section:'http://www.xataka.com'};
mainMenu[mainMenu.length] = {id:'23',father_id:'20',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba16',section:'INFORM15.FEX'};
mainMenu[mainMenu.length] = {id:'24',father_id:'20',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba17',section:'INFORM16.FEX'};
mainMenu[mainMenu.length] = {id:'25',father_id:'20',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba18',section:'INFORM17.FEX'};
mainMenu[mainMenu.length] = {id:'26',father_id:'20',att_list:'div_class|menu_name',div_class:'fclose',menu_name:'Elemento de Prueba19'};
mainMenu[mainMenu.length] = {id:'27',father_id:'26',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba20',section:'http://www.microsoft.com'};
mainMenu[mainMenu.length] = {id:'28',father_id:'26',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba21',section:'http://www.yahoo.es'};
mainMenu[mainMenu.length] = {id:'29',father_id:'26',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba22',section:'INFORM18.FEX'};
mainMenu[mainMenu.length] = {id:'30',father_id:'26',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba23',section:'INFORM19.FEX'};
mainMenu[mainMenu.length] = {id:'31',father_id:'0',att_list:'div_class|menu_name|section',div_class:'leaf',menu_name:'Elemento de Prueba24',section:'alert("Ejecutando función Javascript");'};
*/
var mainMenu = [];
mainMenu[mainMenu.length] = {id:'1',father_id:'0',att_list:'div_class|menu_name|section',div_class:'fclose',menu_name:'Encuentra tu especialidad',section:'http://www.soldados.com/que_ofrecemos/formacion/especialidades.htm'                                                                                                                                                                                                                                                                                                   };


// Esta función genera dos estructuras auxiliares necesarias para la
// construcción del menú.
function getMenuTreeAtts(){
    for (var i = 0, len = mainMenu.length; i < len; ++i){
	      if (treeMenu[parseInt(mainMenu[i].id)] == null){
		        treeMenu[parseInt(mainMenu[i].id)] = new Array();
		    }
		    if (treeMenu[parseInt(mainMenu[i].father_id)] == null) {
		  	  treeMenu[parseInt(mainMenu[i].father_id)] = new Array();
		    }
	      treeMenu[parseInt(mainMenu[i].father_id)].push(parseInt(mainMenu[i].id));

	      // Carga de parámetros

	      atts = mainMenu[i]['att_list'].split(delimiter);
	      if (atts != null && atts!='' && atts.length > 0) {
	          for (var j = 0, lenj = atts.length; j < lenj; ++j) {
  		          if (paramMenu[parseInt(mainMenu[i].id)] == null) {
	  	     	        paramMenu[parseInt(mainMenu[i].id)] = new Array();
		            }
	              paramMenu[parseInt(mainMenu[i]['id'])][atts[j]] = new Array(mainMenu[i][atts[j]]);
		        }
		    }
	  }
}

// Función para el tratamiento de los atributos de Funcionalidad.
// Esta función tiene un comportamiento básico por defecto y se debe modificar
// si se pretende añadir o quitar atributos a los elementos del menú, o cambiar
// el funcionamiento de los ya existentes.

function buildMenuElement (mNode,mId,mFId) {
    mLink = document.createElement('a');
    mLink.id = link_li + mId;
    mLayer = document.createElement('div');
    mLayer.id = element_li + mId;
    //target:"contenido
    
    nextURL = new String(paramMenu[mId]['section']);
    targetURL = new String(paramMenu[mId]['target']);
    // Si el elemento del menú es un submenú (rama)
    if (nextURL == '' || nextURL == null || nextURL == 'undefined') {
    	  mLink.setAttribute('href','#');
    	  mLayer.className = paramMenu[idTreeMenu]['div_class'];
    	  mLayer.onclick=function(){folderHandler(this.id);};
    }
    // Si el elemento del menú es un objeto (hoja)
    else {
    	// Si es una funcion JavaScript
    	if (nextURL.indexOf(jsc_pattern)>=0) {
        mLink.setAttribute('href','#');
    		mLayer.className = 'jsc';
    		var cad = 'mLayer.onclick= function() {' + nextURL + ' folderHandler(this.id); };';
        eval (cad);
    	}
    	else{
    		/* aki comprobamos que haya target y si lo ahy se lo aplicamos */
				if (targetURL != '' && targetURL != null && targetURL != 'undefined') {
					mLink.setAttribute('target',targetURL+'');
					}
        			/* no eliminar +'' despues de la variable nextURL sino internet explorer interpreta que es un objeto y no una cadena.*/
			mLink.setAttribute('href',nextURL+'');
        // URL Externa
        if (nextURL.indexOf(url_pattern)>=0) {
        	mLayer.className = 'uri';
        }
        // Informe FOCUS
        else if (nextURL.indexOf(fex_pattern)>=0) {
        	mLayer.className = 'fex';
        }
        // Otros elementos
        else {
        	mLayer.className = 'unk';
        }
        mLayer.onclick=function(){folderHandler(this.id);};
      }
    }
    rootNode = document.createElement('ul');
    rootNode.id = root_ul + mId;
    addEvent(mLayer);
    mLink.appendChild(document.createTextNode(paramMenu[mId]['asdasf','menu_name']));
    mLayer.appendChild(mLink);
    mNode.appendChild(mLayer);
    rootNode.appendChild(mNode);
    document.getElementById(root_li + mFId).appendChild(rootNode);
}

// Función que recorre la estructura del menú y la trata como un árbol
// siguiendo un recorrido 'Pre-Order'.
// ATENCION: Se recomienda no modificar esta función.

function buildMenu (fatherIdMenuTree, maxLength) {
    var z = 0;
    while (z < maxLength) {
        idTreeMenu = treeMenu[fatherIdMenuTree][z];
    	  lengthIdTreeMenu = treeMenu[idTreeMenu].length;
     	  menuNode = document.createElement('li');
     	  if (lengthIdTreeMenu > 0) {
            menuNode.id = root_li + idTreeMenu;
            buildMenuElement(menuNode, idTreeMenu, fatherIdMenuTree);
   	   	    buildMenu(idTreeMenu, treeMenu[idTreeMenu].length);
  		  }
  		  else {
            menuNode.id = leaf_li + idTreeMenu;
            buildMenuElement(menuNode, idTreeMenu, fatherIdMenuTree);
        }
   	    z++;
    }
}

/*
    Función que se ejecuta cada vez que se detecta un evento click del ratón
    sobre alguno de los elementos del menú.
*/
function folderHandler(nodeId) {
  lastChar = nodeId.indexOf('_');
  elementId = parseInt(nodeId.substring(lastChar+1, nodeId.length));
  divtag = document.getElementById(element_li + elementId);
  o_c = divtag.className;
	for (var i = 0, len = treeMenu[elementId].length; i < len; ++i) {
		ultag = document.getElementById(root_ul+treeMenu[elementId][i]);
		if (o_c=='fclose') {
		  ultag.className = 'vis';
		}
		else {
			ultag.className = 'hid';
	  }
  }
	if (o_c=='fclose') {
		divtag.className = 'fopen';
  }
  else if (o_c=='fopen'){
  	divtag.className = 'fclose';
  }
	document.getElementById(link_li+user_focus).className = null;
	document.getElementById(link_li+elementId).className = 'focused';
	user_focus = elementId;
  return false;
}

function stopEventBubble(e) {
	if (e.stopPropagation) {
	     e.stopPropagation();
	}
  else {
  	   e.cancelBubble = true;
  }
}

function addEvent(el) {
	if (el.addEventListener){
	    el.addEventListener('click', stopEventBubble, false);
  }
  else {
  	el.attachEvent('onclick', stopEventBubble);
  }
}

// Función principal que se ocupa de crear un menú
function getTreeMenu () {
    // Se tratan los atributos Estructurales y de Funcionalidad
    getMenuTreeAtts();
    // Inicio creación elemento Principal del Menú
    mainElement = document.createElement('div');
 	  mainElement.id = menuId;
 	  menuRoot = document.createElement('ul');
 	  menuRoot.id = root_ul + user_focus;
 	  menuRoot.className = 'vis';
 	  menuLeafRoot = document.createElement('li');
 	  menuLeafRoot.id = root_li + user_focus;
    menuLayer = document.createElement('div');
    menuLayer.id = element_li + user_focus;
    menuLayer.className = 'fclose';
    menuLayer.onclick=function(){folderHandler(this.id);};
    addEvent(menuLayer);
 	  menuLink = document.createElement('a');
 	  menuLink.setAttribute('href','#');
 	  menuLink.id = link_li + user_focus;
 	  menuLink.className = 'focused';
 	  menuLink.appendChild(document.createTextNode(root_txt));
 	  menuLeafRoot.appendChild(menuLayer).appendChild(menuLink);
 	  mainElement.appendChild(menuRoot).appendChild(menuLeafRoot);
 	  document.getElementById(father_element).appendChild(mainElement);
 	  // Fin creación elemento Ppal. del Menú

 	  // Se pasa a construir el menu.
	  buildMenu(0, treeMenu[0].length);
	  // Se hace visible el contenido del primer nivel del menú
	  folderHandler(menuLayer.id);
	  return false;
}
