var player;
var plst = null;
var currentItem = -1;
var previousItem = -1;

function playerReady(audio) {
	// Target the embeded player
	player = document.getElementById('audio');
	addListeners();
	getPlaylistData(0);
}

// Add ITEM listener so we can manually change tracks
function addListeners() {
	// Check that playlist is available first, otherwise wait for it to come online
	if (player.getPlaylist()) {
	    player.addControllerListener("ITEM", "itemListener");
    } else {
        setTimeout("addListeners()", 100);
    }
}

function itemListener(obj) {
    if (obj.index != currentItem) {
        previousItem = currentItem;
        currentItem = obj.index;
        getPlaylistData(currentItem);
    }
}

// Control what appears in the playlist and the "now playing" window
function getPlaylistData(theIndex) {
    plst = player.getPlaylist();

    if (plst) {
        var title = plst[theIndex].title;
        var author = plst[theIndex].author;
        var audio_title = document.getElementById("audio_title");
        audio_title.innerHTML = title;
        $("ul.songs li.current").removeClass("current");
        $("ul.songs li." + (theIndex + 1)).addClass("current");
        $("#share").show();
        // Scroll dashboard players to the current song
        if ($(".mp3-player").hasClass(".dashboard-player")) {
            $('#pane4')[0].scrollTo('.' + (theIndex + 1));
        }
    } else {
        setTimeout("getPlaylistData(" + [theIndex] + ")", 300);
    }
}

function selectSong(obj) {
    cur = obj;
    player.sendEvent("ITEM", (cur));
}

// Allow users to select song in playlist
$(document).ready(function(){
    $("ul.songs li a:not(a.dl_song, a.dl_song_again, a.deny_song)").live("click", function(){
        current = $(this).attr("class");
        cur = current - 1;
        player.sendEvent("ITEM", (cur));
        return false;
    });

    // Handle download button functionality
    $(".download a").live("click", function() {
        if ( $(this).hasClass("deny_song") ) {
            var content = '<h1>Download Limit Exceeded</h1><h3>You are allowed 3 attempts to download a song</h3><p>Please use the <a href="/support/">support page</a> to<br />contact us if you feel this is an error.</p><p>You may <a class="nyroModalClose" href="">close this window</a> to continue downloading<br />other songs.';
            $.nyroModalManual({
                minHeight: 170,
                content: content
            });
        } else {
            var id = $(this).attr("id").split("x");
            fetchSong(this, id);
        }
        return false;
    });
});