// ==UserScript==
// @include        https://*.launchpad.net/*
// @include        https://launchpad.net/*
// @require        utils.js
// ==/UserScript==

// This placeholder gets munged with real data at build time.
var WebappsGettextDict = JSON.parse(unescape(
    "%7B%22GETTEXT%22%3A%22PLACEHOLDER%22%7D"
));

window.Unity = external.getUnityObject(1);

function addProjectMenu() {
    var watermark = document.getElementById("watermark");
    if (!watermark) {
        return;
    }
    var menu = watermark.getElementsByClassName("facetmenu")[0], i, child, menuSpan;

    var prefix = "/Project/";
    for (i = 0; i < menu.children.length; i++) {
        child = menu.children[i];
        menuSpan = child.children[0];
        Unity.addAction(prefix + menuSpan.textContent, makeRedirector(menuSpan));
    }
}

function integratePortlet(portlet) {
    var links = portlet.getElementsByTagName("a"), menuElement, i;
    for (i = 0; i < links.length; i++) {
        menuElement = links[i];
        Unity.addAction("/" + menuElement.textContent, makeRedirector(menuElement));
    }
}

function addGlobalActions() {
    var portlets = document.getElementsByClassName("portlet"), portlet, menuElement, i;
    for (i = 0; i < portlets.length; i++) {
        integratePortlet(portlets[i]);
    }
}

function addBugs() {
    var bugs = document.getElementsByClassName("bugtitle"), bug, i;
    var prefix = "/Bugs/";
    for (i = 0; i < bugs.length; i++) {
        bug = bugs[i];
        Unity.addAction(prefix + bug.textContent,
                        makeRedirector(bug.href));
    }
}

function addActions() {
    addProjectMenu();
    addBugs();
    addGlobalActions();
}

function unityLoaded() {
    var uri = window.location.toString();

    try {
        var title = uri.match(/^https:\/\/[^\/]+\/[^\/]+\/?/i)[0]
            .match('\/[^/]+\/?$')[0].match(/[^\/]+/)[0];

        var link = 'https://launchpad.net/' + title;
        linkVisited(link, title);
    } catch (x) {
        linkVisited();
    }
    addActions();
}

Unity.init({ name: 'Launchpad',
             domain: 'launchpad.net',
             homepage: 'https://launchpad.net/',
             iconUrl: 'icon://unity-webapps-launchpad',
             onInit: wrapCallback(unityLoaded) });
