
/**
 * The location of the player.
 */
var PLAYER = "/alfresco/media/flowplayer/flowplayer-3.1.5.swf?time=" + new Date().getTime()

/**
 * The properties used to initialize the player.
 */
var PLAYER_PROPERTIES = {src: PLAYER, wmode: 'transparent'};

/**
 * The location of the Audio plugin.
 */
var AUDIO_PLAYER = '/alfresco/media/flowplayer/flowplayer.audio-3.1.2.swf'

var AUDIO = "audio"

var VIDEO = "video"

var TOKEN_LINK = "token_link"

var TOKEN_ID = "token_id"

var TOKEN_TITLE = "token_title"
    
var TOKEN_NAME = "token_name"

var TOKEN_FILE = "token_file"

var ID_PREFIX = "audio_id_"

var ON_INDICATOR = "> "

var MEDIA_FIND_URL = "/alfresco/service/media/iwebsite/find?guest=true"

var HOVER_COLOR = "#9c607a"

/**
 * If <code>true</code> the first clip is to be played, else not.
 */
var firstClip = true

/**
 * Used to handle the clicks on the buttons.
 */
var buttonHandler = new ButtonHandler()

/**
 * Fetches the flv file that should be played and
 * inserts the link for display of the flowplayer.
 */
var initPlayer = function(myType) {
    switch(myType) {
        case AUDIO:
            $.get(MEDIA_FIND_URL, { type: myType }, startAudio)
            break
    case VIDEO:
            $.get(MEDIA_FIND_URL, { type: myType }, startVideo)
            break
    }
    addPreviousNextHandlers()
}

/**
 * Main definition of the button handler class.
 */
function ButtonHandler() {
}

/**
 * The clip that is currently being played.
 */
ButtonHandler.prototype.currentClip = ""

/**
 * The current index of the clip.
 */
ButtonHandler.prototype.currentIndex = -1

/**
 * The array with all the links that are to be played.
 */
ButtonHandler.prototype.linkArray = []

 /**
  * The array with the titles
  */
 ButtonHandler.prototype.titleArray = []

/**
 * Binds the event handlers for the previous and next functions.
 */
addPreviousNextHandlers = function() {
    $("#previous").click(buttonHandler.handlePrevious)
    $("#next").click(buttonHandler.handleNext)
}

/**
 * Handles going back to the previous file.
 */
ButtonHandler.prototype.handlePrevious = function() {
    buttonHandler.currentIndex = buttonHandler.currentIndex > 0 ?
        --buttonHandler.currentIndex : buttonHandler.linkArray.length - 1
    var index = buttonHandler.currentIndex
    setAudioFile(buttonHandler.linkArray[index], "id_" + buttonHandler.currentIndex, buttonHandler.titleArray[index])
}

/**
 * Handles going back to the next file.
 * @param noStart If <code>true</code> the player does not start playing, otherwise it does.
 */
ButtonHandler.prototype.handleNext = function(noStart) {
    buttonHandler.currentIndex = buttonHandler.currentIndex < buttonHandler.linkArray.length - 1 ?
        ++buttonHandler.currentIndex : 0
    var index = buttonHandler.currentIndex
    setAudioFile(buttonHandler.linkArray[index], "id_" + buttonHandler.currentIndex, buttonHandler.titleArray[index], noStart)
}

/**
 * Sets the clip that is currently being played.
 */
ButtonHandler.prototype.setCurrentClip = function(clip) {
    this.currentClip = clip
    var text = clip.theTitle
    text = unescape(text)
    this.currentIndex = clip.id.replace(/.+\_/, "")
    $("#currentFile").text(text)
}

function Util() {
}

/**
* Limits text by a certain number of characters never breaking 
* a word.
* @param res The string that is to be limited.
* @param limit The limit in characters.
* @return The limited text.
*/
Util.prototype.doLimit = function (res, limit, extension) {
   if(res.length > limit) {
       var index = res.lastIndexOf(' ', limit)
       if(index > -1) {
          limit = index
       }
       return res.substring(0, limit) + extension
   }
}

var util = new Util();

/**
 * Starts the audio player.
 * @param data The JSON data string.
 */
var startAudio = function(data) {
    startPlayer(data, AUDIO)
}

/**
 * Starts the video player.
 * @param data The JSON data string.
 */
var startVideo = function(data) {
    startPlayer(data, VIDEO)
}

/**
 * Injects the link for the flow player with the right flv file
 * which is retrieved from an Alfresco Webscript.
 * @param data The data retrieved from the Alfresco Webscript.
 * @param playerType The type of player to be started.
 */
var startPlayer = function(data, playerType) {
    var playerData = eval('(' + data + ')')
    var status = playerData.response.status
    var thumb = playerData.response.thumbnail
    switch (playerType) {
        case VIDEO:
            var video = playerData.response.video
            var title = playerData.response.title
            var description = playerData.response.description
            var mediaLink = playerData.response.mediaLink
            if(status == "OK") {
                if(title) {
                    $("#videoTitle").text(title);
                }
                if(description) {
                    description = util.doLimit(description, 120, " ..."); // Limit the description
                    $("#videoDescription").text(description);
                }
                if(mediaLink) {
                    $("#mediaLink").attr("href", mediaLink);
                }
                $(function() {
                    flowplayer("player", PLAYER_PROPERTIES, {
                        clips: {
                            autoPlay: false,
                            autoBuffering: false
                        },
                        playlist: [
                            // first entry in a playlist work as a splash image for the MP3 clip
                            thumb,
                            {
                                // our song
                                url: video,
                                autoPlay: false
                            }
                        ],
                        plugins: {
                            controls: {
                                playlist: false
                            }
                        }
                     }).play();
                });
            }
            else {
                $("#videoPlayerContainer").append('Sorry, no videos available at present.');
            }
            break;
        case AUDIO:
            if(status == "OK") {
                var audioList = playerData.response.data
                insertAudioElements(audioList)
            }
            else {
                $("#playerContainer").append('Sorry, no audio files available at present.');
            }
            break;
    }
}

/**
 * Inserts the audio elements into the page.
 * @param audioList The list with the audio list.
 */
function insertAudioElements(audioList) {
    var myPlayList = []
    var template = '<a href="#" id="' + TOKEN_ID + '" onclick="setAudioFile(\'' 
        + TOKEN_LINK + '\', this.id, \'' + TOKEN_TITLE + '\'); return false" name="' + TOKEN_NAME + '">' + TOKEN_FILE + '</a>'
    var flowPlayerlist = []
    for ( var i in audioList ) {
        myPlayList[i] = audioList[i].audio
        var link = template.replace(TOKEN_ID, ID_PREFIX + i)
        link = link.replace(TOKEN_LINK, audioList[i].audio)
        link = link.replace(TOKEN_FILE, audioList[i].title)
        link = link.replace(TOKEN_NAME, audioList[i].filename)
        link = link.replace(TOKEN_TITLE, audioList[i].title)
        $("#playerContainer").append(link);
        buttonHandler.linkArray[buttonHandler.linkArray.length] = audioList[i].audio
        buttonHandler.titleArray[buttonHandler.titleArray.length] = audioList[i].title
        if(i == 0) {
            flowPlayerlist[flowPlayerlist.length] = {url: myPlayList[i], autoPlay: false}
        }
    }
    
    var player = flowplayer("audio", {src: PLAYER, wmode: 'transparent'}, {
        plugins: {
            audio: {
                url: AUDIO_PLAYER
            },
            controls: {
                playlist:false,
                fullscreen:false,
                buttonColor: '#dfd2d2',
                progressGradient: 'medium',
                volumeSliderGradient: 'none',
                bufferGradient: 'none',
                timeBgColor: '#555555',
                tooltipColor: '#5F747C',
                volumeSliderColor: '#000000',
                backgroundGradient: [0.6,0.3,0,0,0],
                sliderColor: '#dedede',
                buttonOverColor: '#728B94',
                backgroundColor: '#ffeee6',
                borderRadius: '0px',
                bufferColor: '#445566',
                durationColor: '#ffffff',
                timeColor: '#e92591',
                sliderGradient: 'none',
                progressColor: '#f4d2d2',
                tooltipTextColor: '#ffffff',
                height: 24,
                opacity: 1.0
            }
        }
    });
    // setup additional event listener using the API
    player.onStart(function() {
        var fileName = player.getClip().url.replace(/.+\//, "")
        fileName = unescape(fileName)
        var children = $("#playerContainer > *")
        for(var i = 0, j = 0; i < children.length; i++) {
            var child = children[i]
            if(child.nodeName.toUpperCase() == "A") {
                var elem = $("#" + ID_PREFIX + j)
                var content = child.attributes["name"].nodeValue
                if(content == fileName) {
                    var highlightedColor = "#dea182"
                    elem.css("backgroundColor", highlightedColor)
                    elem.css("color", "white")
            elem.hover(function() {$(this).css("backgroundColor", highlightedColor), $(this).css("color", "white")}, function() {$(this).css("backgroundColor", highlightedColor), $(this).css("color", "white")})
                }
                else {
                    var textColor = "#6b4e3e"
                    elem.css("backgroundColor", "transparent")
                    elem.css("color", textColor)
            elem.hover(function() {$(this).css("backgroundColor", HOVER_COLOR), $(this).css("color", "white")}, 
                function() {$(this).css("backgroundColor", "transparent"), $(this).css("color", textColor)})
                }
                j++
            }
        }
    })
    buttonHandler.handleNext(true)

}

/**
 * Sets the audio file that is to be played.
 * @param link The link to the audio file.
 */
function setAudioFile(link, id, title, noStart) {

    var clip = {url: link, autoPlay: true, id: id, theTitle: title}
    var player = flowplayer("audio")
    if(!noStart) {
        condplay(clip, player)
    }
    else {
        handleFirstClip(player, clip)
    }
    buttonHandler.setCurrentClip(clip)
    return false
}


/**
 * Handles the first clip by setting autoplay to false and then
 * loading and starting it in a mute player. After 2 seconds 
 * the player is unmuted and the player stopped.
 */
function handleFirstClip(player, clip) {

    player.onStart(function() { 
        if(firstClip) {
            firstClip = false
        for(var i = 0; i < 5; i++) {
                window.setTimeout(function() {player.unmute(), player.pause(), player.seek(0)}, 2000)
        if(player.isPaused()) {
            break;
        }
            }
        }   
    }); 
    var playerInstance = player.play(clip)
}


/**
 * The clip that is to be played.
 * @param player the current instance of the FlowPlayer.
 */
function condplay(clip, player) {
    // retrieve playlist index
    if (player.getState() > 1) {
        player.stop();
    }
    player.getClip(0).update(clip);
    player.play(clip)
}


