
// @todo Re-evaluate need for IDs

var tryClosePause = 1500;

var bookTag = "DIV";
var menuTag = "UL";
var menuItemTag = "LI";
var menuItemLinkTag = "A";
var menuHookTag = "DIV"

var bookClassRegex = new RegExp("bea-portal-book(?:-(primary))?$");
var menuClassRegex = new RegExp("bea-portal-book(?:-(primary))?-menu$");
var hookClassRegex = new RegExp("bea-portal-book(?:-(primary))?-menu-hook$");
var itemClassRegex = new RegExp("bea-portal-book(?:-(primary))?-menu-item(?:-(active))?$");
var linkClassRegex = new RegExp("bea-portal-book(?:-(primary))?-menu-item-link$");

var rootClassRegex = new RegExp("bea-portal-book(?:-(primary))?-menu-root$");
var nestedClassRegex = new RegExp("bea-portal-book(?:-(primary))?-menu-nested$");
var books = new Array();
var currentMenuItem;

function initDynamicMenus()
{
    initBooks();
    createMenus();
}

function initBooks()
{
    var bookCandidates = document.getElementsByTagName(bookTag);
	   for (var i = 0; i < bookCandidates.length; i++)
    {
  
        if (bookCandidates[i].tagName && bookCandidates[i].tagName == bookTag
            && bookCandidates[i].className && bookCandidates[i].className.match(bookClassRegex))
        {
            var book = initBook(bookCandidates[i]);
            if (book)
            {
                books[books.length] = book;
            }
        }
    }
}

function initBook(tag)
{
    var book;
    var menuInstance = getFirstChildByClassRegex(tag, menuTag, menuClassRegex, bookClassRegex);
    var hookInstance = getFirstChildByClassRegex(tag, menuHookTag, hookClassRegex, bookClassRegex);
    if (tag && menuInstance && hookInstance)
    {
    
        var menu = initMenu(menuInstance);
        var hook = initMenuHook(hookInstance);
        if (menu && hook)
        {
            book = new Book(tag, menu, hook);
        }
    }
    return book;
}

function initMenu(tag)
{
    if (!tag)
    {
        alert("No tag defined!");
    }

    tag.style.display = "none";
    var menuItems = new Array();
    var child = tag.firstChild;

    while (child != null)
    {
    
        if (child.tagName && child.tagName == menuItemTag && child.className.match(itemClassRegex))
        {
            var itemGroups = child.className ? child.className.match(itemClassRegex) : null;
			
            if (itemGroups && itemGroups.length >= 1)
            {
                var isActive = false;

                if ((itemGroups.length == 2 && itemGroups[1] == "active")
                    || (itemGroups.length == 3 && itemGroups[2] == "active"))
                {
                    isActive = true;
                }

                menuItems[menuItems.length] = initMenuItem(child, isActive);
            }
        }

        child = child.nextSibling;
    }


    var groups = tag.className.match(menuClassRegex);
    var bookClassQualifier = (groups && groups.length >= 2 && groups[1] == "primary" ? "-primary" : "");
    return new Menu(tag, menuItems, bookClassQualifier);
}

function initMenuHook(tag)
{
    return new MenuHook(tag);
}

function initMenuItem(tag, isActive)
{
    var link;
    var menu;
    var child = tag.firstChild;

    while (child != null)
    {
        if (child.tagName && child.tagName == menuItemLinkTag && child.className.match(linkClassRegex))
        {
            var label = (child.innerText ? child.innerText : child.text);
            link = new Link(child, label);
        }
        else if (child.tagName && child.tagName == menuTag)
        {
            menu = initMenu(child);
        }

        child = child.nextSibling;
    }
    return new MenuItem(tag, link, isActive, menu);
}

function createMenus()
{
    for (var i = 0; i < books.length; i++)
    {
        createRootMenu(books[i].menu, books[i].hook, i);
    }
}

function createRootMenu(menu, hook, menuId)
{
    var menuContext = document.createElement("UL");
    menuContext.className = "bea-portal-book" + menu.bookClassQualifier + "-menu-root";
    menuContext.id = "menu-" + menuId;
    hook.tag.appendChild(menuContext);
    var itemClassName = "bea-portal-book" + menu.bookClassQualifier + "-menu-root-item";
    for (var i = 0; i < menu.menuItems.length; i++)
    {
        createMenuItem(menu.menuItems[i], menuContext, itemClassName, i, "LI", true);
        
    }
}

function createSubMenu(menu, hook, contextId)
{
    var menuContext = document.createElement("div");
    menuContext.style.display = "none";
    menuContext.className = "bea-portal-book" + menu.bookClassQualifier + "-menu-nested";
    menuContext.id = contextId + "-menu";
    hook.tag.appendChild(menuContext);
    var itemClassName = "bea-portal-book" + menu.bookClassQualifier + "-menu-nested-item";
	
    for (var i = 0; i < menu.menuItems.length; i++)
    {
 
           createMenuItem(menu.menuItems[i], menuContext, itemClassName, i, "DIV", false);
    }      
    return menuContext;
}

function createblankSubMenu(menu, hook, contextId)
{
    var menuContext = document.createElement("div");
    menuContext.style.display = "none";
    menuContext.className = "bea-portal-book"  + "-menu-nested";
    menuContext.id = contextId + "-menu";
    hook.tag.appendChild(menuContext);
    var itemClassName = "bea-portal-book" +  "-menu-nested-item";
	
   
    return menuContext;
}

function createMenuItem(menuItem, menuContext, itemClassName, itemId, tagName, isRoot)
{
    var itemContext = document.createElement(tagName);
    if (!isRoot && menuItem.menu && menuContext.id != 'menu-0-item-6-menu')  {
    	itemClassName = "bea-portal-book-primary-menu-not-nested-item";
    }

    itemContext.className = itemClassName + (menuItem.isActive ? "-active" : "");
  
    menuContext.appendChild(itemContext);
    itemContext.id = menuContext.id + "-item-" + itemId;
    
	if (menuItem.link)
    {
    	var link = document.createElement("a");
  		//link.appendChild(document.createElement("span")); 
        link.href = menuItem.link.tag.href; 
               
        var label = document.createTextNode(menuItem.link.label);
        addEventToElement(link, "mouseover", menuItemHoverIn, false);
        addEventToElement(link, "mouseout", menuItemHoverOut, false);
       
        itemContext.appendChild(link);
        link.appendChild(label);
    }

    if (menuItem.menu)
    {
    	var subMenu = createSubMenu(menuItem.menu, new MenuHook(itemContext), itemContext.id);
        itemContext.appendChild(subMenu);
    }
	
	else {var blankMenu = createblankSubMenu(menuItem.menu, new MenuHook(itemContext), itemContext.id);
 	itemContext.appendChild(blankMenu);}
}

function menuItemHoverIn(evt)
{
    var event = getEvent(evt);
    var source = getEventSource(event);
    var parent = source.parentNode;
    currentMenuItem = parent;
    parent.renderedHeight = parent.offsetHeight;
    parent.renderedWidth = parent.offsetWidth;
    closeAll(parent);
    openPath(parent);
}

function menuItemHoverOut(evt)
{
    var event = getEvent(evt);
    
    var source = getEventSource(event);
    var parent = source.parentNode;
    currentMenuItem = null;
    tryClose(parent);
}

var tmpMenuItem;
function tryClose(menuItem)
{

    if (!currentMenuItem)
    {
        tmpMenuItem = menuItem;
        setTimeout("wlp_default_close(tmpMenuItem)", tryClosePause);
    }
}

function wlp_default_close(menuItem)
{
    if (menuItem && !currentMenuItem)
    {
        closeAll(menuItem);
    }
}

function getMenuChild(parent)
{
    var child = parent.firstChild;
    var done = false;
    

    while (!done && child)
    {
        if (child && child.className && child.className.match(nestedClassRegex))
        {
            done = true;

        }
        else
        {
            child = child.nextSibling;
           
        }
        
    }

    return child;
}

function openPath(menuItem)
{
    var path = new Array();
    var childMenu = getMenuChild(menuItem);
   

    if (childMenu)
    {
        path[path.length] = new Array();
        path[path.length - 1][0] = menuItem;
        path[path.length - 1][1] = childMenu;
    }

    var menu = menuItem.parentNode;

    while (menu && !menu.className.match(rootClassRegex))
    {
        menuItem = menu.parentNode;
        path[path.length] = new Array();
        path[path.length - 1][0] = menuItem;
        path[path.length - 1][1] = menu;
        menu = menuItem.parentNode;
    }

    for (var i = 0; i < path.length; i++)
    {
        openMenu(path[i][0], path[i][1], path.length - 1 - i);
    }
}

function openMenu(menuItem, menu, depth)
{
    var width = (menuItem.offsetWidth == 0 ? menuItem.renderedWidth : menuItem.offsetWidth);
    var pos = (depth == 0 ? 1 : getMenuItemPosition(menuItem));
    var height = (menuItem.offsetHeight == 0 ? menuItem.renderedHeight : menuItem.offsetHeight);
    
    var coords = (depth == 0 ? getDocumentOffset(menuItem) : [menuItem.offsetLeft, menuItem.offsetTop]);
   
    menu.style.position = "absolute";
    menu.style.display = "block";
    menu.style.left = coords[0] + (depth == 0 ? 0 : width) + "px";
    //Modified by Venkata Sarvabatla for Defect #324  
    if(navigator.appName=="Microsoft Internet Explorer"){
    	menu.style.top = coords[1] + (pos * height) + "px";
    }else{
    	menu.style.top = coords[1] + (pos * height) + "px";
    }
    //Modifications end for Defect #324
    
    openShim(menu,menuItem); 
}

function getDocumentOffset(object)
{
    var coords = new Array();
    coords[0] = object.offsetLeft;
    //Modified by Venkata Sarvabatla for Defect #324  
    if(navigator.appName=="Microsoft Internet Explorer"){
     coords[1] = object.offsetTop;
    }
	//Modifications end for Defect #324
    while((object = object.offsetParent) != null)
    {
        coords[0] += object.offsetLeft;
        //coords[1] += object.offsetTop;
        
        if(navigator.appName=="Microsoft Internet Explorer"){
     		coords[1] += object.offsetTop;
    	}
    	/*else{
     	//coords[1] = 23;
     		//alert(object.getNodeName());
     		//alert(object.nodeName);
     		if(object.nodeName != 'BODY' && object.nodeName != 'TABLE')
     			coords[1] += object.clientHeight;
     		//alert(coords[1]);
	    }
	    */
        
    }

    return coords;
}

function getMenuItemPosition(menuItem)
{
    var pos = 0;
    var parentMenu = menuItem.parentNode;
    var childMenuItem = parentMenu.firstChild;
    var hit = false;

    while (childMenuItem)
    {
        if (childMenuItem == menuItem)
        {
            hit = true;
            break;
        }

        pos++; 
        
        childMenuItem = childMenuItem.nextSibling;
    }

    if (!hit)
    {
        alert("Parent menu does not contain child menu item!");
    }

    return pos;
}

// @review Consider a closeAllBut(menuItem) that closes everything in the path above the menuItem for Mozilla
function closeAll(menuItem)
{
	var rootMenu = menuItem.parentNode;
    //Modified by Venkata Sarvabatla for Defect #324
    //if(navigator.appName=="Microsoft Internet Explorer"){
	    while (rootMenu && !rootMenu.className.match(rootClassRegex))
	   {
	     rootMenu = rootMenu.parentNode.parentNode;
	   }
     //}
     
     //Modifications end for Defect #324
    closeAllChildren(rootMenu);
}

function closeAllChildren(menu)
{
    var child = menu.firstChild;
	while (child)
    {
        var subMenu = getMenuChild(child);
        if (subMenu)
        {
            closeAllChildren(subMenu);
            subMenu.style.display = "none";
            closeShim(subMenu); 
        }

       child = child.nextSibling;
    }
}

function Book(tag, menu, hook)
{
    this.tag = tag;
    this.menu = menu;
    this.hook = hook;
}

function Menu(tag, menuItems, bookClassQualifier)
{
    this.tag = tag;
    this.menuItems = menuItems;
    this.bookClassQualifier = bookClassQualifier;
}

function MenuHook(tag)
{
    this.tag = tag;
}

function MenuItem(tag, link, isActive, menu)
{
    this.tag = tag;
    this.link = link;
    this.isActive = isActive;
    this.menu = menu;
}

function Link(tag, label)
{
    this.tag = tag;
    this.label = label;
}

//Fix for drop down issue

//Opens a shim, if no shim exists for the menu, one is created
function openShim(menu,menuItem)
{

    if (menu==null) return;
    var shim = getShim(menu);
    if (shim==null) shim = createMenuShim(menu,getShimId(menu));
    
    //Change menu zIndex so shim can work with it
    menu.style.zIndex = 100;
    
    var width = (menu.offsetWidth == 0 ? menuItem.renderedWidth : menu.offsetWidth);
    var height;
    
    if (menu.offsetHeight == 0)
    {
        var menus = getMenuItemCount(menu);
        height = menuItem.renderedHeight * menus;
    }
    else
    {
        var height = menu.offsetHeight;
    }
    
    shim.style.width = width;
    shim.style.height = height;
    shim.style.top = menu.style.top;
    shim.style.left = menu.style.left;
    shim.style.zIndex = menu.style.zIndex - 1;
    
    shim.style.position = "absolute";
    shim.style.display = "block";
}

//Closes the shim associated with the menu
function closeShim(menu)
{
    if (menu==null) return;
    var shim = getShim(menu);
    if (shim!=null) shim.style.display = "none";
}

//Creates a new shim for the menu
function createMenuShim(menu)
{
    if (menu==null) return null;

    //var shim = document.createElement("<div scrolling='no' frameborder='5'"+
    //                                  "style='position:absolute; top:0px;"+
    //                                  "left:0px; display:none'></div>"); 
    var shim = document.createElement("div");
    shim.name = getShimId(menu);
    shim.id = getShimId(menu);
    //Unremark this line if you need your menus to be transparent for some reason
    //shim.style.filter="progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";

    if (menu.offsetParent==null || menu.offsetParent.id=="") 
    {
        window.document.body.appendChild(shim);
    }
    else 
    {
        menu.offsetParent.appendChild(shim); 
    }
    return shim;
}

//Creates an id for the shim based on the menu id
function getShimId(menu)
{
    if (menu.id==null) return "__shim";
    return "__shim"+menu.id;
}

//Returns the shim for a specific menu
function getShim(menu)
{
    return document.getElementById(getShimId(menu));
}

function getMenuItemCount(menu)
{
    var count = 0;
    var child = menu.firstChild;

    while (child)
    {
        if (child.nodeName=="DIV") count = count + 1;
        child = child.nextSibling;
    }
    return count;    
}


function printPortlet(appPath)
{
   var pageString = appPath+'/print/printPage.faces';
   var printWindow = window.open(pageString, 'PrintPage', "toolbar=no,location=no,scrollbars=yes,resizable,width=800,height=650'");
   //printWindow.setTimeout("modifyPrint()",1000);
   printWindow.focus();
}

function modifyPrint(){
    var srcDocument =  self.opener.document.getElementById('printBodyID').cloneNode(true);
    //Convert Links to normal text.
    var links = srcDocument.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
     	var linkNode = links[i];
      	linkNode.removeAttribute("href");
     	linkNode.removeAttribute("onclick");
    	linkNode.removeAttribute("title");
   		linkNode.setAttribute("class","nolink");
   }
    //Remove alt from images.
    var images = srcDocument.getElementsByTagName("img");
    for (var i = 0; i < images.length; i++) {
     	var theimg = images[i];
   		theimg.removeAttribute("alt");
    }
	
    //Remove link from span.
    var allspans = srcDocument.getElementsByTagName("span");
    for (var i = 0; i < allspans.length; i++) {
     	var spanNode = allspans[i];
     	if(spanNode.getAttribute("onclick")){
	     	spanNode.setAttribute("onmouseover","none");
	     	spanNode.removeAttribute("onmouseover");
	     	spanNode.removeAttribute("onmouseout");
	     	spanNode.removeAttribute("onclick");
	    	spanNode.removeAttribute("title");
	    	var theStyle = spanNode.getAttribute("style");
	    	if(theStyle){
	    		theStyle = theStyle.toString();
	    		var newStyle = theStyle.replace("pointer","auto");
		     	spanNode.setAttribute("style",newStyle);
	    	}
    	}
    }
	
	
	
   document.getElementById('portletHtml').innerHTML =   srcDocument.innerHTML;
   window.print();
}

function showPrintEmailIcons(){
	var printDiv = document.getElementById('printBodyID');
	if( document.getElementById('printBodyID') != null){
			if(document.getElementById('idPrintEmail'))
				document.getElementById('idPrintEmail').style.display='block';
			if(document.getElementById('idPrint'))
				document.getElementById('idPrint').style.display='block';
			if(document.getElementById('idEmail'))
				document.getElementById('idEmail').style.display='block';
	}
}

function showPrintIconsOnly(){
	var printDiv = document.getElementById('printBodyID');
	if( document.getElementById('printBodyID') != null){
			if(document.getElementById('idPrintEmail'))
				document.getElementById('idPrintEmail').style.display='block';
			if(document.getElementById('idPrint'))
				document.getElementById('idPrint').style.display='block';
	}
}
