// ==UserScript==
// @include       http://grooveshark.com/*
// @include       http://grooveshark.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 getTrackInfo() {
    var artist = null;
    var title = document.title;
    var artLocation = null;
    var album = null;
    try {
        artist = document.evaluate('//div[contains(@class, "queue-item-active")]/div[@class="queue-item-content"]/div/a[@class="queue-song-artist artist ellipsis"]', document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue.textContent;
        title = document.evaluate('//div[contains(@class, "queue-item-active")]/div[@class="queue-item-content"]/div/a[@class="queue-song-name song song-link ellipsis"]', document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue.textContent;
        album = document.getElementsByClassName('now-playing-link album')[0].textContent;
        artLocation = document.evaluate('//div[@class="img-container"]/img[@id="now-playing-image"]', document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue.src;
    } catch (x) {}

    if (!artLocation) {
        return null;
    }

    return {
        title: title,
        album: album,
        artist: artist,
        artLocation: artLocation
    };
}

function musicPlayerSetup() {
    Unity.MediaPlayer.init("Grooveshark");

    setInterval(wrapCallback(function retry() {
        var trackInfo = getTrackInfo();

        if (!trackInfo) {
            return;
        }

        var paused = document.getElementById('play-pause').className.match(/paused$/);
        if (null !== paused) {
            Unity.MediaPlayer.setPlaybackState(Unity.MediaPlayer.PlaybackState.PAUSED);
        } else {
            Unity.MediaPlayer.setPlaybackState(Unity.MediaPlayer.PlaybackState.PLAYING);
        }
        Unity.MediaPlayer.setTrack(trackInfo);
    }), 1000);

    Unity.MediaPlayer.onPlayPause(wrapCallback(function () {
        launchClickEvent(document.getElementById('play-pause'));
    }));

    Unity.MediaPlayer.onNext(wrapCallback(function () {
        document.getElementById('play-next').click();
    }));

    Unity.MediaPlayer.onPrevious(wrapCallback(function () {
        document.getElementById('play-prev').click();
    }));
}

Unity.init({ name: "grooveshark",
             domain: 'grooveshark.com',
             homepage: 'http://grooveshark.com',
             iconUrl: "icon://unity-webapps-grooveshark",
             onInit: wrapCallback(musicPlayerSetup) });
