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, menuSubtype)
{   
    dmsMenuType = dmsCommunityDocumentsMenu;

	if ((dmsMenuDisplayedId === id && $ektron(dmsWrapper).length > 0) || (dmsMenuDisplayedId !== -1))
	{
		dmsMenuDestroyMenu(id, languageId, menuGuid, true);
		if (dmsMenuDisplayedId !== -1) 
		{
			dmsMenuFetch(id, languageId, menuGuid, menuSubtype);
		}
		dmsMenuDisplayedId = -1;
	}
	else
	{
		dmsMenuFetch(id, languageId, menuGuid, menuSubtype);
		dmsMenuDisplayedId = String(id) + String(languageId) + String(menuGuid);
	}
}

/* This function fetches the menu from the CMS via Ajax */
function dmsMenuFetch(id, languageId, menuGuid, menuSubtype)	
{
    /* Show the "LOADING" div while the menu is being fetched */
    var dmsWrapperId = "#dmsWrapper" + String(id) + String(languageId) + String(menuGuid);
    var dmsWrapper = $ektron(dmsWrapperId);
    $ektron(dmsWrapperId + " p.dmsItemWrapper").addClass("dmsItemWrapperLoading");
    
    //OLD STUFF
    /*var dmsLoadingMessage = $ektron("#dmsMenuLoading");
    if (dmsLoadingMessage) { $ektron("#dmsLoadingMessage").css("display","block"); }
    */
    
	/* Get the menu wrapper */
	var dmsWrapper = $ektron("#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 ($ektron.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 ($ektron("#taxonomyselectedtree").length > 0)
	    {
	        taxonomyOverrideId = $ektron("#taxonomyselectedtree").attr("value");
	    }
	}
	
	/* Use JQuery to fetch the menu via Ajax */
    $ektron.get(dmsMenuAppPath + "DmsMenu/DmsMenu.aspx", { contentId: id, createIeSpecificMenu: ieMenu, 
            communityDocuments:dmsMenuType, dynamicContentBox:dmsDynamicContentBox, 
            dmsEktControlID:dmsEktControlID, dmsLanguageId:languageId, 
            taxonomyOverrideId:taxonomyOverrideId, dmsMenuGuid: menuGuid, dmsMenuSubtype: menuSubtype}, 
        function(data){
            try
            {
                var notLoggedInCheck = data.indexOf("-1|");
                if (notLoggedInCheck != -1)
                {
                    //user's not logged-in, alert user to log in.
                    alert(String(data).replace("-1|",""));
                }
                else
                {
                    //user's logged-in - process data
			        //set the innerHTML of the paragraph element to the AJAX response
			        /* Insert the Ajax response into the dms wrapper */
			        var dmsWrapperId = "#dmsWrapper" + String(id) + String(languageId) + String(menuGuid);
                    $ektron(data).appendTo(dmsWrapperId);
	
	                var dmsMenuWrapper = $ektron("#dmsMenuWrapper" + String(id) + String(languageId) + String(menuGuid));
	                dmsMenuWrapper.css("visibility", "hidden");
			        dmsMenuWrapper.css("display", "block");
			        
			        var dmsMenuWrapperWidth = document.getElementById("dmsMenuWrapper" + String(id) + String(languageId) + String(menuGuid)).offsetWidth;
			        var dmsItemWrapper = $ektron("#dmsItemWrapper" + String(id) + String(languageId) + String(menuGuid));
			        var dmsItemWrapperWidth = document.getElementById("dmsItemWrapper" + String(id) + String(languageId) + String(menuGuid)).offsetWidth;

                    var borderWidth=0;
                    var dmsItemWrapper = $ektron("#dmsItemWrapper" + String(id) + String(languageId) + String(menuGuid));
                    if ($ektron.browser.msie)
                    {
                        switch(dmsItemWrapper.css("border-width"))
                        {
                            case "0px":
                                borderWidth = 1;
                                break;
                            case "medium":
                                borderWidth = 2;
                                break;
                            default:
                                borderWidth = 0;
                                break
                        }
                    }
                    if ($ektron.browser.mozilla)
                    {
                        if (dmsItemWrapper.css("border-right-width") !== "0px")
                        { borderWidth = 0; }
                        else
                        { borderWidth = 2;}
                    }
                    if ($ektron.browser.safari)
                    {
                        if (dmsItemWrapper.css("border-right-width") !== "0px")
                        { borderWidth = 0; }
                        else
                        { borderWidth = 2;}
                        /* eliminate the 1px top margin to ensure menu renders flush with dmsItemWrapper */
                        dmsMenuWrapper.css("margin-top", "-2px !important");
                    } 
                    
			        if (dmsMenuWrapperWidth > dmsItemWrapperWidth)
			        { leftMargin = "20px"; }
			        else
			        { leftMargin = (dmsItemWrapperWidth - dmsMenuWrapperWidth + borderWidth) + "px"; }

                    //remove loading gif
                    $ektron(dmsWrapperId).removeClass("dmsItemWrapperLoading");
                    
                    //set <p> to active
                    $ektron(dmsItemWrapper).attr("class", "dmsItemWrapperActive");
			        $ektron(dmsItemWrapper).attr("title", "Hide Menu");
                    
			        //show the correctly positioned menu
			        $ektron(dmsMenuWrapper).css("margin-left", leftMargin);
			        $ektron(dmsMenuWrapper).css("display", "");
			        $ektron(dmsMenuWrapper).css("visibility", "visible");
			    }
			}
			finally
			{
			    /* Hide loading message */	
                $ektron("#dmsLoadingMessage").css("display","none");
            }
        });
}

/* Begin IE6-specific handling */

var dmsMenuAddIE6HoverOnRefreshCounter = 0;
var dmsMenuAddIE6HoverOnRefreshIntervalId = 0;

setTimeout(function() {
	if ($ektron.browser.msie && $ektron.browser.version < 7) {
		$ektron("div.dmsWrapper").ready(function(){
			dmsMenuAddIE6HoverOnRefreshCounter = 1;
			dmsMenuAddIE6HoverOnRefreshIntervalId = setInterval("dmsMenuAddIE6HoverOnRefresh()", 500);
		});
	}
},1000);
    
function dmsMenuAddIE6HoverOnRefresh()
{
    if (dmsMenuAddIE6HoverOnRefreshCounter < 10)
    {
        $ektron("div.dmsWrapper").hover(
            function() {
                $ektron(this).attr("class", "dmsWrapperIE6Hover");
            },
            function() {
                $ektron(this).attr("class", "dmsWrapper");
            }
        );
        dmsMenuAddIE6HoverOnRefreshCounter++;
    }
    else
    {
        clearInterval(dmsMenuAddIE6HoverOnRefreshIntervalId);
    }
}

function dmsMenuAddIE6Hover(id)
{
    setTimeout(function()
    {
        var dmsWrapper = $ektron("#" + id);
        $ektron(dmsWrapper).hover(
            function() {
                $ektron(dmsWrapper).attr("class", "dmsWrapperIE6Hover");
            },
            function() {
                $ektron(dmsWrapper).attr("class", "dmsWrapper");
            }
        );
    },1000);
}

/* End IE-specific handling */

/* 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 = $ektron('.dmsMenuWrapper');
        for (i=0; i < activeDmsMenus.length; i++)
        {        
            $ektron(activeDmsMenus[i]).remove();
        }
        /* Use Jquery to reset any active Item Wrappers to inactive */
        var activeDmsItemWrappers = $ektron('.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($ektron.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 */
            $ektron.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 */
        $ektron.get(href,
            function(data, status)
            {
                if (status === "success")
                {
                    /* content state change succeeded, refresh page to show change in state */
                    refreshPage();
                }
                else
                {
                    alert("failed!");
                    /* 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"; }
    }
}

/* This function does the same thing as dmsMenuAction, but it opens a success/failure */
/* window to show indicate to the user if the request was succesfully sent or not */
function dmsMenuRequestCheckIn(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 */
        $ektron.get(href,
            function(data, status)
            {
                //show response - success/failure
                alert(data);
				/* 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 dmsForceCheckIn(href, message)
{
    var confirmation=confirm(message);
    if (confirmation)
    {
        dmsMenuAction(href);
    }
}

function viewMSOfficeFile(fileName)
{
    if($ektron.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;
    }
}

function dmsModifyImage(href, idThumb)
{
     /* show AJAX image busy icon */
    var imgtag = document.getElementById(idThumb);
    if (imgtag == null) {
        alert('error: missing ID for thumbnail image in ekml template');
        return false; // no thumbnail so ignore command
    }
    var oldimg = imgtag.src;
    imgtag.src = dmsMenuAppPath + 'http://ymcarichmond.org/images/application/DMSMenu/dmsMenuAjaxLoading.gif';
	
    try
    {
        /* Use Jquery to execute content-state action via ajax */
        $ektron.get(href,
            function(data, status)
            {
                if (status === "success")
                {
                    // anything special to do?
                }
                else
                {
                    /* ajax request failed, attempt to peform the same action via href (non-ajax) */
	                window.location = href;
                }
				/* refresh thumbnail */	
                imgtag.src = oldimg + "?r=" + Math.random();
                // switch over view image as well
                var bigimgtag = document.getElementById(idThumb.replace(/GalleryThumb/,"PhotoGallery"));
		bigimgtag.href = bigimgtag.href + "?r=" + Math.random();	// replace preloaded image
        });
        return false;
    }
    catch(e)
    {
        imgtag.src = oldimg;
        //the ajax request failed, return true so that the browser attempts to perform the action via href.
        return true;
    }
}

if (("undefined" == typeof window.ekMenuEx_ekmenuArray)
	|| (null == window.ekMenuEx_ekmenuArray)) {
	window.ekMenuEx_ekmenuArray = new Array;
}	window.ekMenuEx_ekmenuArray[window.ekMenuEx_ekmenuArray.length] = "5c15927f_14_0";

if (("undefined" == typeof window.ekMenuEx_startupSubmenuBranchId)
	|| (null == window.ekMenuEx_startupSubmenuBranchId)) {
	window.ekMenuEx_startupSubmenuBranchId = new Array;
}	window.ekMenuEx_startupSubmenuBranchId["5c15927f"] = "";

if (("undefined" == typeof window.ekMenuEx_autoCollapseBranches)
	|| (null == window.ekMenuEx_autoCollapseBranches)) {
	window.ekMenuEx_autoCollapseBranches = new Array;
}	window.ekMenuEx_autoCollapseBranches["5c15927f"] = "true";

if (("undefined" == typeof window.ekMenuEx_startCollapsed)
	|| (null == window.ekMenuEx_startCollapsed)) {
	window.ekMenuEx_startCollapsed = new Array;
}	window.ekMenuEx_startCollapsed["5c15927f"] = "true";

if (("undefined" == typeof window.ekMenuEx_startWithRootFolderCollapsed)
	|| (null == window.ekMenuEx_startWithRootFolderCollapsed)) {
	window.ekMenuEx_startWithRootFolderCollapsed = new Array;
}	window.ekMenuEx_startWithRootFolderCollapsed["5c15927f"] = "false";

			if (("undefined" == typeof window.ekFlexMenu_ekflexmenuArray)
				|| (null == window.ekFlexMenu_ekflexmenuArray)) {
				window.ekFlexMenu_ekflexmenuArray = new Array;
			}
			window.ekFlexMenu_ekflexmenuArray[window.ekFlexMenu_ekflexmenuArray.length] = "e5a1dcbef_1730_0";
			//
			if (("undefined" == typeof window.ekFlexMenu_swRev)
			|| (null == window.ekFlexMenu_swRev)) {
			window.ekFlexMenu_swRev = new Array;
			}
			window.ekFlexMenu_swRev["e5a1dcbef"] = "7.0.0.66";
			//
			if (("undefined" == typeof window.ekFlexMenu_startupSubmenuBranchId)
			|| (null == window.ekFlexMenu_startupSubmenuBranchId)) {
			window.ekFlexMenu_startupSubmenuBranchId = new Array;
			}
			window.ekFlexMenu_startupSubmenuBranchId["e5a1dcbef"] = "";
			//
			if (("undefined" == typeof window.ekFlexMenu_autoCollapseBranches)
			|| (null == window.ekFlexMenu_autoCollapseBranches)) {
			window.ekFlexMenu_autoCollapseBranches = new Array;
			}
			window.ekFlexMenu_autoCollapseBranches["e5a1dcbef"] = "true";
			//
			if (("undefined" == typeof window.ekFlexMenu_startCollapsed)
			|| (null == window.ekFlexMenu_startCollapsed)) {
			window.ekFlexMenu_startCollapsed = new Array;
			}
			window.ekFlexMenu_startCollapsed["e5a1dcbef"] = "true";
			//
			if (("undefined" == typeof window.ekFlexMenu_startWithRootFolderCollapsed)
				|| (null == window.ekFlexMenu_startWithRootFolderCollapsed)) {
				window.ekFlexMenu_startWithRootFolderCollapsed = new Array;
			}
			window.ekFlexMenu_startWithRootFolderCollapsed["e5a1dcbef"] = "false";
			//
			if (("undefined" == typeof window.ekFlexMenu_masterControlIdHash)
				|| (null == window.ekFlexMenu_masterControlIdHash)) {
				window.ekFlexMenu_masterControlIdHash = new Array;
			}
			window.ekFlexMenu_masterControlIdHash["e5a1dcbef"] = "";
			
			//
			if (("undefined" == typeof window.ekFlexMenu_ajaxEnabled)
			|| (null == window.ekFlexMenu_ajaxEnabled)) {
			window.ekFlexMenu_ajaxEnabled = new Array;
			}
			window.ekFlexMenu_ajaxEnabled["e5a1dcbef"] = "false";
			//
			if (("undefined" == typeof window.ekFlexMenu_ajaxWSPath)
			|| (null == window.ekFlexMenu_ajaxWSPath)) {
			window.ekFlexMenu_ajaxWSPath = new Array;
			}
			window.ekFlexMenu_ajaxWSPath["e5a1dcbef"] = "/WorkArea/webservices/";
			// 
			if (("undefined" == typeof window.ekFlexMenu_displayXslt)
			|| (null == window.ekFlexMenu_displayXslt)) {
			window.ekFlexMenu_displayXslt = new Array;
			}
			window.ekFlexMenu_displayXslt["e5a1dcbef"] = "/association/../xmlfiles/Demo.xsl";
			//
			if (("undefined" == typeof window.ekFlexMenu_cacheInterval)
			|| (null == window.ekFlexMenu_cacheInterval)) {
			window.ekFlexMenu_cacheInterval = new Array;
			}
			window.ekFlexMenu_cacheInterval["e5a1dcbef"] = "600";
			//
			// Add event handler calling functions:
			//   Test to ensure that ekFlexMenu is valid/reachable (this is needed 
			//   to prevent intermittent Javascript errors that can occur if user
			//   causes event to fire while page is being torn down (i.e. a link is
			//   clicked, browser is fetching new page, movement causes mouse-out...):
			function ekFlexMenu_IsValid(obj) {
				return (("undefined" != typeof obj) && (null != obj));
			}
			function ekFlexMenuPopupMsIn(event) {
				if (ekFlexMenu_IsValid(ekFlexMenu) && ekFlexMenu_IsValid(ekFlexMenu.mouseIn)) {
					return (ekFlexMenu.mouseIn(event));
				}
				return (true);
			}
			function ekFlexMenuPopupMsOut(event) {
				if (ekFlexMenu_IsValid(ekFlexMenu) && ekFlexMenu_IsValid(ekFlexMenu.mouseOut)) {
					return (ekFlexMenu.mouseOut(event));
				}
				return (true);
			}
			function ekFlexMenuKey(event) {
				if (ekFlexMenu_IsValid(ekFlexMenu) && ekFlexMenu_IsValid(ekFlexMenu.menuBtnKeyHdlr)) {
					return (ekFlexMenu.menuBtnKeyHdlr(event));
				}
				return (true);
			}
			function ekFlexMenuMsOut(event) {
				if (ekFlexMenu_IsValid(ekFlexMenu) && ekFlexMenu_IsValid(ekFlexMenu.menuBtnMouseOutHdlr)) {
					return (ekFlexMenu.menuBtnMouseOutHdlr(event));
				}
				return (true);
			}

			function ekFlexMenuMsOvr(event) {
				if (ekFlexMenu_IsValid(ekFlexMenu) && ekFlexMenu_IsValid(ekFlexMenu.menuBtnMouseOverHdlr)) {
					return (ekFlexMenu.menuBtnMouseOverHdlr(event));
				}
				return (true);
			}
			function ekFlexMenuClk(event) {
				if (ekFlexMenu_IsValid(ekFlexMenu) && ekFlexMenu_IsValid(ekFlexMenu.menuBtnClickHdlr)) {
					return (ekFlexMenu.menuBtnClickHdlr(event));
				}
				return (true);
			}
