//Override the function in atlassian gadgets to do nothing. Currently we have no chrome so titles on gadgets make no sense
gadgets.IfrGadgetService.prototype.setTitle = function() { }

// Determines whether we're running in an iframe.
if (window.top.AJS && window.top != window.self)
{
    window.top.AJS.log("Running within a frame/iframe/object.");

    if (window.top.AJS.MacroBrowser)
    {
        window.top.AJS.log("Macro browser is present. So we're in a preview iframe from macro browser.");

        var mb = window.top.AJS.MacroBrowser;

        mb.gadgetPrefs = {};

        mb.gadgetPrefsChanged = false;
        gadgets.IfrGadgetService.prototype.setUserPref = function(editToken, name, value)
        {
            mb.gadgetPrefs[name] = value;
            mb.gadgetPrefsChanged = true;
            if(name == "isConfigured") {
                var warningSpan = window.top.AJS.$("#save-warning-span");
                if(warningSpan[0]) {
                    warningSpan.removeClass("gadget-not-configured-warning").addClass("hidden");
                    var okButton = window.top.AJS.$("#macro-browser-dialog .dialog-button-panel .ok");
                    okButton.attr("disabled","")
                }
            }

            mb.Macros["gadget"].manipulateMarkup();
        };
    }
    else
    {
        window.top.AJS.log("Not running within macro browser.");
    }
}
else
{
    AJS.log("Not running within a frame/iframe/object, presumably in normal page rendering...");
}

/**
 * Runs on every page and manages all the gadgets on that page.
 */

/* TODO BN 1.1.4: AJS-514 - Temporary utility until its available in AUI */
AJS.parseUri = function (uri, strict) {
    var unesc = window.decodeURIComponent || unescape;
    var esc = window.encodeURIComponent || escape;

    function parseUri (str) {
        var	o   = parseUri.options,
            m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
            uri = {},
            i   = 14;

        while (i--) uri[o.key[i]] = m[i] || "";

        uri[o.q.name] = {};
        uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
            if ($1) uri[o.q.name][unesc($1)] = unesc($2);
        });

        return uri;
    }

    parseUri.options = {
        strictMode: !!strict,
        key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
        q:   {
            name:   "queryKey",
            parser: /(?:^|&)([^&=]*)=?([^&]*)/g
        },
        parser: {
            strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
            loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
        }
    };

    uri = parseUri(uri);

    uri.toString = function () {
        var params = [];
        AJS.$.each(uri.queryKey, function (name, value) {
            params.push(esc(name) + "=" + esc(value));
        });

        return uri.protocol + "://" + uri.authority + uri.path + "?" + params.join("&") + "#" + uri.anchor;
    };

    return uri;
};

AJS.toInit(function ($) {
    function updateSecurityTokens() {
        var gadgetFrames = new Array(),
            updateTokenParams = {};

        AJS.log("Updating gadget security tokens");

        $(".gadget").each(function (index) {
            var t = $(this);
            var uri = AJS.parseUri(t.attr("src"));
            var securityToken = uri.queryKey["st"];
            var rpcToken = /rpctoken=([0-9]*)/.exec(uri.anchor)[1];
            var iframeId = t.attr("id");

            gadgetFrames.push(iframeId);

            gadgets.rpc.setAuthToken(iframeId, rpcToken);
            updateTokenParams["st." + index] = securityToken;
        });

        AJS.$.ajax({
            type: "POST",
            url: AJS.Meta.get("context-path") + "/plugins/servlet/gadgets/security-tokens",
            data: updateTokenParams,
            dataType: "json",
            success: function(newSecurityTokens) {
                AJS.$.each(gadgetFrames, function(index) {
                    try {
                        gadgets.rpc.call(this, "update_security_token", null, newSecurityTokens["st." + index]);
                    } catch (e) {
                        AJS.log(e);
                        AJS.log("Unable to update the security token for gadget with iframe id " +
                                this + ".  This likely means that the gadget does not use the " +
                                "'auth-refresh' feature.  If the gadget uses gadgets.io.makeRequest after its" +
                                "initial startup, it is a good idea to use the 'auth-refresh' feature " +
                                "by adding <Optional feature='auth-refresh' /> to your gadget's " +
                                "<ModulePrefs> section.  Otherwise, the gadget's security token could expire" +
                                " and subsequent calls to gadgets.io.makeRequest will fail.");
                    }
                });
                AJS.log("Tokens updated");
            },
            error: function(request, textStatus, errorThrown) {
                if (request.status != 200) {
                    AJS.log("Failed to get new security tokens. Response was had a status of '" +
                            request.status + "' saying '" + request.statusText + "'");
                } else {
                    AJS.log("There was an error processing the response. Error was '" +
                            textStatus + "'");
                }
            }
        });
    }

    var securityTokenRefreshRate = AJS.parseUri(document.location.href).queryKey["__st_refresh"] || 1000*60*12;
    AJS.log("Security tokens will be refreshed every " + securityTokenRefreshRate + "ms");
    window.setInterval(updateSecurityTokens, securityTokenRefreshRate);
});

