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)
    {
        cleanupListeners()

        deleteElement('issueContentIfrmContainer');
        setDisplayProperty('block');
    };

    var cleanupListeners = function()
    {
        // We need to unregister the event listeners that we've added because
        // IE throws errors if we don't (even though we delete the containing element).
        var bodyIfrm = document.getElementById('issueContentIfrm');
        var ifrmBody = bodyIfrm.contentWindow.document.body;
        var table = YAHOO.util.Dom.getElementsByClassName('jiraform', 'table', ifrmBody)[0];
        var cancelButtonEl = bodyIfrm.contentWindow.document.getElementById('cancelButton');
        if(cancelButtonEl != null)
        {
                cancelButtonEl.onclick = null;
                YAHOO.util.Event.removeListener(cancelButtonEl, 'click');
        }
        YAHOO.util.Event.removeListener(table, 'click', resizeIframe);
        YAHOO.util.Event.removeListener(table, 'resize', resizeIframe);
        YAHOO.util.Event.removeListener(window, 'resize', resizeIframe);
        YAHOO.util.Event.removeListener(bodyIfrm.contentWindow.document.forms['jiraform'], 'submit', cleanupListeners);
    }

    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 = 0;
        try
        {
            // This method seems to work better for IE and Mozilla.
            // but if there is no table element found it resorts back
            // to the normal way of finding the document height.
            var table = YAHOO.util.Dom.getElementsByClassName('jiraform', 'table', doco)[0];
            // The extra 10px are for Safari which doesn't seem to count the margins (while the
            // other browsers do.
            scrollHeight = table.offsetHeight + 20;
        }
        catch(e)
        {   }

        if(scrollHeight > 0)
        {
            return scrollHeight
        }
        else
        {
            scrollHeight = (doco.compatMode != 'CSS1Compat') ? doco.body.scrollHeight : doco.documentElement.scrollHeight;
            try
            {
                scrollHeight = scrollHeight + (doco.body.offsetHeight - doco.body.clientHeight);
            }
            catch(e)
            { // If the browser throws an error here just take the earlier value for scroll height
            }
        }
        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;
    };

    var resizeIframe = function()
    {
        document.getElementById('issueContentIfrm').style.height = getScrollHeight(document.getElementById('issueContentIfrm').contentWindow.document) + 'px';
    };


    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;

            YAHOO.util.Event.addListener(window, 'resize', resizeIframe);
            try
            {
                // This is used to resize the iframe when, for example, the user has multiple edit issue screens configured
                // Tried using the onresize event for the table in the form but it didn't work. This way is a little bit ugly
                //  but seems to work.
                var table = YAHOO.util.Dom.getElementsByClassName('jiraform', 'table', ifrmBody)[0];
                YAHOO.util.Event.addListener(table, 'click', resizeIframe);
                YAHOO.util.Event.addListener(table, 'resize', resizeIframe);
            } catch (e) {}
            try{
                var coords = YAHOO.util.Dom.getXY('issueContent');

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

                YAHOO.util.Event.addListener(bodyIfrm.contentWindow.document.forms['jiraform'], 'submit', cleanupListeners);
                resizeIframe();

                // 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";
                    }
                }
            }

            // Normal method in jiraform.jsp for setting the focus doesn't work because
            // the iframe is hidden when the method is fired so we need to set focus to
            // the first form field here.
            try { bodyIfrm.contentWindow.document.jiraform.elements[0].focus(); } catch (e) {}
        },

        // 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)
