if("undefined" === typeof Ektron)
{
    var Ektron = window.Ektron = {};
}

if ("undefined" === typeof Ektron.DMSMenu)
{
    Ektron.DMSMenu =
    {
        /* Properties
        ----------------------------------*/
        dynamicContentBox: true,
        ektronControlId: "",
        menuAppPath: "",
        mouseTimeOut: 0,
        menuInitialized: false,

        /* Objects
        ----------------------------------*/
        ItemWrapper:
        {
            /* Item Wrapper Methods */
            BindToggle: function(itemWrappers)
            {
                // bind dsmItemWrapper toggle events
                itemWrappers.live("click", function()
                {
                    var isActive = $ektron(this).hasClass("dmsItemWrapperMenuActive");
                    if (isActive)
                    {
                        // deactivate this Item Wrapper and Menu
                        $(this).removeClass("dmsItemWrapperMenuActive");
                        // hide the menu
                        Ektron.DMSMenu.HideMenu();
                    }
                    else
                    {
                        // deactivate the previously active item wrapper
                        $ektron(".dmsItemWrapperMenuActive").removeClass("dmsItemWrapperMenuActive");
                        var thisWrapper = $(this);
                        // add active class to this item wrapper
                        thisWrapper.addClass("dmsItemWrapperMenuActive");
                        // get the DMS Menu for this item
                        Ektron.DMSMenu.FetchMenu(thisWrapper);
                    }
                });
            },

            Init: function(itemWrappers)
            {
                Ektron.DMSMenu.ItemWrapper.BindToggle(itemWrappers);
            }
        },

        MenuWrapper:
        {
            BindHover: function(menu)
            {
                // bind menu hover effects
                menu.hover(
                    // mouseover
                    function()
                    {
                        // kill the hide timeout caused by the mouseout on the ItemWrapper
                        clearTimeout(Ektron.DMSMenu.mouseTimeOut);

                        var itemWrapper = $ektron(".dmsItemWrapperMenuActive");
                        var dmsWrapper = itemWrapper.parent();

                        // make the ItemWrapper appear in "hover" mode
                        dmsWrapper.addClass("dmsWrapperHover");
                    },
                    // mouseout
                    function()
                    {
                        var itemWrapper = $ektron(".dmsItemWrapperMenuActive");
                        var dmsWrapper = itemWrapper.parent();

                        // remove the dmsWrapper "hover" state
                        dmsWrapper.removeClass("dmsWrapperHover");

                        // hide the Menu
                        Ektron.DMSMenu.HideMenu();

                    }
                );
            },

            FixListMenuWidth: function(menu)
            {
                var menuListItems = menu.find("li[class!=sectionBreak]");
                var sectionBreaks = menu.find("li.sectionBreak");
                var menuListItemLinks = menu.find("a");
                var menuWidth = 0;
                var version = parseInt($ektron.browser.version, 10);
                menuListItems.each(function(i)
                {
                    var thisListItem = $ektron(this);

                    var selector = "a";
                    if (version < 7)
                    {
                        selector = "span";
                    }

                    var listItemWidth = parseInt(thisListItem.find(selector).outerWidth(), 10);
                    if (menuWidth < listItemWidth)
                    {
                        menuWidth = listItemWidth;

                    }
                });
                menuListItems.css("width", menuWidth + "px");
                if (version < 7)
                {
                    sectionBreaks.css("width", (menuWidth + 8) + "px");
                    menuListItemLinks.css("width", "100%");
                }
                menu.css("width", menuWidth + "px");
            },

            Init: function(menu)
            {
                Ektron.DMSMenu.MenuWrapper.BindHover(menu);
                /*
                    the following if condition fixes a hover bug for the menu items in IE7,
                    and a width problem in IE6
                */
                if($ektron.browser.msie && parseInt($ektron.browser.version, 10) < 8)
                {
                    Ektron.DMSMenu.MenuWrapper.FixListMenuWidth(menu);
                }
            }
        },

        Wrapper:
        {
            /* Wrapper Methods */
            BindHover: function(wrappers)
            {
                // bind dmsWrapper hover effects
                wrappers.live("mouseover", function()
                {
                    // kill the hide timeout caused by the mouseout on anything else
                    var thisWrapper = $ektron(this);
                    thisWrapper.addClass("dmsWrapperHover");
                    var itemWrapper = thisWrapper.find(".dmsItemWrapper");
                    var isActive = itemWrapper.hasClass("dmsItemWrapperMenuActive");
                    if (isActive)
                    {
                        // kill any hide timeouts
                        clearTimeout(Ektron.DMSMenu.mouseTimeOut);
                        // show the menu
                        Ektron.DMSMenu.ShowMenu();
                    }
                });
                wrappers.live("mouseout", function()
                {
                    var thisWrapper = $ektron(this);
                    thisWrapper.removeClass("dmsWrapperHover");
                    var itemWrapper = thisWrapper.find(".dmsItemWrapper");
                    var isActive = itemWrapper.hasClass("dmsItemWrapperMenuActive");
                    if (isActive)
                    {
                        clearTimeout(Ektron.DMSMenu.mouseTimeOut);
                        Ektron.DMSMenu.mouseTimeOut = setTimeout(function(){
                            Ektron.DMSMenu.HideMenu();
                        }, 10);
                    }
                });
            },

            Init: function(wrappers)
            {
                Ektron.DMSMenu.Wrapper.BindHover(wrappers);
            }
        },

        WrapperLink:
        {
            BindHover: function(links)
            {
                // bind dmsWrapperLink hover effects
                links.live("mouseover", function()
                {
                    // kill the hide timeout caused by the mouseout on anything else
                    clearTimeout(Ektron.DMSMenu.mouseTimeOut);
                });
                links.live("mouseout", function()
                {
                    clearTimeout(Ektron.DMSMenu.mouseTimeOut);
                    Ektron.DMSMenu.mouseTimeOut = setTimeout(function(){
                        Ektron.DMSMenu.HideMenu();
                    }, 10);
                });
            },

            Init: function(links)
            {
                Ektron.DMSMenu.WrapperLink.BindHover(links);
            }
        },

        /* Methods
        ----------------------------------*/
        CalculateMenuPosition: function()
        {
            var menuWrapper = $ektron(".dmsMenuWrapper");
            if (menuWrapper.length > 0)
            {
                var itemWrapper = $ektron(".dmsItemWrapperMenuActive");
                var dmsWrapper = itemWrapper.parent();
                var menu = $ektron(".dmsMenuWrapper");
                var availableHeight = $ektron("body").outerHeight();
                // determine correct placement of the menu
                //var menuPosition = $ektron.positionedOffset(dmsWrapper);
                menuPosition = dmsWrapper.offset();
                var menuWrapperWidth = menuWrapper.outerWidth();
                var itemWrapperWidth = itemWrapper.outerWidth();
                /*
                    the next line is a fix for FF when the scrollbar appears and then disappears
                    (as a result of AJAX content brought into the page for example).  It forces
                    FF to recalculate the width of the itemWrappers correctly when this happens.
                */
                var bs = itemWrapper.css("width");

                if (menuWrapperWidth > itemWrapperWidth)
                {
                    // menu is wider than the wrapper, position it slightly right of the wrapper left edge
                    menuPosition.left += 20;
                }
                else
                {
                    // menu is smaller than the wrapper, position it right
                    menuPosition.left += (itemWrapperWidth - menuWrapperWidth);
                }

                if ( menuPosition.top + (dmsWrapper.outerHeight() - 1) + menu.outerHeight() > availableHeight)
                {
                    // menu would appear below the window's available space,
                    // display it above the wrapper
                    menuPosition.top = menuPosition.top - menu.outerHeight() + 1;
                }
                else
                {
                    // display the menu below the wrapper
                    menuPosition.top += (dmsWrapper.outerHeight() - 1);
                }
                menuWrapper.css({
                    "left": menuPosition.left + "px",
                    "top" : menuPosition.top + "px"
                });
            }
        },

        ConfirmDelete: function(str)
        {
            var confirmation = confirm(str);
            if (confirmation === true)
            {
                return true;
            }
            else
            {
                return false;
            }
        },

        DestroyMenu: function(leaveActive)
        {
            // remove the menu
            $ektron("ul.dmsMenuWrapper").remove();
        },

        /* This method opens Office documents in IE only */
        EditMSOfficeFile: function(checkOutUrl, fileName)
        {
            if($ektron.browser.msie)
            {
	            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
                                {
                                    var obj = null;
		                            /* if ajax call was successful, open office with document */
		                            try
                                    {
                                        obj = new ActiveXObject('SharePoint.OpenDocuments.2');
                                        obj.EditDocument2(window,fileName, '');
                                    }
                                    catch(e2)
                                    {
                                        try
                                        {
                                            obj = new ActiveXObject('SharePoint.OpenDocuments.3');
                                            obj.EditDocument3(window,fileName, '');
                                        }
                                        catch(e3)
                                        {
                                            obj = new ActiveXObject('SharePoint.OpenDocuments.1');
                                            obj.EditDocument(window,fileName, '');
                                        }
                                    }

                                    //31312 - edit in office does not work first time after install
                                    Ektron.DMSMenu.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";
		                        }
                            }
                            else
                            {
                                /* ajax request failed, attempt to peform the same action via href (non-ajax) */
		                        window.location = checkOutUrl + "&executeActiveX=true";
                            }
                    });
                    return false;
                }
                catch(e)
                {
                    //alert(e.description);
                    return true;
                }
            }
        },

        FetchMenu: function(itemWrapper)
        {
            itemWrapper.addClass("dmsItemWrapperLoading");

            // destroy any previous menus
            Ektron.DMSMenu.DestroyMenu();

            /*
                if the appropriate data attributes are present assign them to the necessary variables,
                otherwise assign empty string value.
            */
            var contentId = (itemWrapper.attr("data-ektron-dmsmenu-id")) ? itemWrapper.attr("data-ektron-dmsmenu-id") : "";
            var languageId = (itemWrapper.attr("data-ektron-dmsmenu-languageid")) ? itemWrapper.attr("data-ektron-dmsmenu-languageid") : "";
            var menuGUID = (itemWrapper.attr("data-ektron-dmsmenu-guid")) ? itemWrapper.attr("data-ektron-dmsmenu-guid") : "";
            var menuType = (itemWrapper.attr("data-ektron-dmsmenu-communitydocumentsmenu")) ? itemWrapper.attr("data-ektron-dmsmenu-communitydocumentsmenu") : "";
            var menuSubType = (itemWrapper.attr("data-ektron-dmsmenu-subtype")) ? itemWrapper.attr("data-ektron-dmsmenu-subtype") : "";

            var pageurl = window.location.href; // pass this on so that we can handle the back button properly
            var taxonomyOverrideId = 0;

            var dmsWrapper = itemWrapper.parent();
            var dmsMenuClientId = dmsWrapper.find("input[type='hidden'][class='dmsItemClientId']");
            var ieMenu = "false";

            if (dmsMenuClientId.length > 0)
            {
                // this is a control using the DMS menu, and we need that control's ClientId for AJAX responses
                dmsMenuClientId = dmsMenuClientId.val().replace(/\$/g, "_");
            }
            else
            {
                dmsMenuClientId = Ektron.DMSMenu.ektronControlId;
            }

            /* If the browser is IE, then we can create a menu specific to IE (opens Office assets directly in Office */
            /* See the methods "EditMSOfficeFile()" and ViewMSOfficeFile() below */
            if ($ektron.browser.msie)
            {
	            // Only set "ieMenu" to true if office is installed
	            /*
	               ShowMultipleUpload() tests to see if Office is installed
	               and exists in Workarea/java/determineoffice.js
	            */
	            if (typeof ShowMultipleUpload != 'undefined' && ShowMultipleUpload())
	            {ieMenu = "true";}
            }

            if (menuType !== '')
            {
                if ($ektron("#taxonomyselectedtree").length > 0)
                {
                    taxonomyOverrideId = $ektron("#taxonomyselectedtree").attr("value");
                }
            }

            // Use JQuery to fetch the menu via Ajax
            $ektron.get(Ektron.DMSMenu.menuAppPath + "DmsMenu/DmsMenu.aspx",
                {
                    contentId: contentId,
                    createIeSpecificMenu: ieMenu,
                    communityDocuments: menuType,
                    dynamicContentBox: Ektron.DMSMenu.dynamicContentBox,
                    dmsEktControlID: dmsMenuClientId,
                    dmsLanguageId: languageId,
                    taxonomyOverrideId: taxonomyOverrideId,
                    dmsMenuGuid: menuGUID,
                    dmsMenuSubtype: menuSubType,
                    fromPage: pageurl
                },
                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
			                // insert hte data returned into the page
			                $ektron("body").append(data);
			                var dmsMenuWrapper = $ektron(".dmsMenuWrapper");
			                // ensure we can get/set height/width
			                dmsMenuWrapper.css("visibility", "hidden");
			                dmsMenuWrapper.css("display", "block");
			                // apply "inherited" styling so we can get accurate measurements
			                dmsMenuWrapper.css({
			                    "font-family": (itemWrapper.css("font-family")) ? itemWrapper.css("font-family") : "inherit",
			                    "font-weight": (itemWrapper.css("font-weight")) ? itemWrapper.css("font-weight") : "inherit",
			                    "font-style": (itemWrapper.css("font-style")) ? itemWrapper.css("font-style") : "inherit",
			                    "font-variant": (itemWrapper.css("font-variant")) ? itemWrapper.css("font-variant") : "inherit"
			                });
			                Ektron.DMSMenu.MenuWrapper.Init(dmsMenuWrapper);
			                // make sure the mouse is still hovering over the wrapper before showing the menu
			                if (itemWrapper.parent().hasClass("dmsWrapperHover"))
			                {
			                    Ektron.DMSMenu.ShowMenu();
			                }
                        }
                    }
                    finally
                    {
                        itemWrapper.removeClass("dmsItemWrapperLoading");
                    }
                }
            );

        },

        ForceCheckIn: function(href, message)
        {
            var confirmation=confirm(message);
            if (confirmation)
            {
                Ektron.DMSMenu.MenuAction(href);
            }
        },

        HideMenu: function()
        {
            $ektron("ul.dmsMenuWrapper").css("visibility", "hidden");
        },

        Init: function()
        {
            /*
                This method initializes the elements of the page that are require DMS Menus.
            */
            // find the dmsWrappers in the page
            var dmsWrappers = $ektron(".dmsWrapper");
            var dmsItemWrappers = $ektron(".dmsItemWrapper");
            var dmsWrapperLinks = $ektron(".dmsViewItemAnchor");
            Ektron.DMSMenu.Wrapper.Init(dmsWrappers);
            Ektron.DMSMenu.WrapperLink.Init(dmsWrapperLinks);
            Ektron.DMSMenu.ItemWrapper.Init(dmsItemWrappers);

            // bind resize events
            $ektron(window).bind("resize", function()
            {
                setTimeout(function(){
                        Ektron.DMSMenu.CalculateMenuPosition();
                    }, 1);
            });
        },

        /*
            The following method 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
        */
        MenuAction:  function(href)
        {
            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 */
                            Ektron.DMSMenu.RefreshPage();
                        }
                        else
                        {
                            alert("failed!");
                            /* ajax request failed, attempt to peform the same action via href (non-ajax) */
	                        window.location = href;
                        }
                    }
                );
                return false;
            }
            catch(e)
            {
                //the ajax request failed, return true so that the browser attempts to perform the action via href.
                return true;
            }
        },

        ModifyImage: function(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 + '/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;
            }
        },

        RefreshPage: function()
        {
            /*
                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".
            */
	        setTimeout(function()
	        {
		        self.location.href=self.location;
	        }, 10);
        },

        /*
            This method does the same thing as MenuAction, but it opens a success/failure
            window to show indicate to the user if the request was succesfully sent or not
        */
        RequestCheckIn: function(href)
        {
            try
            {
                /* Use Jquery to execute content-state action via ajax */
                $ektron.get(href,
                    function(data, status)
                    {
                        //show response - success/failure
                        alert(data);
                    }
                );
                return false;
            }
            catch(e)
            {
                //the ajax request failed, return true so that the browser attempts to perform the action via href.
                return true;
            }
        },

        ShowMenu: function()
        {
            // makes sure the menu is positioned correctly
            Ektron.DMSMenu.CalculateMenuPosition();
            $ektron("ul.dmsMenuWrapper").css("visibility", "visible");
        },

        Sync: function(settings)
        {
            /*  possible settings parameters:
                {
                    contentLanguage: indicates the content language for this content
                    contentId: the id of the cotnent item
                    contentAssetId: the content asset id number (if applicable)
                    contentAssetVersion: the content asset version number (if applicable)
                    folderId: the parent folder id  number
                    dmsSyncPath: the full path to the dmsSync.aspx necessary when the modals are not present
                }
            */
            var s = settings;
            // check for the presence of the necessary SyncConfigModal
            if ($ektron("#ShowSyncConfigModal").length > 0)
            {
                // the modal is present, so we can do the sync in this window
                Ektron.Sync.checkMultipleConfigs(s.contentLanguage, s.contentId, s.contentAssetId, s.contentAssetVersion, s.folderId, s.isMultisite);
            }
            else
            {
                // popup a new window to perform the sync
                dmsSyncWindow = window.open(s.dmsSyncPath + '?contentLanguage=' + s.contentLanguage + '&contentId=' + s.contentId + '&contentAssetId=' + s.contentAssetId + '&contentAssetVersion=' + s.contentAssetVersion + '&folderId=' + s.folderId + '&isMultiSite=' + s.isMultisite, 'dmsSync', 'resizable=no,scrollbars=no,toolbar=no,status=no,menubar=no,location=no,height=1,width=1');
                dmsSyncWindow.focus();
            }
            //return false to prevent click through
            return false;
        },

        ViewMSOfficeFile: function(fileName)
        {
            if($ektron.browser.msie)
            {
                var obj = new ActiveXObject('SharePoint.OpenDocuments.2');
                obj.ViewDocument2(window,fileName, '');
		        return false;
            }
        }
    };
}

Ektron.ready(function()
{
    if (typeof(Sys) !== "undefined")
    {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(Ektron.DMSMenu.Init);
    }
    Ektron.DMSMenu.Init();
});
