// ==UserScript==
// @include       https://*.wordpress.com/wp-admin/
// @include       http://*.wordpress.com/wp-admin/
// @include       https://*.wordpress.com/wp-admin/index.php
// @include       http://*.wordpress.com/wp-admin/index.php
// @require       utils.js
// ==/UserScript==

window.Unity = external.getUnityObject(1);

function isCorrectPage() {
    var i, ids = ['table table_discussion'];

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

    return true;
}

function messagingIndicatorSetup() {
    Unity.Launcher.addAction(_("New Post"),
			     makeRedirector('http://wordpress.com/#!/post/'));

    var blogName = unsafeWindow.location.toString().match(/[^\/.]+(?=\.wordpress\.com\/wp-admin\/)/)[0];
    if (!localStorage.getItem('blogNames')) {
        localStorage.setItem('blogNames', JSON.stringify([blogName]));
    } else {
        var blogs = JSON.parse(localStorage.getItem('blogNames'));
        blogs.push(blogName);
        localStorage.setItem('blogNames', JSON.stringify(blogs));
    }

    var i, blogNames = localStorage.getItem('blogNames');
    for (i = 0; i < blogNames.length; i++) {
        Unity.Launcher.addAction(blogNames[i], makeRedirector('https://' + blogNames[i] + '.wordpress.com/wp-admin/'));
    }

    var count = document.evaluate('//*[@class="table table_discussion"]/table/tbody/tr[@class="first"]/td/a/span[@class="total-count"]',
                                  document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue.textContent;

    if (localStorage.getItem('count') === null) {
        localStorage.setItem('count', count);
    } else {
        var old = Number(localStorage.getItem('count'));
        localStorage.setItem('count', count);

        if (count > old) {
            Unity.MessagingIndicator.showIndicator(_("new comments"), { count: (count - old).toString() });
        }
    }
}

if (isCorrectPage()) {
    Unity.init({ name: "WordPress",
		 domain: 'wordpress.com',
		 homepage: 'https://wordpress.com/wp-admin/',
                 iconUrl: 'icon://unity-webapps-wordpress',
                 onInit: wrapCallback(messagingIndicatorSetup) });
}

