﻿var MultiAudioPlayer =
{
    FlashName: "audioplayer",
    FlashObject: null,
    CurrentPlayer: null,
    _playersAudio: [],
    CurrentVideoPlayer: null,
    LoggingAddress: null,
    register: function(player) {
        if (player) {
            if (!this._playersAudio[player.id]) {
                this._playersAudio[player.id] = player;
            } /*else {
                throw "Player already registered";
                }*/
        }
        else {
            throw "Player not defined";
        }
    },
    play: function(playerId) {
        if (this._playersAudio[playerId]) {
            this.stopPlayingVideo();
            this._playersAudio[playerId].play();
        } else {
            throw "Player not registered";
        }
    },
    playById: function(playerId, trackId) {
        if (this._playersAudio[playerId]) {
            this.stopPlayingVideo();
            this._playersAudio[playerId].playById(trackId);
        } else {
            throw "Player not registered";
        }
    },
    playAll: function(playerId, trackId) {
        if (this._playersAudio[playerId]) {
            this.stopPlayingVideo();
            this._playersAudio[playerId].stop();
            this._playersAudio[playerId].playById(trackId);
            this._playAllMode = true;
            this.autoNext = true;
        }
        else {
            throw "Player not registered";
        }
    },
    stop: function(playerId, trackId) {
        if (this._playersAudio[playerId]) {
            this._playersAudio[playerId].stop(trackId);
        } else {
            throw "Player not registered";
        }
    },
    previous: function(playerId) {
        if (this._playersAudio[playerId]) {
            this.stopPlayingVideo();
            this._playersAudio[playerId].previous();
        } else {
            throw "Player not registered";
        }
    },
    next: function(playerId) {
        if (this._playersAudio[playerId]) {
            this.stopPlayingVideo();
            this._playersAudio[playerId].next();
        } else {
            throw "Player not registered";
        }
    },
    setFlash: function() {
        this.FlashObject = this.getElement(this.FlashName);
    },
    stopPlayingVideo: function() {
        if (this.CurrentVideoPlayer != null) {
            var video = document.getElementById(this.CurrentVideoPlayer);
            if (video != null) {
                video.doPlayPause();
            }
        }
    },
    setCurrentVideoPlayer: function(playerName) {
        if (playerName != null && this.CurrentVideoPlayer != null && this.CurrentVideoPlayer != playerName) //cas de lecture d'une autre video d'un autre player alors qu'une vidéo est deja en cours
        {
            this.stopPlayingVideo();
        }
        if (playerName != null) {
            this.CurrentVideoPlayer = playerName;
            if (this.CurrentPlayer != null) {
                this.CurrentPlayer.stop();
            }
        }
    },
    getElement: function(name) {
        if (navigator.appName.indexOf("Microsoft") != -1) {
            return window[name];
        } else {
            return document.getElementById(name);
        }
    },
    stopCurrentPlayer: function() {
        if (this.CurrentPlayer != null)
            this.CurrentPlayer.stop();
        if (this.CurrentVideoPlayer != null)
            this.stopPlayingVideo();
    }
}

function LogListening(args)
{
  $.ajax({
  url: MultiAudioPlayer.LoggingAddress,
  type: "GET",
  data:({content : args}),
  dataType: "jsonp",
  success: function(data) {
    
  }
});
}
function PlayerCallback(what, who, args) {
    
    if (what == 'initialized') {
        MultiAudioPlayer.setFlash();
    }
    if (typeof (who) != 'undefined' && who != null && who.length > 0 && who != 'null') {
        switch (what) {
            case 'play':
                {
                    MultiAudioPlayer.stopPlayingVideo();
                    MultiAudioPlayer.CurrentPlayer.raiseMediaChanged(who);
                    break;
                }
            case 'error':
            case 'pause':
                {
                    break;
                }
            case 'stop':
                {
                    MultiAudioPlayer.CurrentPlayer.raiseMediaStopped(who);
                    break;
                }
            case 'finished':
                {
//                    MultiAudioPlayer.stopCurrentPlayer();
                    MultiAudioPlayer.CurrentPlayer.finished();
                    break;
                }
            case 'logAccessFile':
                {
                    LogListening(args);
                    break;
                }
        }
    }
}

function AudioItem(id, url, type, title, performer, duration, coverUrl,coverLiteral,index,userId) {
    this.id = id;
    this.url = url;
    this.index = index;
    this.title = title;
    this.performer = performer;
    this.duration = duration;
    this.coverUrl = coverUrl;
    this.coverLiteral = coverLiteral;
    this.type = type;//1:fnacmusic(oid),2:fnaccom(id Dsp)
    this.userId = userId;
};

AudioItem.prototype = {
    id: null,
    url: null,
    title: null,
    performer: null,
    duration: null,
    coverUrl:null,
    coverLiteral:null,
    index: -1,
    type:null,
    userId:null,
    isLast: false,
    isFirst: false
}

function AudioPlayer(id, mediaList, mediaChangedCallback,mediaStoppedCallback, metaUpdatedCallback) {
    this.initialize(id, mediaList, mediaChangedCallback,mediaStoppedCallback, metaUpdatedCallback);
};



AudioPlayer.prototype = {
    mediaChanged: function(player, media) { },
    mediaStopped: function(player, media) { },
    metaUpdated: function(player, media, currentTime, totalTime, loadRatio, playRatio) { },
    update: function(player) {
        if (this.updateOnce(player)) {
            setTimeout(function() { player.update(player); }, 300);
        }
    },
    updateOnce: function(player) {
        if (player != null && MultiAudioPlayer.FlashObject != null && player.metaUpdated != null && player._playingId != null) {
            var totalTime = MultiAudioPlayer.FlashObject.GetSongDuration(player._playingId);
            var currentTime = MultiAudioPlayer.FlashObject.GetSongTime(player._playingId);
            var playRatio = MultiAudioPlayer.FlashObject.GetSongPosition(player._playingId);
            var loadRatio = MultiAudioPlayer.FlashObject.GetSongProgress(player._playingId);
            var item = player._media[player._playingId];
            player.metaUpdated(player, item, currentTime, totalTime, loadRatio, playRatio);
            return true;
        }
        return false;
    },
    raiseMediaChanged: function(mediaId) {
        if (this.mediaChanged) {
            this.mediaChanged(this, this._media[mediaId]);
        }
    },
    raiseMediaStopped: function(mediaId) {
        if (this.mediaStopped) {
            this.mediaStopped(this, this._media[mediaId]);
            //this.metaUpdated(this, this._media[mediaId], 0, 0, 0, 0);
        }
    },
    id: null,
    _media: [],
    _keys: [],
    _playingId: null,
    _lastPlayingId: null,
    autoNext: true,
    autoNextSingle: true,
    _playAllMode: false,
    initialize: function(playerId, list, mediaChangedCallback, mediaStoppedCallback, metaUpdatedCallback) {
        this.id = playerId;
        this._media = [];
        this._keys = [];
        this._lastPlayingId = null;
        this._playingId = null;
        if (list) {
            for (var p in list) {
                this.addTrack(p, list[p], null, null, null, null);
            }
        }
        this.mediaChanged = mediaChangedCallback;
        this.metaUpdated = metaUpdatedCallback;
        this.mediaStopped = mediaStoppedCallback;
    },
    clear: function() {
        this._media = [];
        this._keys = [];
    },
    addTrack: function(id, url, type, title, performer, duration, coverUrl, coverLiteral, userId) {
        var item = new AudioItem(id.toString(), url, type, title, performer, duration, coverUrl, coverLiteral, this._keys.length, userId);
        this._media[item.id] = item;
        if (this._keys.length == 0)
            item.isFirst = true;
        if (this._keys.length > 0)
            this._keys[this._keys.length - 1].isLast = false;
        item.isLast = true;
        this._keys.push(item);

    },
    play: function() {
        if (this._lastPlayingId != null)
            this.playById(this._lastPlayingId);
        else
            this.playByIndex(0);
        this._playAllMode = true;
    },
    playById: function(id) {

        var item = this._media[id];
        if (this._lastPlayingId != id)
            this.stop();
        this.playByItem(item);
    },
    playByIndex: function(index) {
        var item = this._keys[index];
        this.playByItem(item);
    },
    playByItem: function(item) {
        this._playAllMode = this.autoNextSingle;
        this._playByItem(item);
    },
    _playByItem: function(item) {
        if (MultiAudioPlayer.FlashObject != null && item) {
            // Si on demande à rejouer le même track, on le stoppe uniquement
            var dontplay = (this._playingId == item.id);
            // On arrête le player en cours
            if (MultiAudioPlayer.CurrentPlayer != null)
                MultiAudioPlayer.CurrentPlayer.stop();
            // On set le player courant
            if (MultiAudioPlayer.CurrentPlayer != this)
                MultiAudioPlayer.CurrentPlayer = this;
            if (!dontplay) {
                this._playingId = item.id;
                this._lastPlayingId = this._playingId;
                MultiAudioPlayer.FlashObject.LoadSong(item.url, item.id, item.type, item.userId);
                this.update(this);
            }
        }
    },
    stop: function() {
        if (MultiAudioPlayer.FlashObject != null) {
            if (this._playingId != null) {
                MultiAudioPlayer.FlashObject.StopSong(this._playingId);
                this._playingId = null;
            }
        }
    },
    next: function() {
        if (MultiAudioPlayer.FlashObject != null) {
            if (this._lastPlayingId != null) {
                var i = this._media[this._lastPlayingId].index;
                if (i < this._keys.length - 1) {
                    this._playByItem(this._keys[i + 1]);
                }
                else {
                    this.stop();
                    //this._playingId = null;
                }
            }
        }
    },
    previous: function() {
        if (MultiAudioPlayer.FlashObject != null) {
            if (this._lastPlayingId != null) {
                var i = this._media[this._lastPlayingId].index;
                if (i > 0) {
                    this._playByItem(this._keys[i - 1]);
                }
            }
        }
    },
    tracksCount: function() {
        return this._keys.length;
    },
    currentTrackIndex: function() {
        if (this._lastPlayingId) {
            return this._media[this._lastPlayingId].index;
        }
        return -1;
    },
    finished: function() {
        if (this._playAllMode && this.autoNext) {
            this.next();
        }
    },
    volumeUp: function() {
        if (MultiAudioPlayer.FlashObject != null && this._playingId != null) {
            var v = MultiAudioPlayer.FlashObject.GetSongVolume(this._playingId);
            if (v < 1) {
                v = v + 0.1;
                var v = MultiAudioPlayer.FlashObject.SetSongVolume(this._playingId, v);
            }
        }
    },
    volumeDown: function() {
        if (MultiAudioPlayer.FlashObject != null && this._playingId != null) {
            var v = MultiAudioPlayer.FlashObject.GetSongVolume(this._playingId);
            if (v > 0) {
                v = v - 0.1;
                var v = MultiAudioPlayer.FlashObject.SetSongVolume(this._playingId, v);
            }
        }
    }
}


var TrackId=0;
var Type="";
var useOffset=false;
function OpenPopin(obj, e, type, id) {
    var offsetTop = 0;
    var offsetLeft = 0;
    if (useOffset) {
        var offset = $("#editorialContent .blk_inside").offset();
        offsetTop= offset.top;
        offsetLeft = offset.left; 
    } 
    TrackId = id;
    Type = type;
    var e = $.event.fix(e);
	$("#PlayerPopin, #FMPlaylistPopin")
	  .css({ top: (e.pageY - offsetTop) - 31, left: (e.pageX - offsetLeft) + 24 })
	  .filter("#PlayerPopin")
      .css("display", "block");
      
}
function popinPos(obj, e) {
    var offsetTop = 0;
    var offsetLeft = 0;
    if (useOffset) {
        var offset = $("#editorialContent .blk_inside").offset();
        offsetTop= offset.top;
        offsetLeft = offset.left; 
    } 
    var e = $.event.fix(e);
	$("#FMPlaylistPopin")
	  .css({ top: (e.pageY - offsetTop) - 31, left: (e.pageX - offsetLeft) + 24 });
}

$(function() {
	$("#closePlayerPopin").click(function() {
		$("#PlayerPopin").css('display', 'none');
		return false;
	});
});
//Temporaire pendant la transistion JS -> permet de notifier de la création de l'objet MultiAudioPlayer
AppCore.ready(function()
{
    AppCore.register("audioplayer", function()
    {
        return {};
    });
});
