﻿
var hasCtxMenu = false;
var hasCtxClicked = false;

var MenuUIHeader = '<table id="@@@" class="ms-MenuUI" cellspacing="0" cellpadding="0" onmouseout="DelayMouseOutRoot();"><tbody>';
var MenuUIFooter = '</tbody></table>';

var GlobalMenuArray = new Array();
var SelectedTitle = null;
var TimerArray = new Array();
var IsCloseMenu = false;
var currentParentId = null;
var LastHoveredOutElement = null;

// menus über array gelöscht
// rahmen über unselect gelöscht

// wenn ein Item mit Submenu geklickt wird
function Empty()
{
    IsCloseMenu = false;
}

function PreLoad()
{
    document.PreLoad = new Array();
    
    for (var i = 0; i < PreLoad.arguments.length; i++)
    {
        document.PreLoad[i] = new Image();
        document.PreLoad[i].src = PreLoad.arguments[i];
    }
}

function BodyOnClick()
{
    if (IsCloseMenu)
    {
        if (SelectedTitle != null)
        {
            ClearTimer();
            MouseOutRoot();
        }
    }
    
    IsCloseMenu = true;
}

function SelectTitle(divIndex)
{

    var tableObj = document.getElementById('Table' + divIndex);
    var imageObj = document.getElementById('Image' + divIndex);
    var cellObj = document.getElementById('Cell' + divIndex);
    
    if (tableObj != null)
    {
        tableObj.className = 'ms-selectedtitle';
    }
    
    if (cellObj != null)
    {
        if (IsInternetExplorer())
        {
            cellObj.style.paddingTop = '0px';
            cellObj.style.paddingBottom = '1px';
            cellObj.style.paddingLeft = '3px';
        }
        
        if (IsNetscape())
        {
            cellObj.style.paddingTop = '0px'; // 0
            cellObj.style.paddingBottom = '0px'; // 0
            cellObj.style.paddingLeft = '3px'; // 4
        }
    }
    
    if (imageObj != null)
    {
        imageObj.className = 'ms-menuimagecell';
        //imageObj.innerHTML = '<img style="width:1px" src="_layouts/images/ItisPlaceholder.gif" />&#x25BC;<img style="width:1px" src="_layouts/images/ItisPlaceholder.gif" />';
        imageObj.innerHTML = '<img src="/_layouts/images/Menu1.gif" onclick="javascript:var divObj = document.getElementById(\'' + divIndex + '\');divObj.OnClick();" />';
        
    }
            
    SelectedTitle = divIndex;
}

function UnSelectTitle()
{
    var tableObj = document.getElementById('Table' + SelectedTitle);
    var imageObj = document.getElementById('Image' + SelectedTitle);
    var cellObj = document.getElementById('Cell' + SelectedTitle);
    
    if (tableObj != null)
    {
        tableObj.className = 'ms-unselectedtitle';
    }
    
    if (cellObj != null)
    {
        if (IsInternetExplorer())
        {
            cellObj.style.paddingLeft = '4px';
            cellObj.style.paddingTop = '1px';
            cellObj.style.paddingBottom = '2px';
        }
        
        if (IsNetscape())
        {
            cellObj.style.paddingLeft = '4px';
            cellObj.style.paddingTop = '0px'; // 1
            cellObj.style.paddingBottom = '0px'; // 2
        }
    }
    
    if (imageObj != null)
    {
        imageObj.className = '';
        imageObj.innerHTML = '<img src="/_layouts/images/ItisPlaceholder.gif" />';
    }
    
    SelectedTitle = -1;
}

function ClearTimer()
{
    if (TimerArray.length > 0)
    {
        for (var i = TimerArray.length - 1; i >= 0; i--)
        {
            window.clearTimeout(TimerArray[i]);
            TimerArray.pop();
        }
    }
}

function MouseOverRoot(divIndex)
{        
    // wenn ein Menü offen ist und über ein anderes "Root" hovert
    if (GlobalMenuArray.length > 0)
    {
        // ist es das gleiche Root -> Timer abschalten
        if (SelectedTitle == divIndex)
        {
            ClearTimer();
        }
        
        // dann nix machen
        return;
    }
   
    SelectTitle(divIndex);
}


function MouseOutRoot()
{
    UnSelectTitle();
    
    if (GlobalMenuArray.length > 0)
    {	
        DeleteMenu();
    }
}


function DelayMouseOutRoot()
{
    if (GlobalMenuArray.length > 0)
    {       
        TimerArray.push(window.setTimeout('MouseOutRoot()', 3000));
    }
    else
    {
        MouseOutRoot();
    }
}


function MouseOnClick(elem, Menu, divIndex)
{ 
    if (SelectedTitle != null)
    {
        if (SelectedTitle != divIndex)
        {
            ClearTimer();
            MouseOutRoot();
        }
    }

    SelectTitle(divIndex);

    var newMenu = CreateCtxMenu(elem, Menu, divIndex); 
    ShowPopup(elem, newMenu, 'Iframe_' + newMenu);
 
    IsCloseMenu = false;
}


function CreateCtxMenu(elem, Menu, divIndex)
{

    // wenns das menü schon gibt, dann nix machen
    for (var i = 0; i < GlobalMenuArray.length; i++)
    {
        if (GlobalMenuArray[i] == elem.id + '_menu') 
        {
            return elem.id + '_menu';
        }
    }

    var objectMenu = document.createElement('div');
    objectMenu.id = elem.id + '_menu';
    
    var tempString = MenuUIHeader.replace(/@@@/g, objectMenu.id);
    
    var subMenuArrow = '';
    var icon = '';
    var onClickAction = '';
    var menuHoverAction = '';
    var cssClass = '';
    
    for (var i = 0; i < Menu.length; i++)
    {
        if (Menu[i]['Icon'].length > 1)
        {
            icon = '<img title="" height="16" alt=">" src="' + escape(Menu[i]['Icon']) + '" width="16">';
        }
        else
        {
            icon = '';
        }

        if (Menu[i]['SubmenuArrow'].length > 1)
        {
            subMenuArrow = '<img title="" height="16" alt=">" src="' + escape(Menu[i]['SubmenuArrow']) + '" width="16">';
        }
        else
        {
            subMenuArrow = '';
        }
        
        if (Menu[i]['Submenu'].length > 1)
        {
            menuHoverAction = 'HoverInMenuItem(this, ' + i + ', ' + Menu[i]['Submenu'] + ');';        
        }
        else
        {
            menuHoverAction = 'HoverInMenuItem(this, ' + i + ', null);';
        }

        // "Root"-Element ist immer "root" + _weitereBezeichnung
        var rootElement = elem.id.split('_');
        var rootElementName = rootElement[0];
        
        switch (Menu[i]['Function'][rootElementName])
        {   
            // keine Funktion
            case '':
                cssClass = 'class="ms-MenuUIItemTableCellDisabled"';
                onClickAction = 'javascript:Empty();';
                break;
                
            // hat ein SubMenü
            case '0':
                cssClass = '';
                onClickAction = 'javascript:Empty();';
                break;
        
            default:
                cssClass = '';
                                
                // wenn es ein Menü im HEAD ist (mit @ getrennt)
                if ((Menu[i]['Function'][rootElementName]).indexOf("@") > 0)
                {
                    for (var j = 0; j < document.getElementsByTagName('a').length; j++) 
                    {
                        var str = String(document.getElementsByTagName('a')[j].id)
                   
                        if (str.length > 0)
                        {                              
                            if (str.substring(str.length - (Menu[i]['Function'][rootElementName]).length, str.length) == Menu[i]['Function'][rootElementName])
                            {
                                var item = document.getElementById(str);
                                var replaceString = String(item.href).replace(/%20/g, " ");
                                //replaceString = replaceString.replace(/'/g, "\'");
                                replaceString = replaceString.replace(/"/g, "'");
                                onClickAction = 'javascript:MouseOutRoot();' + replaceString;
                            } 
                        }  
                    }  
                }
                else
                {
                    // clientseitige Script enthalten "(...)"
                    if ((Menu[i]['Function'][rootElementName]).indexOf(")") > 0)
                    {
                        onClickAction = 'javascript:MouseOutRoot();' + Menu[i]['Function'][rootElementName];
                    }
                    // 2008-04-11 für Links
                    else if ((Menu[i]['Function'][rootElementName]).indexOf("aspx") > 0 || 
                        (Menu[i]['Function'][rootElementName]).indexOf(".") > 0 || 
                        (Menu[i]['Function'][rootElementName]).indexOf("?") > 0 ||
                        (Menu[i]['Function'][rootElementName]).indexOf("=") > 0)
                    {
                        onClickAction = 'javascript:MouseOutRoot();' + Menu[i]['Function'][rootElementName];
                    }
                    else
                    {
                        for (var j = 0; j < document.getElementsByTagName('a').length; j++) 
                        {
                            var str = String(document.getElementsByTagName('a')[j].id)
                       
                            if (str.length > 0)
                            {                              
                                if (str.substring(str.length - (Menu[i]['Function'][rootElementName]).length, str.length) == Menu[i]['Function'][rootElementName])
                                {
                                    var item = document.getElementById(str);
                                    var replaceString = String(item.href).replace(/%20/g, " ");
                                    //replaceString = replaceString.replace(/'/g, "\'");
                                    replaceString = replaceString.replace(/"/g, "'");
                                    var searchResult = replaceString.match(/DELETELINE/g);
                                    
                                    if (searchResult)
                                    {
                                        //markusp 2008-01-23 show multilanguage message by deleting a line
                                        onClickAction = 'javascript:MouseOutRoot(); var ax = confirm(\'' + caption + '\'); if(ax) {' + replaceString + '};';     
                                        //onClickAction = 'javascript:MouseOutRoot(); var ax = confirm(\'Do you want to delete this record ?\'); if(ax) {' + replaceString + '};';
                                    }
                                    else
                                    {
                                        onClickAction = 'javascript:MouseOutRoot();' + replaceString;
                                    }
                                } 
                            }  
                        }
                        
                    }
                }
        }
     
        tempString += '<tr><td class="ms-MenuUIItemTableCell">'+
                    '<table id="' + objectMenu.id + '_' + i + '" onclick="' + onClickAction + '" onmouseover="' + menuHoverAction +'" onmouseout="HoverOutMenuItem(this);" class="ms-MenuUIItemTable" style="width:100%; height:100%;" cellspacing="1" cellpadding="0">'+
                    '<tbody><tr>'+
                         '<td class="ms-MenuUIIcon" nowrap align="middle">' + icon + '</td>'+
                         '<td class="ms-MenuUILabel" nowrap id="ctxItem' + i + '_' + objectMenu.id + '" style=" width: 100%">'+
                            '<div style="text-align:left;" ' + cssClass + '>'+
                                Menu[i]['Label'] + 
                            '</div>'+
                        '</td>'+
                        '<td class="ms-MenuUIAccessKey" nowrap id="ctxAccessKey' + i + '_' + objectMenu.id + '">' + Menu[i]['AccessKey'] + '</td>'+
                        '<td class="ms-MenuUISubmenuArrow" nowrap>' + subMenuArrow + '</td>'+
                    '</tr></tbody></table></td></tr>';              
    }  

    tempString += MenuUIFooter;
    
    objectMenu.innerHTML = tempString;
     
    objectMenu.style.position = 'absolute';
    objectMenu.className = 'ms-MenuUIPopupBody';
    document.body.appendChild(objectMenu);
   
    GlobalMenuArray.push(objectMenu.id);
    objectMenu.style.zIndex = '10' + String(GlobalMenuArray.length + 1);
    
	if (IsInternetExplorer())
	{	
        // Iframe erstellen
        var objectIframe = document.createElement('iframe');
        objectIframe.id = 'Iframe_' + objectMenu.id;
        objectIframe.style.display = 'block';
        objectIframe.style.zIndex = '10' + String(GlobalMenuArray.length);
        objectIframe.style.position = 'absolute';
        objectIframe.frameBorder = '0';
        document.body.appendChild(objectIframe);
 	}

    return objectMenu.id;

}


function SetHighlighting(elem)
{
    elem.className = 'ms-MenuUIItemTableHover';
    elem.cellSpacing = '0px';
    elem.childNodes[0].childNodes[0].childNodes[1].style.paddingLeft = '7px';
    elem.childNodes[0].childNodes[0].childNodes[2].style.paddingLeft = '2px';    
}

function HoverInMenuItem(elem, ctxItemIndex, SubMenu)
{
    // nicht beim ersten Mal
    if (currentParentId != null)
    {
	    if (currentParentId != elem.offsetParent.offsetParent.offsetParent.id)
        {
            // alle Highlightings im Zielmenü löschen
		    var parent = elem.offsetParent.offsetParent.offsetParent;
            
            // alle TR durchlaufen
            for (var i = 0; i < parent.childNodes[0].childNodes[0].childNodes.length; i++)
            {
                // TR - TD - Table
                DeleteHighlighting(parent.childNodes[0].childNodes[0].childNodes[i].childNodes[0].childNodes[0]);
            }
            
            // wenn es ein Submenu ist, dann das Highlighting wiederherstellen
            SetHighlighting(LastHoveredOutElement);
        }
    }


    ClearTimer();
    SetHighlighting(elem);
    
    if (SubMenu != null)
    {
        // automatisch alle Menüs außer der eigenen "Stufe" löschen
	    DeleteMenuByLevel(elem.offsetParent.offsetParent.id);
    
        var newMenu = CreateCtxMenu(elem, SubMenu, ctxItemIndex);

	    if (IsInternetExplorer())
	    {
            ShowCtxSubMenu(elem.parentElement.parentElement.parentElement.parentElement.parentElement, newMenu, 'Iframe_' + newMenu, 'ctxItem' + ctxItemIndex + '_' + elem.parentElement.parentElement.parentElement.parentElement.id);
	    }

	    if (IsNetscape())
	    {
	        ShowCtxSubMenu(elem.offsetParent.offsetParent.offsetParent, newMenu, null, 'ctxItem' + ctxItemIndex + '_' + elem.offsetParent.offsetParent.id);
    	}
	
	}
    else
    {   
        // automatisch alle Menüs bis zur eigenen "Stufe" löschen
	    DeleteMenuByLevel(elem.offsetParent.offsetParent.id);
    }

	currentParentId = elem.offsetParent.offsetParent.offsetParent.id;
}


function DeleteHighlighting(elem)
{
    elem.className = 'ms-MenuUIItemTable';
    elem.cellSpacing = '1px'; 
    elem.childNodes[0].childNodes[0].childNodes[1].style.paddingLeft = '6px';
    elem.childNodes[0].childNodes[0].childNodes[2].style.paddingLeft = '0px';
}

function HoverOutMenuItem(elem)
{
    DeleteHighlighting(elem);
    LastHoveredOutElement = elem;
}


function DeleteMenu()
{ 
    if (GlobalMenuArray.length > 0)
    { 
        for (var i = GlobalMenuArray.length - 1; i >= 0; i--)
        { 
		    if (IsInternetExplorer())
		    {
                document.body.removeChild(document.getElementById('Iframe_' + GlobalMenuArray[i]));
		    }
            document.body.removeChild(document.getElementById(GlobalMenuArray[i]));
            GlobalMenuArray.pop();
        }
    }

}

// alle Menüs außer dem übergebenen löschen
function DeleteMenuByLevel(Level)
{

    if (GlobalMenuArray.length > 0)
    {
        for (var i = GlobalMenuArray.length - 1; i >= 0; i--)
        {
            // nur löschen, wenns nicht das aktuelle Menü ist
            if (GlobalMenuArray[i] != Level)
            {
		        if (IsInternetExplorer())
		        {
                    document.body.removeChild(document.getElementById('Iframe_' + GlobalMenuArray[i]));
		        }
                document.body.removeChild(document.getElementById(GlobalMenuArray[i]));
                GlobalMenuArray.pop();
            }
            else
            {
                // wenn das aktuelle Level erreicht ist abbrechen
                break;
            }
        }
    }

}

function ShowCtxSubMenu(menuContainer, divName, ifrm, ctxItemName)
{

    var ctxItem = document.getElementById(ctxItemName)
    var divToShow = document.getElementById(divName);
    var docEl = document.documentElement;
    var docB = document.body;

    var scrollTop = (docEl.scrollTop>0)?docEl.scrollTop:docB.scrollTop;
	var scrollLeft = (docEl.scrollLeft>0)?docEl.scrollLeft:docB.scrollLeft;
	var scrollHeight = (docEl.scrollHeight>0)?docEl.scrollHeight:docB.scrollHeight;
	var scrollWidth = (docEl.scrollWidth>0)?docEl.scrollWidth:docB.scrollWidth;
	var visibleHeight = document.body.clientHeight;
	var visibleWidth = ((docEl.clientWidth>0)?docEl.clientWidth:docB.clientWidth);
	var clientWidthToUse = visibleWidth + scrollLeft;
    var clientHeightToUse = visibleHeight + scrollTop;
	var divToShowRightBorder = menuContainer.offsetWidth + menuContainer.offsetLeft + divToShow.offsetWidth;
    var optimalTop = menuContainer.offsetTop + ctxItem.offsetParent.offsetParent.offsetTop;

    if (clientWidthToUse >= divToShowRightBorder)
    {
        divToShow.style.left = menuContainer.offsetWidth + menuContainer.offsetLeft - 1;
    }
    else
    {
        divToShow.style.left = clientWidthToUse - divToShow.offsetWidth;
    }

	if (clientHeightToUse >= (optimalTop + divToShow.offsetHeight)) 
	{
		divToShow.style.top = optimalTop;
	}
	else
	{
		divToShow.style.top = clientHeightToUse - divToShow.offsetHeight;
	}

    divToShow.style.visibility = 'visible';

    if(IsInternetExplorer())        
    {
        var sfx = "px";
        var ifrmObj = document.getElementById(ifrm);
        ifrmObj.style.left = divToShow.offsetLeft + sfx;
        ifrmObj.style.top = divToShow.offsetTop + sfx;
        ifrmObj.style.width = divToShow.offsetWidth + sfx;
        ifrmObj.style.height = divToShow.offsetHeight + sfx;
        ifrmObj.style.visibility = 'visible';
    }
   
}

function ShowPopup(menuContainer, divName, ifrm)
{
    var divToShow = document.getElementById(divName);
    var docEl = document.documentElement;
    var docB = document.body;
    
    var scrollTop = (docEl.scrollTop>0)?docEl.scrollTop:docB.scrollTop;
	var scrollLeft = (docEl.scrollLeft>0)?docEl.scrollLeft:docB.scrollLeft;
	var scrollHeight = (docEl.scrollHeight>0)?docEl.scrollHeight:docB.scrollHeight;
	var scrollWidth = (docEl.scrollWidth>0)?docEl.scrollWidth:docB.scrollWidth;		
	var visibleHeight = document.body.clientHeight;
	var visibleWidth = ((docEl.clientWidth>0)?docEl.clientWidth:docB.clientWidth);
	var clientWidthToUse = visibleWidth + scrollLeft;
    var clientHeightToUse = visibleHeight + scrollTop;
	var optimalTop = menuContainer.offsetTop + menuContainer.offsetHeight;
	
	divToShow.style.left = (menuContainer.offsetWidth + menuContainer.offsetLeft) - divToShow.offsetWidth;
	
	if (IsInternetExplorer())
	{
	    divToShow.style.left = (menuContainer.offsetWidth + menuContainer.offsetLeft) - divToShow.offsetWidth + 1;
	}
	
	var lastIndex = (divToShow.style.left).lastIndexOf("px");
	var left = divToShow.style.left;
	left = left.substring(0, lastIndex);
	
	if (parseInt(left) < 0) 
	{ 
	    divToShow.style.left = 0;
	}

	if (clientHeightToUse >= (optimalTop + divToShow.offsetHeight)) 
	{
		divToShow.style.top = optimalTop;
	}
	else
	{
		divToShow.style.top = clientHeightToUse - divToShow.offsetHeight;
	}	

    divToShow.style.visibility = 'visible';

    if (IsInternetExplorer())        
    {
        var sfx = "px";
        var ifrmObj = document.getElementById(ifrm);
        ifrmObj.style.left = divToShow.offsetLeft + sfx;
        ifrmObj.style.top = divToShow.offsetTop + sfx;
        ifrmObj.style.width = divToShow.offsetWidth + sfx;
        ifrmObj.style.height = divToShow.offsetHeight + sfx;
        ifrmObj.style.visibility = 'visible';
    }

}

function IsInternetExplorer() {return (navigator.appName == 'Microsoft Internet Explorer');}
function IsNetscape() {return (navigator.appName == 'Netscape');}

