﻿// global playlist array this essentially keeps track of whats currently being played
var playlist = new Array();
// the position within the playlist
var currentMediaId = 0;
// Variable for the interval id. this continuously retrieves the progress within the file
var idI;
// Variable for the interval thread id, for monitoring of playstate changes
var playsStateiDl;
// Various states of the windows media player, along with a string representation
var playstateValues = new Array("Undefined", "Stopped...", "Paused...", "Playing...", "Scan Forward", "Scan Reverse", "Buffering...", "Waiting", "Media Ended", "Loading...", $get("Ready"), "Reconnecting");

var timer = null;
var bufferTimer = null;
var playing = false;
var stopped = false;
var previousId = null;

var userId = null;
var playFullVersion = null;

// retrieves the relevant id for the different browsers
function getWMPPlayerNameFromBrowser() {

    if (BrowserDetect.browser == "Explorer") {
        return 'iePlayer';
    }
    else {
        return 'nonIEPlayer';
    }
}

// easy access to WMP obj
function getWMPObj() {
    return document.getElementById(getWMPPlayerNameFromBrowser());
}

var playerObj = getWMPObj();

// event occurs when song changes
function wmpMediaChange(currentMediaId) {
    if (playerObj == null) {
        playerObj = getWMPObj();
    }

    if (playlist != null) {
        if (playlist[currentMediaId] != null) {
            // we update the artist and track information
            document.getElementById('artist').innerText = playlist[currentMediaId].Artist;
            document.getElementById('track').innerText = playlist[currentMediaId].TrackName;
            document.getElementById('trackStatus').style.display = "block";
            idI = window.setInterval("UpdatePlayer()", 100);
            stopped = false;
            playerObj.controls.play();
            document.getElementById('status').innerText = $get('buffering').innerText;
            bufferTimer = setTimeout("ShowBufferError();", 15000);
        }
    }
}

function ShowBufferError() {
    document.getElementById('status').innerText = "'" + playlist[currentMediaId].Artist + " - " + playlist[currentMediaId].TrackName + " " + $get('Unavailable').innerText;
    clearInterval(idI);
    document.getElementById('trackStatus').style.display = "none";
    timer = setTimeout("Next();", 3000);
}

// when the state of wmp control changes,
// we need to act different according to the state
function wmpPlayStateChange() {
    if (playerObj == null) {
        playerObj = getWMPObj();
    }

    if (playstateValues[playerObj.playState] == "Stopped...") {
        if (!stopped) {
            playing = false;
            if (currentMediaId < playlist.length) {
                if (playlist[currentMediaId].Uri != "NoClip" && playlist[currentMediaId].Uri != "NoFile") {
                    Next();
                }
            }
        }
    }
    else if (playstateValues[playerObj.playState] == "Playing...") {
        clearTimeout(bufferTimer);
        if (!playing) {
            document.getElementById('status').innerText = $get('playing').innerText;
            RecordTrackPlay(playlist[currentMediaId].Id);
            playing = true;
        }
    }
}

// Play Action
function Play() {
    clearTimeout(bufferTimer);
    wmpMediaChange(currentMediaId);
}

// Stop Action
function Stop() {
    if (getWMPObj() != null) {
        clearInterval(idI);
        clearTimeout(timer);
        clearTimeout(bufferTimer);
        stopped = true;
        playing = false;
        document.getElementById('status').innerText = $get('stopped').innerText;
        document.getElementById("trackStatus").style.display = "none";
        getWMPObj().controls.stop();
    }
}

// Previous track in playlist
function Previous() {
    if (playerObj == null) {
        playerObj = getWMPObj();
    }

    if (playerObj != null) {
        var newMediaId = currentMediaId - 1;

        if (newMediaId >= 0) {
            currentMediaId = newMediaId;
            playerObj.URL = playlist[currentMediaId].Uri;
            wmpMediaChange(currentMediaId);
            playing = false;
            HighlightPlaylistItem(playlist[currentMediaId].Id);
            SetCookie("playerposition", currentMediaId);
        }
    }
}

// next track in current playlist
function Next() {
    if (playerObj == null) {
        playerObj = getWMPObj();
    }

    if (playerObj != null) {

        var newMediaId = currentMediaId + 1;
        currentMediaId = newMediaId;

        if (newMediaId < playlist.length) {
            if (playlist[currentMediaId].Uri != "NoClip" && playlist[currentMediaId].Uri != "NoFile") {
                document.getElementById('trackStatus').style.display = "block";
                playerObj.URL = playlist[currentMediaId].Uri;
                wmpMediaChange(currentMediaId);
                playing = false;
                HighlightPlaylistItem(playlist[currentMediaId].Id);
                SetCookie("playerposition", currentMediaId);

            } else {
                document.getElementById('status').innerText = "'" + playlist[currentMediaId].Artist + " - " + playlist[currentMediaId].TrackName + "' unavailable...";
                document.getElementById('trackStatus').style.display = "none";
                SetCookie("playerposition", currentMediaId);
                HighlightPlaylistItem(playlist[currentMediaId].Id);
                timer = setTimeout("Next();", 3000);
            }
        }
        else {
            clearInterval(idI);
            document.getElementById('status').innerText = $get('stopped').innerText;
            document.getElementById("trackStatus").style.display = "none";
            getWMPObj().controls.stop();
        }
    }
}

// by clicking on track in playlist, seek to a track
function SeekToTrack(id) {
    for (i = 0; i < playlist.length; i++) {
        if (playlist[i].Id == id) {
            currentMediaId = i;
        }
    }

    if (playlist[currentMediaId].Uri != "NoClip" && playlist[currentMediaId].Uri != "NoFile") {
        document.getElementById('trackStatus').style.display = "block";
        getWMPObj().URL = playlist[currentMediaId].Uri;
        playing = false;
        wmpMediaChange(currentMediaId);
        HighlightPlaylistItem(playlist[currentMediaId].Id);
        SetCookie("playerposition", currentMediaId);
    } else {
        document.getElementById('status').innerText = "'" + playlist[currentMediaId].Artist + " - " + playlist[currentMediaId].TrackName + "' unavailable...";
        HighlightPlaylistItem(playlist[currentMediaId].Id);
        document.getElementById('trackStatus').style.display = "none";
        timer = setTimeout("Next();", 3000);
    }
}

// mute/unmute
function Mute() {
    var player = getWMPObj();

    if (player != null) {
        x = player.settings.mute;

        if (x == 0) {
            player.settings.mute = "1";

            var image = document.getElementById('mute');

            if (image != null) {
                image.src = "../Images/player/unmute.png";
            }

        }
        else {
            player.settings.mute = "0";

            var image = document.getElementById('mute');

            if (image != null) {
                image.src = "../Images/player/mute.png";
            }
        }
    }
}

// volume up
function VolumeUp() {
    var player = getWMPObj();

    if (player != null) {
        X = player.settings.volume;
        player.settings.volume = X + 20;
        DisplayVolumeBarImage(player.settings.volume);
    }
}

// volume down
function VolumeDown() {
    var player = getWMPObj();

    if (player != null) {
        X = player.settings.volume;
        player.settings.volume = X - 20;
        DisplayVolumeBarImage(player.settings.volume);
    }
}

// changes volume image
function DisplayVolumeBarImage(volume) {
    var image = document.getElementById('volumeBar');

    if (image != null) {
        image.src = "../Images/player/volumebar_" + volume + ".png";
    }
}

// highlights the currently playing item
function HighlightPlaylistItem(id) {
    var prevRow = null;

    if (previousId != null) {
        prevRow = document.getElementById(previousId);

        if (prevRow != null) {
            prevRow.className = "nonhighlightedtrack";
        }
    }

    var row = document.getElementById(id);

    if (row != null) {
        row.className = "PlayingSong";
        previousId = id;
    }
}

// called continuously to update position in track
function UpdatePlayer() {
    getCurrentPosition();
    wmpPlayStateChange();
}

// sets the current position in the player
function getCurrentPosition() {
    var player = getWMPObj();

    if (player != null) {
        if (player.controls.currentPositionString != "") {
            document.getElementById('currentPos').innerText = player.controls.currentPositionString;
        }
        else {
            document.getElementById('currentPos').innerText = "00:00";
        }
    }

    document.getElementById('totalTime').innerText = player.currentMedia.durationString;
}

// retrieves track details via Media Player client web service
function PlayTrack(compoId, localeId, loggedIn) {
    if (compoId != null) {
        document.getElementById('status').innerText = $get('AcquiringDetails').innerText;
        Bibc.Audiolounge.Client.Player.PlayTrack(compoId, localeId, loggedIn, SucceededCallback, OnPlayerWSRequestFailed);
    }
}

// retrieves album details via Media Player client web service
function PlayAlbum(mediaId, localeId, loggedIn) {
    if (mediaId != null) {
        playlist = new Array();
        document.getElementById('status').innerText = $get('AcquiringDetails').innerText;
        Bibc.Audiolounge.Client.Player.PlayAlbum(mediaId, localeId, loggedIn, SucceededCallback, OnPlayerWSRequestFailed);
    }
}

// retrieves playlist details via Media Player client web service
function PlayPlaylist(playlistId, loggedIn) {
    if (playlistId != null) {
        playlist = new Array();
        document.getElementById('status').innerText = $get('AcquiringDetails').innerText;
        Bibc.Audiolounge.Client.Player.PlayPlaylist(playlistId, loggedIn, SucceededCallback, OnPlayerWSRequestFailed);
    }
}

function RecordTrackPlay(contentId) {
    if (userId == null) {
        userId = document.getElementById('userId').value;
    }

    if (playFullVersion == null) {
        playFullVersion = document.getElementById('playFullVersion').value;
    }

    if (userId != 0 && playFullVersion == "True") {
        Bibc.Audiolounge.Client.Player.RecordTrackPlay(userId, contentId);//, SucceededCallback, OnPlayerWSRequestFailed);
    } 
}

// once media item has been retrieved return the details to the call back
// which processes the returned values.
function SucceededCallback(result) {

    getWMPObj().controls.stop();

    try {
        obj = Sys.Serialization.JavaScriptSerializer.deserialize(result);
    }
    catch (err) {
        obj = null;
    }

    if (obj != null && typeof (obj) != "undefined") {

        clearTimeout(bufferTimer);
        document.getElementById('status').innerText = $get('DetailsAcquired').innerText;
        readyCount = 0;
        var totalItems = obj.length;
        var nextAvailablePos = 0;
        currentMediaId = 0;
        playlist = new Array();

        for (i = 0; i < obj.length; i++) {
            playlist[nextAvailablePos] = obj[i];
            nextAvailablePos++;
        }

        if (obj.length > 1) {
            var temp = builder.bind(obj);
            $get("grid").innerHTML = temp;
        }
        else {
            $get("grid").innerHTML = "";
        }

        if (playlist[currentMediaId].Uri != "NoClip" && playlist[currentMediaId].Uri != "NoFile") {
            document.getElementById('trackStatus').style.display = "block";
            getWMPObj().URL = playlist[currentMediaId].Uri;
            getWMPObj().controls.play();

            wmpMediaChange(currentMediaId);
            HighlightPlaylistItem(playlist[currentMediaId].Id);

            SetCookie("playeritem", result);
            SetCookie("playerposition", currentMediaId);
        }
        else {
            document.getElementById('status').innerText = "'" + playlist[currentMediaId].Artist + " - " + playlist[currentMediaId].TrackName + "' unavailable...";
            HighlightPlaylistItem(playlist[currentMediaId].Id);
            document.getElementById('trackStatus').style.display = "none";
            timer = setTimeout("Next();", 3000);
            SetCookie("playeritem", result);
            SetCookie("playerposition", currentMediaId);
        }
    }
    else {
        DisplayPrompt("", $get('Failed').innerText);
    }
}

function OnPlayerWSRequestFailed(error) {
    document.getElementById('status').innerText = $get('Failed').innerText;
}

// restores the playback after postback
function RestorePlaybackAfterRefresh() {
    var previouslyPlayed = GetCookie("playeritem");
    currentMediaId = GetCookie("playerposition");
    var playerAction = GetCookie("playeraction");

    try {
        obj = Sys.Serialization.JavaScriptSerializer.deserialize(previouslyPlayed);
    }
    catch (err) {
        obj = null;
    }

    if (obj != null && typeof (obj) != "undefined") {
        if (playerAction == null || typeof (playerAction) == "undefined") {
            playlist = obj;

            if (playlist.length > 1) {
                var temp = builder.bind(playlist);
                $get("grid").innerHTML = temp;
                HighlightPlaylistItem(playlist[currentMediaId].Id);
            }
        }
    }
}

function ClearMediaPlayer() {
    var wmp = getWMPObj();

    if (wmp != null) {
        getWMPObj().controls.stop();
        playlist = new Array();
        SetCookie("playeraction", "");
        SetCookie("playerposition", "");
        SetCookie("playeritem", "");
        $get("grid").innerHTML = "";
    }
}

function PlayMedia(ItemId, ItemType) {
    if (ItemType == 'Composition') {
        PlayTrack(ItemId, true);
    }
    else {
        PlayAlbum(ItemId, true);
    }
}