/**
 * 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 site = typeof(g_SITE_NAME) != "undefined" ? g_SITE_NAME : extractParam('site')

var MEDIA_FIND_URL = "/alfresco/service/media/iwebsite/find?guest=true" + (site.length > 0 ? "&site=" + site : "")

var HOVER_COLOR = "#9c607a"

/**
 * If <code>true</code> the first clip is to be played, else not.
 */
var firstClip = true

/**
 * Extracts a parameter with a certain name.
 * @param paramName The name of the parameter for which we are looking for the value.
 */
function extractParam(paramName) {
    var start = location.href.indexOf(paramName)
    if(start == -1) {
        return ""
    }
    start += paramName.length + 1
    var end = location.href.indexOf("&", start)
    if(end == -1) {
      end = location.href.length
    }
    return location.href.substring(start, end)
}

/**
 * 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. Limits the displayed text to 35
 * characters.
 * 
 * @param clip
 *            The clip which is to be displayed.
 */
ButtonHandler.prototype.setCurrentClip = function(clip) {
	this.currentClip = clip
	this.currentIndex = clip.id.replace(/.+\_/, "")
}

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
	}
	return res;
}

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,
				autoBuffering : false
			}
		}
	}

	var player = flowplayer("audio", {
		src : PLAYER,
		wmode : 'transparent'
	}, {
		clip : {
			autoBuffering : false
		},
		plugins : {
			audio : {
				url : AUDIO_PLAYER
			},
			controls : controlsProperties
		}
	});
	// setup additional event listener using the API
	player.onStart(function() {
		var clip = player.getClip()
		var fileName = clip.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) {
					buttonHandler.setCurrentClip(clip)
					elem.css("backgroundColor", HIGHLIGHTED_BCK_COLOR)
					elem.css("color", HIGHLIGHTED_COLOR)
					elem.hover(function() {
						$(this).css("backgroundColor", HIGHLIGHTED_BCK_COLOR), $(
								this).css("color", HIGHLIGHTED_COLOR)
					}, function() {
						$(this).css("backgroundColor", HIGHLIGHTED_BCK_COLOR), $(
								this).css("color", HIGHLIGHTED_COLOR)
					})
					// Set the title at the bottom.
					var text = elem.text()
					text = unescape(text)
					elem.focus()
					var limitedText = util.doLimit(text, 28, " ...")
					$("#currentFile").text(limitedText)
				} else {
					elem.css("backgroundColor", "transparent")
					elem.css("color", TEXT_COLOR)
					elem.hover(function() {
						$(this).css("backgroundColor", HOVER_COLOR), $(this)
								.css("color", HIGHLIGHTED_COLOR)
					}, function() {
						$(this).css("backgroundColor", "transparent"), $(this)
								.css("color", TEXT_COLOR)
					})
				}
				j++
			}
		}
	})
	buttonHandler.handleNext(true)

}

/**
 * Sets the audio file that is to be played.
 * 
 * @param link
 *            The link to the audio file.
 * @param id
 *            The clip identifier.
 * @param title
 *            The title of the clip.
 */
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)
	}
	return false
}

/**
 * Handles the first clip separately or in case it is not the first clip plays
 * it.
 * 
 * @param player
 *            The FlowPlayer.
 * @param clip
 *            The clip that is to be played.
 */
function handleFirstClip(player, clip) {
	if (firstClip) { // Activates, but does not buffer not start the first
						// clip.
		player.onLoad(function() {
			var clippy = player.getClip(0)
			clippy.onBeforeBegin(function() {
				if (firstClip) {
					firstClip = false
					return false
				}
			})
			clippy.update(clip)
		})
		player.load(clip)
	} else {
		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)
}
