var dmsMenuDisplayedId = -1;
var dmsMenuType = ''; // 'community', 'taxonomy', ''
var dmsDynamicContentBox = true;
var dmsEktControlID = '';
var dmsMenuAppPath = '';

/* This function is called by menu items that need to perform server-side */
/* logic, which the content page needs to refesh to see.  For example, */
/* "Check-in" executes an ajax request to check-in the content item, then */
/* needs to refresh the page to show the state of the content has changed from "O" to "I" */
function refreshPage()
{
	setTimeout(function()
		{
			self.location.href=self.location;
		}, 1000);
}

/* This fucntion is called by the onclick event of the folder item's paragraph element */
function dmsMenuShowMenu(id, languageId, menuGuid, dmsCommunityDocumentsMenu)
{   
    dmsMenuType = dmsCommunityDocumentsMenu;
    
	var dmsMenuWrapper = document.getElementById("dmsMenuWrapper" + String(id) + String(languageId) + String(menuGuid));
    
	if ((dmsMenuDisplayedId === id && dmsMenuWrapper !== null) || (dmsMenuDisplayedId !== -1))
	{
		dmsMenuDestroyMenu(id, languageId, menuGuid, true);
		if (dmsMenuDisplayedId !== -1) 
		{
			dmsMenuFetch(id, languageId, menuGuid);
		}
		dmsMenuDisplayedId = -1;
	}
	else
	{
		dmsMenuFetch(id, languageId, menuGuid);
		dmsMenuDisplayedId = String(id) + String(languageId) + String(menuGuid);
	}
}

/* This function fetches the menu from the CMS via Ajax */
function dmsMenuFetch(id, languageId, menuGuid)	
{
    /* Show the "LOADING" div while the menu is being fetched */
    var dmsLoadingMessage = document.getElementById("dmsMenuLoading");
    if (dmsLoadingMessage) { dmsLoadingMessage.style.display = "block"; }

	/* Get the menu wrapper */
    var dmsWrapper = document.getElementById("dmsWrapper" + String(id) + String(languageId) + String(menuGuid));
	
	/* If the browser is IE, then we can create a menu specific to IE (opens Office assets directly in Office */
	/* See functions "editMSOfficeFile()" and viewMSOfficeFile() below */
	var ieMenu = "false";
	if (ektjq.browser.msie)
	{
		/* Only set "ieMenu" to true if office is installed */
		/* ShowMultipleUpload() tests to see if Offic is installed and exists in Workarea/java/determineoffice.js */
		if (typeof ShowMultipleUpload != 'undefined' && ShowMultipleUpload())
		{ieMenu = "true";}
	}
	
	var taxonomyOverrideId = 0;
	if (dmsMenuType != '')
	{
	    if (document.getElementById("taxonomyselectedtree") != null) {
	        taxonomyOverrideId = document.getElementById("taxonomyselectedtree").value
	    }
	}
	
	/* Use JQuery to fetch the menu via Ajax */
    ektjq.get(dmsMenuAppPath + "DmsMenu/DmsMenu.aspx", { contentId: id, createIeSpecificMenu: ieMenu, communityDocuments:dmsMenuType, dynamicContentBox:dmsDynamicContentBox, dmsEktControlID:dmsEktControlID, dmsLanguageId:languageId, taxonomyOverrideId:taxonomyOverrideId, dmsMenuGuid: menuGuid}, 
        function(data){
            try
            {
			    //set the innerHTML of the paragraph element to the AJAX response
			    dmsWrapper.innerHTML = dmsWrapper.innerHTML + data;
			    
			    /* Get the menu wrapper */
			    var dmsItemWrapper = document.getElementById("dmsItemWrapper" + String(id) + String(languageId) + String(menuGuid));
			    dmsItemWrapper.className = "dmsItemWrapperActive";
			    dmsItemWrapper.title = "Hide Menu";
    			
    			/* Get the menu wrapper element */
    			var dmsMenuWrapper = document.getElementById("dmsMenuWrapper" + String(id) + String(languageId) + String(menuGuid));
			    /* Calculate widths to correctly position the menu */
			    var dmsMenuWidth = dmsMenuWrapper.offsetWidth;
			    var dmsItemWrapperWidth = dmsItemWrapper.offsetWidth;
			    
			    /* Determine if a border is present - if not, add 1 or 2 pixels to ensure it lines up */
			    var borderBuffer = 0;
			    var dmsItemWrapperBorder = ektj$("#dmsItemWrapper" + String(id) + String(languageId) + String(menuGuid));
		        var borderLeftWidth = dmsItemWrapperBorder.css("borderLeftWidth");
		        var borderRightWidth = dmsItemWrapperBorder.css("borderRightWidth");
			    if (ektjq.browser.msie)
			    {
			        /* if margin = "medium", then the margin is not specifically set to 1px 
			        /* this means the :hover border doesn't exist. */
			        /* Add a pixel to left margin to ensure the menu lines up */
			        if (borderLeftWidth === "medium") { borderBuffer++; }
			    }
			    {
			        if (borderLeftWidth === "0px") {borderBuffer++; }  //no left margin exists, add a pixel to left margin
			        if (borderRightWidth === "0px") {borderBuffer++; } //no right margin exists, add a pixel to left margin
			    }
			    
			    /* calculate left margin */
			    var leftMargin;
			    
			    if (dmsItemWrapperWidth < dmsMenuWidth)
			    { leftMargin = "20px"; }
			    else
			    {
			        leftMargin = (dmsItemWrapperWidth - dmsMenuWidth + borderBuffer) + "px"; 
			    }
			    
			    //show the correctly positioned menu
			    dmsMenuWrapper.style.marginLeft = leftMargin;
			    dmsMenuWrapper.style.display = "";
			    dmsMenuWrapper.style.visibility = "visible";
			}
			finally
			{
			    /* Hide loading message */	
                if (dmsLoadingMessage) { dmsLoadingMessage.style.display = "none"; }
            }
        });
}

/* This function destroys the menu object the previously selected menu */
function dmsMenuDestroyMenu(id, languageId, menuGuid, forceMenuClose)
{
    if (dmsMenuDisplayedId != (String(id) + String(languageId) + String(menuGuid)) || forceMenuClose === true)
    {
        /* Use Jquery to remove any Dms Menus */
        var activeDmsMenus = ektj$('.dmsMenuWrapper');
        for (i=0; i < activeDmsMenus.length; i++)
        {        
            ektj$(activeDmsMenus[i]).remove();
        }
        /* Use Jquery to reset any active Item Wrappers to inactive */
        var activeDmsItemWrappers = ektj$('.dmsItemWrapperActive');
        for (i=0; i < activeDmsItemWrappers.length; i++)
        {
           activeDmsItemWrappers[i].className = 'dmsItemWrapper';
           activeDmsItemWrappers[i].title = 'View Menu';
        }
        
        /* Since the menu's been destroyed, set the global var dmsMenuDisplayedId to -1 */
        dmsMenuDisplayedId = -1;
    }
}

/* This funtion opens Office documents in IE only */
function editMSOfficeFile(checkOutUrl, fileName)
{
    if(ektjq.browser.msie)
    {
        /* Show the "LOADING" div while the menu is being fetched */
        var dmsLoadingMessage = document.getElementById("dmsMenuLoading");
        if (dmsLoadingMessage) { dmsLoadingMessage.style.display = "block"; }
	    
	    try
	    {
            /* Use Jquery to execute content-state action via ajax */
            ektjq.get(checkOutUrl,
                function(data, status)
                {
                    if (status === "success")
                    {
                        /* attempt to change content state */
                        try
                        {
		                    /* if ajax call was successful, open office with document */
		                    try
                            {
                                var obj = new ActiveXObject('SharePoint.OpenDocuments.2');
                                obj.EditDocument2(window,fileName, '');
                            }
                            catch(e)
                            {
                                try
                                {
                                    obj = new ActiveXObject('SharePoint.OpenDocuments.3');
                                    obj.EditDocument3(window,fileName, '');
                                }
                                catch(e)
                                {
                                    obj = new ActiveXObject('SharePoint.OpenDocuments.1');
                                    obj.EditDocument(window,fileName, '');
                                }
                            }
		                    
                            //31312 - edit in office does not work first time after install
                            refreshPage();
                            /* prevent href from firing - ajax attempt was ok */
		                }
		                catch(e)
		                { 
		                    /* active X instantiation failed, attempt to peform the same action via href (non-ajax) */
		                    window.location = checkOutUrl + "&executeActiveX=true";
		                }
		                finally
		                {
		                    /* Hide loading message */	
                            if (dmsLoadingMessage) { dmsLoadingMessage.style.display = "none"; }
                        }
                    }
                    else
                    {
                        /* ajax request failed, attempt to peform the same action via href (non-ajax) */
		                window.location = checkOutUrl + "&executeActiveX=true";
                    }
            });
            
            //refreshPage();
            return false;
        }
        catch(e)
        {
            //alert(e.description);
            return true;
        }
    }
}

/* This funtion executes a number of menu actions - mainly for actions that require content state change. */
/* Specifically, this fucntion is called by the following menu items: */
/* Approve, CheckIn, Decline, Delete, Publish, Submit */
function dmsMenuAction(href)
{
     /* Show the "LOADING" div while the menu is being fetched */
    var dmsLoadingMessage = document.getElementById("dmsMenuLoading");
    if (dmsLoadingMessage) { dmsLoadingMessage.style.display = "block"; }
	
    try
    {
        /* Use Jquery to execute content-state action via ajax */
 ektjq.get(href,
            function(data, status)
            {
                if (status === "success")
                {
                    /* content state change succeeded, refresh page to show change in state */
                    refreshPage();
                }
                else
                {
                    /* ajax request failed, attempt to peform the same action via href (non-ajax) */
	                window.location = href;
                }
				/* Hide loading message */	
                if (dmsLoadingMessage) { dmsLoadingMessage.style.display = "none"; }
        });
        return false;
    }
    catch(e)
    {
        //the ajax request failed, return true so that the browser attempts to perform the action via href.
        return true;
    }
    finally
    {
        /* Hide loading message */	
        if (dmsLoadingMessage) { dmsLoadingMessage.style.display = "none"; }
    }
}

function viewMSOfficeFile(fileName)
{
    if(ektjq.browser.msie)
    {
        var obj = new ActiveXObject('SharePoint.OpenDocuments.2');
        obj.ViewDocument2(window,fileName, '');
		return false;
    }
}

function dmsMenuConfirmDelete(str)
{
    var confirmation = confirm(str);
    if (confirmation === true)
    {
        return true;
    }
    else
    {
        return false;
    }
}
