(function ($) {
    var loadTemplates = function(spaceKey) {
        $.getJSON(contextPath + "/plugins/dashboard/getTemplates.action?spaceKey=" + spaceKey, function(data) {
            var $spaceOptGroup = $("#spacePageTemplates").empty(),
                $globalOptGroup = $("#globalPageTemplates").empty(),
                that;

            data.spaceTemplates.length ? $spaceOptGroup.show() : $spaceOptGroup.hide();
            data.globalTemplates.length ? $globalOptGroup.show() : $globalOptGroup.hide();

            for (var i = 0, ii = data.spaceTemplates.length; i < ii; i++) {
                that = data.spaceTemplates[i];
                $("<option></option>").attr("value", that.id).text(that.name).appendTo($spaceOptGroup);
            }
            for (var i = 0, ii = data.globalTemplates.length; i < ii; i++) {
                that = data.globalTemplates[i];
                $("<option></option>").attr("value", that.id).text(that.name).appendTo($globalOptGroup);
            }
        });
    };

    var onContentsLoaded = function (shouldLoadTemplates, onInitCallbackParams, $contents) {
        var $spaceSelect = $(".space-key-selector", onInitCallbackParams.popup), oneOptionSelected = false;

        var previousSpaceSelection = getCookie("dashboard-actions-space");
        if (previousSpaceSelection) {
            $spaceSelect.val(previousSpaceSelection);

            // if cookie value does not match any space in the drop down then ensure at least one option is selected
            $spaceSelect.each(function () {
                if (this.selected) {
                    oneOptionSelected = true;
                    return false;
                }
            });
            !oneOptionSelected && ($spaceSelect[0].selectedIndex = 0);
        }
        shouldLoadTemplates && loadTemplates($spaceSelect.val());

        $(".cancel-link", onInitCallbackParams.popup).click(function (e) {
            onInitCallbackParams.hide();
            return AJS.stopEvent(e);
        });

        $(".expand-explanation-link", onInitCallbackParams.popup).click(function (e) {
            $(this).parent().siblings(".explanation").slideToggle();
            return AJS.stopEvent(e);
        });

        $spaceSelect.change(function () {
            var selectedValue = $(this).val();
            setCookie("dashboard-actions-space", selectedValue);
            shouldLoadTemplates && loadTemplates(selectedValue);
        });

        updateShadow($contents, onInitCallbackParams.popup);
    };

    var hideCallback = function () {
        $(".dashboard-actions .explanation").hide();
    };

    /**
     * Introduce variables to hold the "special" parameters object passed to the onInitCallback for the inline dialog.
     * Among other things, the object contains a reference to the hide function (which modifies the internal state of the
     * dialog on top of fading out). This is bad but I've had no choice. The current incarnation of AJS.InlineDialog
     * frustratingly does not expose this special object outside of init (in our case we need it post-initialisation).
     */
    var initCallbackParamsForPage, initCallbackParamsForBlogPost;

    var generatePopupDisplayCoordinator = function (type) {
        return function ($contents, trigger, doShowPopup) {
            $contents.html('<div style="padding: 15px 10px; text-align: center"><img style="vertical-align: middle" src="' + contextPath + '/images/icons/wait.gif"/></div>');
            doShowPopup();
            // fetch contents of div asynchronously
            $contents.load(contextPath + "/plugins/dashboard/add.action?type=" + type, function () {
                doShowPopup();
                if (type == "page") {
                    onContentsLoaded(true, initCallbackParamsForPage, $contents);
                } else {
                    onContentsLoaded(false, initCallbackParamsForBlogPost, $contents);
                }
            });
        };
    };

    // This is needed here as the dialog changes height and we need to update the
    // shadow accordingly. It was copied from AUI cause it doesn't expose this method atm.
    var updateShadow = function ($contents, popup) {
        var shadow = $("#inline-dialog-shadow");
        shadow.css({
            width: $contents.outerWidth() + 32,
            height: $contents.outerHeight() + 25
        });
        $(".b", shadow).css("width", $contents.outerWidth() - 26);
        $(".l, .r", shadow).css("height", $contents.outerHeight() - 21);

        if (AJS.$.browser.msie) {
            // iframeShim
            var iframeShim = $('#inline-dialog-shim');
            iframeShim.appendTo(popup).show();
            iframeShim.css({
                width: $contents.outerWidth(),
                height: $contents.outerHeight()
            });
        }
    };

    AJS.toInit(function ($) {
        AJS.InlineDialog($("#addPageLink"), "addPagePopup", generatePopupDisplayCoordinator("page"), {
            initCallback: function () { initCallbackParamsForPage = this; },
            hideCallback: hideCallback,
            width: 270,
            offsetY: 15,
            hideDelay: 36e5 // make it one hour, so it will not fire... soon
        });
        AJS.InlineDialog($("#addBlogLink"), "addBlogPopup", generatePopupDisplayCoordinator("blogpost"), {
            initCallback: function () { initCallbackParamsForBlogPost = this; },
            hideCallback: hideCallback,
            width: 270,
            offsetY: 15,
            hideDelay: 36e5 // make it one hour, so it will not fire... soon
        });
    });
})(AJS.$);

