/**
 * @author aalucas
 * This script requires jQuery ***
 */

/**
 * Brightcove Player & Javascript API configuration object.
 * It's global but we're already forced into global scope because of their API.
 * This means to have multiple players on one page they need to use an iframe.
 */
var dniBrightcove = {
	'bcConfig': {
		"videoId": null, "videoRef": null, "lineupId": null,
		"playerTag": null, "autoStart": false, "preloadBackColor": "#000000",
		"width": 326, "height": 292, "playerId": null,
		"wmode": "transparent"
	},
	'config': {
		"experience": 8,
		"playlistLength": 4,
		"playlistId": "playlist",
		"playingId": "playing",
		"moreVideosId": "more-videos",
		
		'handlers': {
			//needs to handle both title and lineup DTOs
			'lineupTitles': function (DTO) {},
	
			'playlist': function (lineupDTO, titleDTO) {},
			//takes the video id and the new player title
			//(usually the video's display name)
			'playTitle': function (titleId, title) {},
			'setPlayerTitle': function (title) {} 	
		},
	
		'translations': {
			"playVideo": "Play Video",
			"moreVideos": "More Videos >"
		}
	},
	'init': function () {
		//assign container object which contains the player
		var cnt = document.getElementById("dniBrightcovePlayer");
		this.config.container = cnt;
		
		//return information about the lineup back to our handlers
		getFeaturedLineup();
	},
	'lineupObjects': []
}

//#Horrible Brightcove Player Global Results & Event Handlers
function onTemplateLoaded (message) {
	callFlash("addEventListener", "contentLoad", "onContentLoad");
}
function onContentLoad () {
	dniBrightcove.init();
}
function getFeaturedLineup () {
	callFlash('getFeaturedLineup');
}
function getFeaturedLineup_Result (lineupDTO) {
	dniBrightcove.config.handlers.lineupTitles(lineupDTO);
}
function getTitleById (id) {
	callFlash("getTitleById",id);
}
function getTitleById_Result (titleDTO) {
	dniBrightcove.config.handlers.lineupTitles(titleDTO);
}
function loadTitleById (id) {
	callFlash('loadTitleById',id);
}
//#End Horror

dniBrightcove.util = {}
dniBrightcove.util.getInfoFromString = function (str, delimit) {
	if (!delimit) var delimit = " ";
	var isparam = RegExp('(.*)__(.*)');
	var arr = {}
	
	//Create an array of the element's classes
	var str = str.split(delimit);
	//loop through classes and add them to arr if they are parameters
	for (var i=str.length-1,k;k=str[i];i--) {
		var tmp = k.match(isparam);
		if (tmp) {
			arr[tmp[1]] = tmp[2];
		}
	}
	//return the array object of parameters
	return arr;
}

/**
 * Plays the video with the specified id in the player
 * @param {Integer}	titleId		Video Id of the title to play 
 */
dniBrightcove.playTitle = function (titleId, title) {
	
	loadTitleById(titleId);
	this.config.handlers.setPlayerTitle(title);
	
}
/**
 * Changes the main title of the player
 * @param {String}	title	The new title of the player
 */
dniBrightcove.setMainTitle = function (title) {
	
	var ptitle = this.config.container.getElementsByTagName("h4")[0];
	ptitle.innerHTML = title;
	
	var ptitleTitle = document.createAttribute("title");
	ptitleTitle.nodeValue = title;
	
	ptitle.setAttributeNode(ptitleTitle);
}

/**
 * This method will handle the gathering of information to pass on to the renderPlaylist method
 * @param {Object} DTO	A Brightcove title or lineup data transfer object (basically like a bean)
 */
dniBrightcove.handleLineup = function (DTO) {
	
	//check whether we're being called to handle a single title or a lineup
	
	var dtoType = 0; // initialise to 0 meaning unknown
	
	if (typeof DTO.videoIds !== "undefined") {
		dtoType = 1; // set to 1 if we're a lineup
	} else {
		dtoType = 2; // set to 2 if we're a single title
	}
	
	switch (dtoType) {
		case 1:
			dniBrightcove.lineup = DTO;
			
			// if we're a lineup, fetch the data object for each title
			for (var i = DTO.videoIds.length - 1, k;
					k = DTO.videoIds[i];
					i--) {
				
				getVideoById(k);
				
			}
			break;
		case 2:
			//if we're a single title then populate the lineup array
			dniBrightcove.lineupObjects.push(DTO); 
			
			//if we have all the titles now then render the playlist below the player
			if (dniBrightcove.lineupObjects.length == dniBrightcove.lineup.videoIds.length) {
				
				dniBrightcove.config.handlers.playlist(dniBrightcove.lineup,dniBrightcove.lineupObjects);
				
			}
			break;
		default: return false;
	}
	
	//get video data objects, will cause a call back to handleLineup
	//which will be handled above in the switch statement
	function getVideoById (id) {
		getTitleById(id);
	}
	
}

/**
 * This method creates the HTML for the player's playlist and inserts it into the
 * element assigned to dniBrightcove.container
 * @param {Object} lineup	The Brightcove lineup DTO
 * @param {Object} titles	An array of the Brightcove title DTOs for the lineup
 */
dniBrightcove.renderPlaylist = function (lineup, titles) {
	
	//create the playlist container element
	var container = document.createElement("ul");
	
	//create attribute nodes for playlist
	var containerId = document.createAttribute("class");
	var activeClass = document.createAttribute("class");
	var moreVideosClass = document.createAttribute("class");
	
	containerId.nodeValue = this.config.playlistId;
	activeClass.nodeValue = this.config.playingId;
	moreVideosClass.nodeValue = this.config.moreVideosId;
	
	//create the playlist items
	function createLi (titleDTO, scope) {
		var item = document.createElement("li");
		var itemId = document.createAttribute("class");
		itemId.nodeValue = "videoId__" + titleDTO.id;
		
		if ("" + titleDTO.id == "" + lineup.videoIds[0]) {
				itemId.nodeValue += " " + activeClass.nodeValue;
				scope.config.handlers.setPlayerTitle(titleDTO.displayName);
		}
		
		//create Title number
		var num = document.createElement("em");
		num.innerHTML = (titles.length - position) + " ";
		
			var numId = document.createAttribute("class");
			numId.nodeValue = "item-number";
			num.setAttributeNode(numId);
		
		item.appendChild(num);
		
		//create Video Title
		var title = document.createElement("strong");
		title.innerHTML = titleDTO.displayName;
		
			var titleTitle = document.createAttribute("title");
			titleTitle.nodeValue = titleDTO.displayName;
			title.setAttributeNode(titleTitle);
			
		item.appendChild(title);
		
		//create Play Video Text
		var play = document.createElement("em");
		play.innerHTML = " " + scope.config.translations.playVideo;
		
			var playId = document.createAttribute("class");
			playId.nodeValue = "play-video";
			play.setAttributeNode(playId);
		
		item.appendChild(play);
		
		//assign id/class and insert into container
		item.setAttributeNode(itemId);
		container.appendChild(item);
	}
	
	var position = titles.length - 1;
	for (var k;
			((titles.length - position) < this.config.playlistLength)
				&& (k = titles[position]);
			position--) {
		
		createLi(k, this);	
	}
	
	if (this.config.moreVideos) {
		var moreVideos = document.createElement("li");
		moreVideos.setAttributeNode(moreVideosClass);
		
		var moreVideosLink = document.createElement("a");
		moreVideosLink.href = this.config.moreVideos;
		moreVideosLink.innerHTML = this.config.translations.moreVideos;
		moreVideos.appendChild(moreVideosLink);
		
		container.appendChild(moreVideos);
	} else {
		createLi(titles[position], this);
	}
	
	//insert playlist into page
	container.setAttributeNode(containerId);
	this.config.container.appendChild(container);
	
	//activate playlist functionality
	this.addPlaylistEvents();
	
}

/**
 * Requires jQuery.
 * Initialises functionality to play lineup titles when they are clicked in the playlist.
 */
dniBrightcove.addPlaylistEvents = function () {
	//add events to all li which have videoIds assigned
	
	var li = this.config.container.getElementsByTagName("li");
	
	for (var i = li.length - 1, k;
			k = li[i];
			i--) {

		if (k.className) {
			var value = this.util.getInfoFromString(k.className);

			if ((value.videoId)||(k.className == this.config.moreVideosId)) {
				
				$(k).click(function () { //play video and update playlist classes
					
					var value = dniBrightcove.util.getInfoFromString(this.className);
					
					var playingClass = dniBrightcove.config.playingId;
					var i1 = $(this); //this as jQuery object 
					
					//play the video
					dniBrightcove.config.handlers.playTitle(value.videoId, i1.children("strong").text());
					
					//update classes
					i1.parent().children("." + playingClass).removeClass(playingClass);
					i1.addClass(playingClass);
					
				});
				
				$(k).hover(
					function () { $(this).addClass("hover")},
					function () { $(this).removeClass("hover")}
				)				
			}
		}
	}
	
}

//# Assign dniBrightcove handlers
dniBrightcove.config.handlers.lineupTitles = function (DTO) { dniBrightcove.handleLineup(DTO);}
dniBrightcove.config.handlers.playlist = function (lineup, titles) { dniBrightcove.renderPlaylist(lineup, titles)};
dniBrightcove.config.handlers.playTitle = function (titleId, title) { dniBrightcove.playTitle(titleId, title);}
dniBrightcove.config.handlers.setPlayerTitle = function (title) { dniBrightcove.setMainTitle(title);}
