//--------------------------VARIABLES Y CONTANTES-------------------------------

var NS = ( navigator.appName == "Netscape" && parseInt(navigator.appVersion, 10) >= 5 ) ? true : false;
var IE = ( navigator.appVersion.search(/MSIE/) != -1)? true : false;

var MENU_ANCHO = 150;
var ITEM_ALTO = 20;
var MENU_DIR_FLECHA = "../images/flecha.gif";

var MENU_ESTILO = '';

var MENU_IMAGEN_ALTO = 30;
var MENU_IMAGEN_ANCHO = 30;

var MENU_DIR_DESPLIEGUE = "DERECHA";
var NO_IMAGEN = "images/no_imagen.gif";

//------------------------FIN VARIABLES Y CONTANTES-----------------------------


//-------------------------------MENU ITEM---------------------------------------

function MenuItem(id, nombre, ancho) {
	this.id = id;
	this.nombre = nombre;
	this.items = null;
	this.accion = null;
	this.mostrar = menu_mostrar;
	this.ocultar = menu_ocultar;
	this.agregarItem = menu_agregar_item;
	this.eliminarItem = menu_eliminar_item;
	this.buscarMenu = menu_buscar_menu;
	this.ocultarHijos = menu_ocultar_hijos;
	this.obtenerXY = menu_obtener_xy;
	this.top = 0;
	this.capa = null;
	this.ubicacion = null;
	this.ancho = ancho ? ancho : MENU_ANCHO;
	this.crearCapa = menu_crear_capa;
	this.obtenerCoordenadas = menu_obtener_coordenadas;
	this.iframe = null;
	this.altoItem = parseInt(ITEM_ALTO, 10);
	this.altoImagen = parseInt(MENU_IMAGEN_ALTO, 10);
	this.anchoImagen = parseInt(MENU_IMAGEN_ANCHO, 10);
	this.estilo = MENU_ESTILO;
	this.dirDespliegue = MENU_DIR_DESPLIEGUE;
//	this.imagen = "imagen.jpg";
	//this.imagenSobre = "imagen_sobre.jpg";
}

function menu_mostrar(x, y, hijo) {
	if (this.items == null || this.items.length == 0)
		return;
	
	this.ocultarHijos();
	
	var conImagenes = false;
	for (var i = 0; i < this.items.length; i++) {
		if (this.items[i].imagen) {
			conImagenes = true;
			break;
		}
	}
	
	if (this.ubicacion)
		MENU_ESTILO = this.menuEstilo;

	//calcular la posicion del menú
	var posicion = null;
        if (x)
		posicion = this.obtenerXY(x, y, hijo);
        else
                posicion = {x: 0, y: 0};

	var ancho_tabla = this.ubicacion ? "100%": this.ancho + "px";

	var html = "<div class='" + MENU_ESTILO + "'><table border='0' width='" + ancho_tabla + "' cellspacing='1' cellpading='0' class='fondo'>";
        for (var i = 0; i < this.items.length; i++) {
                html += "<tr class='normal' onmouseover='javascript: menu_mouseover(this, \"" + this.items[i].id + "\", \"" + this.id + "\");' onclick='javaScript: menu_click(\"" + this.items[i].id + "\")'>";
		html += "<td width='100%' style='cursor:pointer;' height='" + this.items[i].altoItem + "px'>";
		html += "<table width='100%' class='normal' border='0' cellspacing='0' cellpading='0'><tr>";
		html += "<td align=\"center\" valign=\"top\" " + (conImagenes ? "width='" + this.anchoImagen + "px'": "") + ">";
		if (conImagenes) {
			if (this.items[i].imagen)
				html += "<img id='" + this.items[i].id + "_img' src='" + this.items[i].imagen + "' width='" + this.anchoImagen + "' height='" + this.altoImagen + "'>";
			else
				html += "<img id='" + this.items[i].id + "_img' src='" + NO_IMAGEN + "' width='" + this.anchoImagen + "' height='" + this.altoImagen + "'>";
		}
		html +=" </td>";
		html += "<td>" + this.items[i].nombre + "</td>";
		html += "<td width='5px' align='left'>";
		if (this.items[i].items != null && this.items[i].items.length != 0)
			html += "<img src='" + MENU_DIR_FLECHA + "' border='0'>";
		html += "</td></tr></table>";
		html += "</td></tr>";
	}
	html += "</table></div>";
	
//para los menús fijos
	if (this.ubicacion) {
		this.ubicacion.innerHTML = html;
		return;
	}
	
	if (this.capa == null) {
		this.crearCapa();
		
	} else {
		this.capa.style.display = "block";
		if (this.iframe != null)
			this.iframe.style.display = "block";
	}
		
	this.capa.innerHTML = html;
	this.capa.style.left = posicion.x + 'px';
	this.capa.style.top = posicion.y + 'px';

	if (this.iframe != null) {
		this.iframe.style.left = (posicion.x + 1) + 'px';
		this.iframe.style.top = (posicion.y) + 'px';
		this.iframe.style.width = this.ancho + 'px';
		this.iframe.style.height = ((ITEM_ALTO + 1) * this.items.length) + 'px';
	}

}


function menu_obtener_xy(x, y, hijo) {
	//obtener el ancho y alto de la ventana
	var vtn = getVentana();
	var despx = 0;
	var despy = 0;
	
	if (IE) {
		despx = document.documentElement.scrollLeft + document.body.scrollLeft;
		despy = document.documentElement.scrollTop + document.body.scrollTop;
	} else {
		despx = document.body.scrollLeft;
		despy = document.body.scrollTop;
	}
	
	vtn.ancho += despx;
	vtn.alto += despy;

	//calcular x
	if (x + this.ancho > vtn.ancho) {
		if (hijo) {
			if (vtn.ancho - this.ancho >= x - this.ancho / 2)
				x = vtn.ancho - this.ancho;
			else
				x -= 2 * this.ancho;
		} else {
			x = vtn.ancho - this.ancho;
		}
	}
	
	//calcular y
	if (y + (ITEM_ALTO + 1) * this.items.length >= vtn.alto)
		y = vtn.alto - (ITEM_ALTO + 1) * this.items.length - 1;

	if (x < 0)
		x = 0;
	if (y < 0)
		y = 0;

	return {x: x, y: y};
}

function menu_ocultar() {
	if (this.capa != null)
		this.capa.style.display = "none";
	if (this.iframe != null)
		this.iframe.style.display = "none";
	if (this.ubicacion && this.tdResaltado) {
            this.tdResaltado.attributes['class'].value = 'normal';
            this.tdResaltado.childNodes[0].childNodes[0].attributes['class'].value = 'normal';
	}
	this.ocultarHijos();
}

function menu_ocultar_hijos() {
	if (this.items != null) {
		for (var i = 0; i < this.items.length; i++)
			this.items[i].ocultar();
	}
}

function menu_agregar_item(menuItem) {
	if (this.items == null) {
		this.items = new Array();
		this.accion = null;
	}
	this.items[this.items.length] = menuItem;
}

function menu_eliminar_item() {
    //alert(this.items.length);
    //alert(this.items.splice(1,0));
    if (this.items != null)
    //this.items.removeAll();
    this.items.length = 0;
    //alert(this.items.length);
}

Array.prototype.removeAll=function(){this.splice(0, this.length);}

function menu_buscar_menu(id) {
	if (this.items == null || this.items.length == 0)
		return null;
	if (this.id == id)
		return this;
	for (var i = 0; i < this.items.length; i++) {
		if (this.items[i].id == id)
			return this.items[i];
		var obj = this.items[i].buscarMenu(id);
		if (obj != null)
			return obj;
	}
}

//------------------------------FIN MENÚ ITEM----------------------------------------

//------------------------MÉTODOS DE APOYO A LOS MENÚS-------------------------------

function menu_crear_capa() {
    var parent = document.body;
    var div = null;

    if (!IE) {
        div = document.createElement('DIV');
        div.setAttribute('id', this.id);
        div.setAttribute('style', "position:absolute; width:'" + MENU_ANCHO + "px'; overflow:visible; z-index:1; visibility: visible;");
        parent.appendChild(div);

    } else {
        var srcFrame = '<iframe id="ifrm_' + this.id + '" frameborder=0 src="' + (location.protocol=='https:'?' src="/blank.html"':'') + '" style="filter:Alpha(Opacity=0);visibility:inherit;position:absolute;top:0px;left:0px;height:100%;width:100%;z-index:0;"></iframe>';
        var src = "<div id='" + this.id + "' style='position:absolute; width:'" + MENU_ANCHO + "px'; overflow:visible; z-index:1; visibility: visible;'></div>";
        parent.insertAdjacentHTML("BeforeEnd", srcFrame);
        parent.insertAdjacentHTML("BeforeEnd", src);
        div = document.getElementById(this.id);
        this.iframe = document.getElementById('ifrm_' + this.id);
    }

    this.capa = div;
    return div;	
}

function getVentana() {
    var ancho, alto;
    if (self.innerHeight) {
        ancho = self.innerWidth;
        alto = self.innerHeight;

    } else if (document.documentElement && document.documentElement.clientWidth) { // IE6 Strict
        ancho = document.documentElement.clientWidth;
        alto = document.documentElement.clientHeight;
    
    } else if (document.body.clientHeight) { // IE quirks
        ancho = document.body.clientWidth;
        alto = document.body.clientHeight;
    }
    return {ancho: ancho, alto: alto};
}

function menu_obtener_coordenadas(element) {
    var y = 0;
    var x = 0;
    while (element.offsetParent) {
        x += element.offsetLeft;
        y += element.offsetTop;
        element = element.offsetParent;
    }
    return { x:x, y:y };
}


//----------------------FIN MÉTODOS DE APOYO A LOS MENÚS------------------------------



//---------------MÉTODOS PARA EL MANEJO DE LOS EVENTOS DEL MOUSE-----------------------

var mouse_x = 0;
var mouse_y = 0;

document.oncontextmenu = new Function("return false");

document.onmousedown = menu_mousedown;
if (document.layers)
	window.captureEvents(Event.MOUSEDOWN);
	
window.onmousedown = menu_mousedown;
document.onmouseup = menu_mouseup;
document.onmousemove = menu_mousemove;

function menu_mousedown (e) {
	if (NS) {
		if (e.which == 2 || e.which == 3)
			menuContextual.mostrar(mouse_x, mouse_y);
	} else if (IE) {
		if (window.event.button == 2 || window.event.button == 3)
			menuContextual.mostrar(mouse_x, mouse_y);
	}
}

function menu_mouseup (e) {
	if (NS) {
		if (e.which == 1)
			menuPool.ocultar();
	} else if (IE) {
                if (!window || !window.event)
                    menuPool.ocultar();
		else if (window.event.button == 1)
                    menuPool.ocultar();
	}
	return true;
}

function menu_mousemove(e) {
	if (NS) {
		mouse_x = e.pageX;
		mouse_y = e.pageY;
	} else if (IE) {
	    mouse_x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
	    mouse_y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
	}
}

function menu_mouseover(obj, id, idPadre) {
	var menuItem = menuPool.buscarMenu(id);
	var menuPadre = menuPool.buscarMenu(idPadre);

        if (menuPadre.ubicacion) {
            MENU_ESTILO = menuPadre.estilo;
            menuPool.ocultarOtros(idPadre);
            menuPadre.tdResaltado = obj;
        }
	
	//quitar la selección de los nodos hermanos
	for (var i = 0; i < obj.parentNode.childNodes.length; i++) {
		var tr = obj.parentNode.childNodes[i];
		var table = tr.childNodes[0].childNodes[0];
		var img = table.childNodes[0].childNodes[0].childNodes[0].childNodes[0];
		tr.attributes['class'].value = 'normal';
		table.attributes['class'].value = 'normal';
		if (img && img.src_normal)
			img.src = img.src_normal;
    }

	//asignar la selección al nodo actual
	obj.attributes['class'].value = 'resaltado';
    obj.childNodes[0].childNodes[0].attributes['class'].value = 'resaltado';

	//mostrar la imagen de sobre
	var imgr = document.getElementById(id + "_img");
	if (imgr && menuItem.imagenSobre) {
		imgr.src_normal = imgr.src;
		imgr.src = menuItem.imagenSobre;
	}

	//ocultar los hijos del padre
	if (menuPadre != null)
		menuPadre.ocultarHijos();

	//mostrar el menu hijo si existe	
	if (menuItem.items != null && menuItem.items.length != 0) {
		var ctn = menuPadre.ubicacion ? menuPadre.ubicacion: menuPadre.capa;
		var despliegue = parseInt(ctn.offsetWidth + 1, 10);

		if (menuPadre.dirDespliegue == 'IZQUIERDA')
                    despliegue = -1 * (menuItem.ancho + 1);
                    
                var delta = menuPadre.ubicacion != null ? 0: -1;
                var p = menuPadre.obtenerCoordenadas(obj);
                //if (menuPadre.ubicacion == null) {
                    menuItem.mostrar(p.x + despliegue, p.y + delta, true);
                /*} else {
                    menuItem.mostrar(p.x + delta, p.y + obj.offsetHeight, true);
                }*/
	}
}

function menu_click(id) {
	var menuItem = menuPool.buscarMenu(id);
	if (menuItem == null || menuItem.items != null)
		return;
	if (menuItem.accion)
		menuItem.accion();
}

//-------------FIN MÉTODOS PARA EL MANEJO DE LOS EVENTOS DEL MOUSE---------------------

//-------------------------------MÉTODOS POOL MENU--------------------------

function MenuPool() {
	this.listaMenus = new Array();
	this.registrarMenu = menupool_registrar_menu;
	this.buscarMenu = menupool_buscar_menu;
	this.ocultar = menupool_ocultar_menu;
	this.ocultarOtros = menupool_ocultar_otros_menu;
}

function menupool_registrar_menu(menuItem) {
	for (var i = 0; i < this.listaMenus.length; i++) {
            if (this.listaMenus[ i ].id == menuItem.id) {
                this.listaMenus[ i ] = menuItem;
                return;
            }
	}
	this.listaMenus[ this.listaMenus.length ] = menuItem;
}

function menupool_buscar_menu(id) {
	for (var i = 0; i < this.listaMenus.length; i++) {
		var mnu = this.listaMenus[i].buscarMenu(id);
		if (mnu != null)
			return mnu;
	}
	return null;
}

function menupool_ocultar_menu() {
	for (var i = 0; i < this.listaMenus.length; i++) {
		this.listaMenus[i].ocultar();
	}
}

function menupool_ocultar_otros_menu(id) {
	for (var i = 0; i < this.listaMenus.length; i++) {
		if (this.listaMenus[i].id != id)
			this.listaMenus[i].ocultar();
	}
}

//-------------------------------FIN MÉTODO POOL MENU-----------------------


var menuPool = new MenuPool();
var menuContextual = new MenuItem("mnuRaiz", "Menu Contextual");
menuPool.registrarMenu(menuContextual);

