﻿
var player;
var bcExp;

var modVP;
var modExp;
var modCon;
var modMedia;
var modAd;
var tabBar, videoList;


var PostBackDelay = 5;
var hasPostedBack = false;
var comboBox;
var playlists;

var loadedPlaylists = new Array();

var currentMediaID;
var currentReference;
var currentUserID;
var currentCustomerID;
var currentPlaylistID;
var currentCategoryID;
var autoPlayVPModule = false;
var autoPlayQuicklist = false;
var nextMedia;

var didPlayAd = false;
var addedPlaylistCount = 0;
var responseCounter = 0;

var loadComplete = false;

var returnthing;

function onTemplateLoaded(experienceID) {

	bcExp =		brightcove.getExperience(experienceID);
	modVP =		bcExp.getModule(APIModules.VIDEO_PLAYER);
	modExp =	bcExp.getModule(APIModules.EXPERIENCE);
	modCon =	bcExp.getModule(APIModules.CONTENT);
	
	modExp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
	modCon.addEventListener(BCContentEvent.MEDIA_COLLECTION_LOAD, onMediaCollectionLoad);
}

function onTemplateReady(event) {
	comboBox = modExp.getElementByID("playlistCombo");
	comboBox.setLabel("loading media...");

	// cue the current media on it's preview
	//if (!autoPlayVPModule) modVP.cueVideo(currentReference, "id");

	//---------------------- Progress handling --------------------//
	modVP.addEventListener(BCVideoEvent.VIDEO_COMPLETE, onVideoComplete);
	//if (InSkinParams) modVP.addEventListener(BCVideoEvent.VIDEO_START, onVideoStart);
	//if (InSkinParams) modVP.addEventListener(BCVideoEvent.START_BUFFER, onVideoStart);
	modExp.getElementByID("videoList").addEventListener("elementClick", videoListClick);

	loadPlaylists();
}

/// loads the required playlists asynchronously
function loadPlaylists() {
	var playlistRequestURL = "/JSON/playlist.ashx?";
	if (currentMediaID) playlistRequestURL += "mid=" + currentMediaID + "&";
	if (currentUserID) playlistRequestURL += "uid=" + currentUserID + "&";
	if (currentCategoryID) playlistRequestURL += "catid=" + currentCategoryID + "&";
	if (currentPlaylistID) playlistRequestURL += "pid=" + currentPlaylistID + "&";
	if (currentCustomerID) playlistRequestURL += "cid=" + currentCustomerID + "&";

	var timeoutReloadPlaylist = setTimeout(loadPlaylists, 10000);
	$.getJSON(playlistRequestURL, function(data) {
		clearTimeout(timeoutReloadPlaylist);
		playlists = data;
		$.each(playlists.items, function(i, item) {
			item.loaded = false;
			modCon.getMediaInGroupAsynch(item.mediaIds);
		});
	});
}

/// tileList click handler
function videoListClick(event) {
	var newMediaID = BCRefToTSID(event.elementData.referenceId);
	var playlistIndex = comboBox.getSelectedIndex();
	var playlistID = loadedPlaylists[playlistIndex].id
	if (playlistID <= 0)
		playlistID = null;
	MEview.redirectToVideo(newMediaID, playlistID);
	setTimeout(function() { modExp.unload() }, 10);
}
/*
var inSkinInit = false;
function onVideoStart(event)
{
	if (!inSkinInit) {
		InSkinLoad.init(InSkinParams);
		inSkinInit = true;
	}
}
*/
function onVideoComplete(event) {
	if (autoPlayQuicklist) {
		MEview.quicklistMove(1);
	}
	else if (autoPlayVPModule && nextMedia != null) {
		MEview.redirectToVideo(nextMedia, currentPlaylistID);
		setTimeout(function() { modExp.unload() }, 10);
	}
}

/// onMediaCollectionLoad handler for getMediaInGroupAsynch request
function onMediaCollectionLoad(event) {
	if (event.mediaCollection == null) {
		// Do nothing because no results came back. Must have been all disabled videos. 
	}
	else {
		// -ve ids are returned for getMediaInGroupAsynch
		if (event.mediaCollection.id < 0) {
			loadMediaCollection(event.mediaCollection);
		}
	}
}

/// loads a mediacollection into the comboBox dropdown
function loadMediaCollection(mediaCollection) {
	$.each(playlists.items, function(i, val) {
		// find which playlist the returned collection matches
		if (arrayMatch(val.mediaIds, mediaCollection.mediaIds)) {
			if (!playlists.items[i].loaded) {
				var playlist = {
					displayName: val.displayName,
					mediaIds: mediaCollection.mediaIds
				};
				
				// add the playlist to the dropdown
				addDropDown(playlist);

				playlists.items[i].loaded = true;
				loadedPlaylists[responseCounter] = playlists.items[i];
				responseCounter++;
			}
		}
	});
	// if we've finished loading all the playlists
	if (responseCounter == playlists.items.length) {
		// loading the combobox resets the current video for some reason

		comboBox.setSelectedIndex(0);
		if (!currentCustomerID) { // customer media doesn't feature the active video in the playlist
			var videoList = modExp.getElementByID("videoList");

			var clipArray = videoList.getData();
			$.each(clipArray, function(i, val) {
				if (val.id == currentReference) {
					videoList.setSelectedIndex(i);

					// scroll and highlight the current media
					for (var vids = 0; vids < Math.floor(i / 3); vids++)
						videoList.showNextPage();
					// showPage tweens backwards....?
					// videoList.showPage(Math.floor(i / 3));

					if (autoPlayVPModule && clipArray.length > i + 1) {
						nextMedia = BCRefToTSID(clipArray[i + 1].referenceId);
					}
				}

			});
		}
		else
			modVP.play();
			
		// load the requested video
		// this doesn't do what it should..
		/*
		if (autoPlayVPModule)
		modVP.loadVideo(currentReference, "id");
		else {
		modVP.cueVideo(currentReference, "id");
		}
		*/
	}
}

/// called form the html frontend to prime the parameters
function setMedia(mediaid, reference, userID, customerID, playlistID, categoryID, autoStart) {
	currentMediaID = mediaid;
	currentReference = reference;

	currentUserID = userID;
	currentCustomerID = customerID;
	currentPlaylistID = playlistID;

	currentCategoryID = categoryID;
	autoPlayVPModule = autoStart;
}

function arrayMatch(a, b) {
	if (a.length != b.length) return false;
	for (var i = a.length; --i >= 0; )
		if (a[i] != b[i])
			return false;
	return true;
}

/// adds a playlist to the player dropdown
function addDropDown(playlist) {
	playlist.videoDTOs = new Array();
	for(var i = 0; i < playlist.mediaIds.length; i++) {
		playlist.videoDTOs.push(modCon.getVideo(playlist.mediaIds[i]));
	}
	var cmbArray = comboBox.getData();
	cmbArray.splice(addedPlaylistCount,0,playlist);
	comboBox.setData(cmbArray);
	addedPlaylistCount++;
}


function BCRefToTSID(reference)
{
	return reference.replace("meview_","");
}

function identify(element) {
	returnthing = element;
}