// ==UserScript==
// @include       http://plus.google.com/*
// @include       https://plus.google.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 getAppNameNode() {
    return document.evaluate('//div[@id="contentPane"]/div/nav/div/div/div[3]',
                             document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue;
}

function isCorrectPage() {
    if (!document.getElementById('contentPane')) {
        return false;
    }
    return true;
}

function getImg(appName) {
    var params = "numNotificationsToFetch=20&sp=%5B9%2C2%2Cnull%2Cnull%2Cnull%2C20%2Cnull%2Cnull%2C%5B%5D%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2C%5B%5D%5D&hl=en&at=AObGSAjzAjXMPD4pE9JoHEDsiL82mpcUkw%3A1337256020000&";
    var request = new XMLHttpRequest();

    request.onreadystatechange = wrapCallback(function () {
        if (request.readyState === 4) {
            var text = request.responseText;
            var pos = text.indexOf(appName);
            while (text[pos] !== '[' && pos > 0) {
                pos--;
            }
            var startPos = pos;
            pos++;
            var depth;
            for (depth = 1; depth && pos < text.length; pos++) {
                if (text[pos] === '[') {
                    depth++;
                }
                if (text[pos] === ']') {
                    depth--;
                }
            }
            var desc = text.substr(startPos, pos - startPos);

            pos = desc.indexOf(',');
            while (desc.indexOf(',', pos + 1) !== -1) {
                pos = desc.indexOf(',', pos + 1);
            }

            var img = desc.substr(pos + 2);
            img = img.substr(0, img.length - 2);
            if (img.indexOf('https://') !== -1) {
                img = 'http://' + img.substr('https://'.length);
            }

            Unity.toDataURL(img, function (aResult, uri) {
                Unity.init({ name: appName,
                             iconUrl: uri,
                             domain: 'plus.google.com',
                             homepage: String(window.location),
                             onInit: null });
            });
        }
    });
    request.open("POST", "https://plus.google.com/_/games/getGamesModel?_reqid=3432&rt=j", true);

    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-length", params.length);
    request.setRequestHeader("Connection", "close");

    request.send(params);
}


if (isCorrectPage()) {
    setInterval(wrapCallback(function wait() {
        // It's change location without reloading page
        if (!getAppNameNode() || !getAppNameNode().textContent.length) {
            return;
        }
        var appName = getAppNameNode().textContent;

        if (!localStorage.getItem(appName)) {
            getImg(appName);
            localStorage.setItem(appName, true);
        }
    }), 2000);
}
