if (typeof ATLASSIAN == "undefined") {
    var ATLASSIAN = {};
}

if (typeof ATLASSIAN.JIRA == "undefined") {
    ATLASSIAN.JIRA = {};
}

(function() {

    // Replaces JavaScript onclick handler on edit issue forms (Because
    // the content is displayed IFRAME means standard cancel button
    // JavaScript doesn't work).
    var handleCancelEvent = function(event)
    {
        // We need to unregister the onClick event listener on the cancel button because
        // IE throws errors if we don't (even though we delete the containing element).
        var bodyIfrm = document.getElementById('issueContentIfrm');
        var cancelButtonEl = bodyIfrm.contentWindow.document.getElementById('cancelButton');
        if(cancelButtonEl != null)
        {
                cancelButtonEl.onclick = null;
                YAHOO.util.Event.removeListener(cancelButtonEl, 'click');
        }
        deleteElement('issueContentIfrmContainer');
        setDisplayProperty('block');
    };

    var addParameterToUrl = function(url, parameter)
    {
        if(url.indexOf('?') > 0)
        {
            return url + "&" + parameter;
        }
        else
        {
            return url + "?" + parameter;
        }
    }

    // Returns the actual height of the document being passed in
    var getScrollHeight = function(doco)
    {
        var scrollHeight = (doco.compatMode != 'CSS1Compat') ? doco.body.scrollHeight : doco.documentElement.scrollHeight;
        return scrollHeight;
    };

    // Handles the onclick events for decorated links. Hides issue content and displays
    // the contents of the link in a new iframe undecorated
    var switchBodyDiv = function(event)
    {
        YAHOO.util.Event.preventDefault(event);
        var issueContentElem = document.getElementById('issueContent');
        if(issueContentElem != null)
        {
            // Delete existing iframe
            deleteElement('issueContentIfrmContainer');

            // Create new iframe
            var anchor = findParentElement(YAHOO.util.Event.getTarget(event), "A");
            var url = addParameterToUrl(anchor.getAttribute("href") + "", "decorator=basic");

            var ifrmContainerDiv = document.createElement('DIV');
            ifrmContainerDiv.id = 'issueContentIfrmContainer';
            ifrmContainerDiv.innerHTML = ' <iframe id="issueContentIfrm" src="' + url +
                                                    '" scrolling="no" onload="ATLASSIAN.JIRA.issueoperations.reformatFrame()" scrolling="no" style="border:0px; width: 100%; padding: 10px; height: 0px;" frameborder="0"> </IFRAME>';

            issueContentElem.parentNode.appendChild(ifrmContainerDiv);
        }
        return false;
    };

    // Sets the style.display property for the issue content, workflow
    // actions and issue operations. Used to hide and display these elements.
    var setDisplayProperty = function(displayType)
    {

        var issueContentElem = document.getElementById('issueContent');
        issueContentElem.style.display = displayType;

        var workflowActionsMenu = document.getElementById('workflowactions');
        if(workflowActionsMenu != null)
        {
            workflowActionsMenu.style.display = displayType;
        }

        var operationsMenuList = YAHOO.util.Dom.getElementsByClassName('operations');
        for(var i = 0; i < operationsMenuList.length; ++i)
        {
            operationsMenuList[i].style.display = displayType;
        }
    };


    // Deletes a HTML element identified by the id passed in if it exists.
    var deleteElement = function(elementId)
    {
        var delElement = document.getElementById(elementId);
        if((delElement != null) && (delElement.parentNode != null))
        {
            delElement.parentNode.removeChild(delElement);
        }
    };

    // Returns the first parent of a given node with a particular type or
    //  null if there is no parent of the specified type.
    var findParentElement = function (element, parentNodeName)
    {
        while((element != null) && (element.localName != null) && (element.localName != parentNodeName)) {
            element = element.parentNode
        }
        return element;
    };

    ATLASSIAN.JIRA.issueoperations = {
        // Used to reformat the issue content iframe so that its size matches the
        // size of its contents and decorating any cancel buttons it finds in the iframe.
        reformatFrame: function()
        {
            var ifrmContainerDiv = document.getElementById('issueContentIfrmContainer');
            var bodyIfrm = document.getElementById('issueContentIfrm');
            var ifrmBody = bodyIfrm.contentWindow.document.body;

            try{
                var coords = YAHOO.util.Dom.getXY('issueContent');

                bodyIfrm.style.height = getScrollHeight(bodyIfrm.contentWindow.document) + 'px';
                ifrmBody.style.border = '0px';
                ifrmBody.style.padding = '0px 10px 0 0';
                ifrmBody.style.margin = '0px';
                bodyIfrm.contentWindow.document.forms['jiraform'].target = '_parent';

                // Hide old menus and body content
                setDisplayProperty('none');
                YAHOO.util.Dom.setXY('issueContentIfrmContainer', coords);
            }
            catch(e)
            {
                window.status = 'Error: ' + e.number + '; ' + e.description;
            }

            var cancelButtonEl = bodyIfrm.contentWindow.document.getElementById('cancelButton');
            if(cancelButtonEl != null)
            {
                // This is to get the onclick function of the cancel button to working correctly.
                // We replace the normal onclick handler with one that deletes the iframe and redisplays the old body content.
                cancelButtonEl.onclick = null;
                YAHOO.util.Event.addListener(cancelButtonEl, 'click', handleCancelEvent);
            }

            var anchors = bodyIfrm.contentWindow.document.links;
            for(var i = 0; i < anchors.length; i++)
            {
                if(anchors[i].getAttribute('rel') == 'pageReload')
                {
// Eventually we may want to use this method (i.e. load anchor in iframe instead of parent frame
// (the current method). Unfortunately IE 6 throws an error after switching between the single and
// multiple files views and then submitting the attach file form.
//                    anchors[i].href = addParameterToUrl(anchors[i].href + "", "decorator=basic");
                    if(anchors[i].target != "_parent")
                    {
                        anchors[i].target = "_parent";
                    }
                }
            }

        },

        // Decorates all links with the rel lazyLink not to work normally and to
        // invoke the switchBodyDiv function defined above onclick.
        initOperations:function()
        {
            var anchors = YAHOO.util.Dom.getElementsBy(function(anchor)
            {return ((anchor.getAttribute('rel') != null) &&
                     ((anchor.getAttribute('rel') + "").indexOf('lazyLink') >= 0) &&
                     (typeof (anchor.href) != "undefined") &&
                     (anchor.href.length > 0))}, 'a');

            YAHOO.util.Event.addListener(anchors, 'click', switchBodyDiv);
        }
    }
})();

YAHOO.util.Event.addListener(window, 'load', ATLASSIAN.JIRA.issueoperations.initOperations)
