// ==UserScript==
// @include       http://www.linkedin.com/*
// @include       http://www.linkedin.com
// @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 isCorrectPage() {
    var i, ids = ['header'];

    for (i = 0; i < ids.length; i++) {
        if (!document.getElementById(ids[i])) {
            return false;
        }
    }

    return true;
}

function doMatrixIntegration() {
    function integrateSubMenu(parent) {
        var i, snapshot = document.evaluate('ul/li/a',
                                            parent, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
        for (i = 0; i < snapshot.snapshotLength; i++) {
            var node = snapshot.snapshotItem(i);
            var text = node.textContent;
            var link = node.href;
            console.log(text);
            Unity.addAction('/' + text, makeRedirector(link));
        }
    }
    var i, snapshot = document.evaluate('//div[@id="header"]/div[2]/div/ul/li',
                                        document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);

    for (i = 0; i < snapshot.snapshotLength; i++) {
        var node = snapshot.snapshotItem(i);
        var text = trim(node.getElementsByTagName('a')[0].textContent);
        var link = node.getElementsByTagName('a')[0].href;

        console.log(text);
        Unity.addAction('/' + text, makeRedirector(link));
        integrateSubMenu(node);
    }
}

function messagingIndicatorSetup() {
    function checkMessagesCount() {
        var count = document.getElementById('header-messages-count');

        if (count) {
            count = count.textContent.match(/\d+/)[0];
        } else {
            count = '0';
        }
        return [{ name: _("Inbox"),
                  count: count,
                  callback: makeRedirector('http://www.linkedin.com/inbox/messages/received?trk=hb_tab_inbox_top') }];
    }
    var indicatorsController = new Indicators(checkMessagesCount);

    Unity.Launcher.addAction(_("Compose New Message"),
                             makeRedirector("http://www.linkedin.com/msgToConns?displayCreate="));

    doMatrixIntegration();

    //selfTest(); TODO define selfTest and re-enable this later.
}

if (isCorrectPage()) {
    Unity.init({ name: 'LinkedIn',
                 domain: 'linkedin.com',
                 homepage: 'http://www.linkedin.com',
                 iconUrl: 'icon://unity-webapps-linkedin',
                 onInit: wrapCallback(messagingIndicatorSetup) });
}
