// ==UserScript==
// @include       http://*.live.com/*
// @include       https://*.live.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 isOutlook() {
    return document.getElementById('inboxControl0f') !== null;
}

function getOutlookInboxCountNode() {
    return document.evaluate('//*[@id="inboxControl0f"]//*[contains(@title, "Inbox")]', document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue;
}

function getOutlookInboxCount() {
    var node = getOutlookInboxCountNode();
    var match = node.title.match(/.*\s+(\d*)/);
    if (match === null) {
        return '0';
    }
    return match[1];
}

function getHotmailInboxCountNode() {
    return document.getElementById('c_murc');
}

function getHotmailMessagesCountNode() {
    return document.getElementById('c_mocc');
}

function getMailDataForPage() {
    var inboxCount = '0';
    var messageCount = '0';

    try {
        if (isOutlook()) {
            inboxCount = getOutlookInboxCount();
        } else {
            inboxCount = getHotmailInboxCountNode().textContent.match(/\d+/)[0];
            messageCount = getHotmailMessagesCountNode().textContent.match(/\d+/)[0];
        }
    } catch (x) {}

    return {
        inbox: inboxCount,
        messages: messageCount
    };
}

function listenToChanges(handler) {
    if (isOutlook()) {
        getOutlookInboxCountNode().addEventListener('DOMSubtreeModified', handler, false);
    } else {
        getHotmailInboxCountNode().addEventListener('DOMSubtreeModified', handler, false);
        getHotmailMessagesCountNode().addEventListener('DOMSubtreeModified', handler, false);
    }
}

function isCorrectPage() {
    if (isOutlook()) {
        return getOutlookInboxCountNode() !== null;
    }

    // fall back on hotmail
    return getHotmailMessagesCountNode() && getHotmailInboxCountNode();
}

function messagingIndicatorSetup() {
    var checkMessagesCount = wrapCallback(function () {
        var d = getMailDataForPage();
        Unity.MessagingIndicator.showIndicator("Inbox", { count: d.inbox });
        if (!isOutlook()) {
            Unity.MessagingIndicator.showIndicator("Messenger", { count: d.messages });
        }
    });

    checkMessagesCount();

    listenToChanges(checkMessagesCount);
}

setTimeout(function self() {
    if (!isCorrectPage()) {
        setTimeout(self, 1000);
        return;
    }

    Unity.init({ name: "LiveMail",
                 domain: 'mail.live.com',
                 homepage: 'http://mail.live.com',
                 iconUrl: "icon://unity-webapps-outlook",
                 onInit: wrapCallback(messagingIndicatorSetup) });
}, 1000);
