var player;
var menu_status = 'closed';
var bc_video = null;
var bc_player = null;
var content, exp;      
var videoList;  
var playlists = null;
var mediaElement = null;
var playlistElement = null;
var contentElement = null;
var debug = null;
var player = null;
var activePlaylistItem = 0;
var activeVideo = 0;
var PlaylistItem = 142;
var activePlaylist = null;
var Progress = 0;
var currentState = ['','',''];
var historyCounter = -1;
var addthis_pub = 'tategallery';
var stateengine = false;
var vplayerstate = true;
var pageTracker = null;


$(document).ready(function(){

	_gat._getTracker("UA-3117493-1");
	pageTracker._setDomainName(".tate.org.uk");
	pageTracker._trackPageview();
	
	configureAjax();
	
	
	contentElement = $('div#content div#contentElement');
	mediaElement = $('div#content div#mediaElement');
	playlistElement = $('div#content div#playlistElement');
	
	/// first we check if we have a bookmarked url
	var location = window.location.href;
	var hashl = location.indexOf('#');
	if (hashl > -1) {
		var hash = location.substring(hashl+1);
	}
	if (hashl > -1 && hash != '') {
			var check = setState(hash);
			//message('restoring state: '+hash);
			if (check[2] == '' & contentElement.length > 0) {
				contentSetup();
			}
			if (check[0] == '' & mediaElement.length > 0) {
				mediaSetup();
			}
			if (check[1] == '' & playlistElement.length > 0) {
				playlistSetup();
			}
	} else {
	
	
		
			
		if (contentElement.length > 0) {
		
			contentSetup();
		
		}
		
		
		// handle various states....
		
		if (mediaElement.length > 0) {
			// we are on a video page (build this into the series part page as well)
			mediaSetup();
		}
	

	
		if (playlistElement.length > 0) {	
			playlistSetup();
	
			// scrolling and clicking for playlist should be part of the content area parsing
			
		} else {
			// do we have playlists in the content area?
			var contentpl = contentElement.find('div.playlistBox');
			if (contentpl. length > 0) {
				loadPlaylistElement(contentpl.eq(0).find('h1 a').attr('href'));
			}
		}
		//loadPlayer(element);
	}
	
	// toggle if we're on a series page
	var synopsis = $('div.synopsis');
	if (synopsis.length > 0) {
		_activateToggle(synopsis);
	}

	
});


//////////////////////////////////////////////////////////
//
//	Setup
//
//////////////////////////////////////////////////////////
function playlistSetup() {
// activating playlist
	currentState[1] = playlistElement.attr('rel');
	
	// we are on a playlist page
	var playlist = playlistElement.find('li');
	if (playlist.length > 0) {
		activatePlaylist(playlist);
	}

}

function contentSetup() {
	currentState[2] = contentElement.attr('rel');
	setupContentLinks();
}

function mediaSetup() {
	message('media setup');
	_activateToggle(mediaElement);
	
	mediaElement.find('div.threeCol img').load(function(){
	//	message('image loaded');
		loadPlayer();
	});
	if(mediaElement.find('div.threeCol img')[0].complete){
		loadPlayer();
	}
	
	currentState[0] = mediaElement.attr('rel');
}

function AddThisSetup(elm,url,title) {
	if (elm.length > 0) {
		var id = elm.attr('id');
		addthis.button('#'+id, {username:"tategallery",ui_click:true }, {url:url,title:title});
		//message('add this init:'+id);
	} //else {
		//message('add this not init');
	//}
}


//////////////////////////////////////////////////////////
//
//	Content area
//
//////////////////////////////////////////////////////////

function loadContentElement(url,hurl) {
	var historyurl = hurl;
	
	$.ajax({
		data: {},
		success: function(data, textStatus) {
			contentElement.html(data);
			addHistory(historyurl,2);
			setupContentLinks();
			pageTracker._trackPageview(url);
		},
		error: function() {
			message('error loading content');
			// we load the default playlist screen
			$.get('/channel/playlists.ajax',function(data){
				contentElement.html(data);
				addHistory('/channel/playlists',2);
				setupContentLinks();
			});

		},
		dataType: 'html',
		url: url,
		type: 'GET'
	});
	
	
	//contentElement.load(url,function(){
	//	addHistory(historyurl,2);
	//	setupContentLinks();
	//});

}


function setupContentLinks() {


	// menu links and pager links
	contentElement.find('ul.searchLinks:not(.links) a').add('ul.paginator a').click(function(me){
		me.preventDefault();
		var url = $(this).attr('href');
		var add = '';
		// don't parse external links
		if (url.indexOf('://') == -1) {
			if ($(this).html().indexOf('elated') > -1) {
				// the related link has been clicked
				add = '?video='+activeVideo;
			}
			if (url.indexOf('?') > -1) {
				// we have parameters... cut them off and feed them into add
				add = url.substr(url.indexOf('?'));
				url = url.substring(0,url.indexOf('?'));
			}
			loadContentElement(url+'.ajax'+add,url+add);
			//contentElement.load(url+'.ajax'+add,function(){
			//	addHistory(url+add,2);
			//	setupContentLinks();
			//});
	
		}
		
		return false;
	});

	// search box
	var sf = contentElement.find('div.search').parent();
	sf.submit(function(me){
		me.preventDefault();
		var url = sf.attr('action');
		var query = '?'+sf.serialize();
		//message(url+'.ajax'+query);
		loadContentElement(url+'.ajax'+query,url+query);
		//contentElement.load(url+'.ajax'+query,function(){
		//	addHistory(url+query,2);
		//	setupContentLinks();
		//});
		return false;
	});

	// video links
	contentElement.find('div.videoBox').each(function(){
		var pobj = $(this);
		pobj.find('a').click(function(me){
			me.preventDefault();
			var obj = $(this);
			var url = obj.attr('href');
			
			// we need to check if this is a series we're clicking on
			if (pobj.attr('rel') != '') {
				loadPlaylistElement(url);
			} else {
				loadMediaElement(0,url);
			}			
			
	
			
			return false;
		});
	});
	
	
	
	
	// playlist elements
	var playlists = $('div#contentElement ul.videoStrip');
	if (playlists.length > 0) {
		var counter = 1;
		playlists.each(function(){
			var url = $(this).parent().find('h1 a').attr('href');
			$(this).parent().find('a').click(function(me){
				//message('click');
				var id = $(this).attr('rel');
				me.preventDefault();
				loadPlaylistElement(url,id);
				return false;
			});
			activateScrolling($(this).find('li'),counter);
			counter++;
		});
			
			
		
	}
	
}

//////////////////////////////////////////////////////////
//
//	History and url handling
//
//////////////////////////////////////////////////////////


function setState(newLocation) {
	message('settingState' + newLocation +', '+stateengine);
	//message(newLocation == null);
	
	stateengine = true;
	message('setting state engine to true');
	var mediaoverride = false;
	if (newLocation != null && newLocation != '') {
		newState = parseAddress(newLocation);
			
		//if (newState[0] != '') {
			// we can only do this when we've got at least a complete media state
			if (newState[2] != currentState[2] && newState[2] != '') {
				message('setting context: '+newState[2]);
				var url = newState[2]+'.ajax';
				var curl = newState[2];
				//message('context after: '+url);
				if (newState[2].indexOf('?') > -1) {
					var add = newState[2].indexOf('?');
					url = newState[2].substring(0,add) + '.ajax' + newState[2].substring(add);
				}
				//message('context after2: '+url);
				loadContentElement(url,curl);
				//contentElement.load(url,function(){
				//	setupContentLinks();
				//});
				//addHistory(curl,2);
			}
			
			
			if (newState[1] !== currentState[1]) {
				message('different playlist :'+newState[1]);
				//message(currentState[1]);
				if (newState[1] == '') {
					if (activePlaylist != null) {
						removeActivePlaylist();
					}
				} else {
					// here we should pass the movie id so we avoid loading the media element twice
					// look for last slash and take the end bit
					if (newState[0] != '') {
						
						var movieid = newState[0].substring(newState[0].lastIndexOf('/')+1);
						mediaoverride = true;
						message('loading playlist with movie id'+movieid);
						loadPlaylistElement(newState[1],movieid);
					} else {
						message('loading playlist without movie id');
						loadPlaylistElement(newState[1]);
					}
				}
			}
			
			
			
			if (newState[0] != currentState[0] && newState[0] && mediaoverride == false) {
				message('url loading video');
				// video has changed
				brightcove.removeExperience(player);
				loadMediaElement(0,newState[0]);
				// we also need to check if there is a playlist and we need to highlight in the playlist
				if (activePlaylist != null) {
					// we have a playlist 
					findVideoInActivePlaylist(newState[0]);
				}
			} 
		//}
		stateengine = false;
		return newState;
	}
	stateengine = false;
	message('setting state engine to false');
	//}
}

function HistoryEvent(newLocation,historyData) {
	message('HistoryEvent received from history object...'+newLocation+' , '+historyData+' , '+historyCounter);
	//console.log(historyData);
	if (newLocation != null && newLocation != '') {

		//message("A history change has occured:\n newLocation=" + newLocation + "\n historyData="+historyData);
		if (stateengine == false) {
			setState(newLocation);
		}

				
	}
}

function parseAddress(newLocation) {
	//message('parsing: '+newLocation);
	var output = ['','','']
	var nl = newLocation.split('&');
	var nll = nl.length;
	//message(nll);
	for(var i=0; i< nll; i++) { 
		message(nl[i]);
		var value = nl[i].split(':');
		message(value[0]);
		if (value[0] == 'media') {
			output[0] = value[1];
		} else if (value[0] == 'list') {
			output[1] = value[1];
		} else if (value[0] == 'context') {
			output[2] = value[1];
		}
	}
	message(output[0] + ','+output[1]+','+output[2]);
	return output;
}



function addHistory(what,where) {
	//message('add History called with: '+what+', '+where);
	// here we receive any change on the page
	// the entry in the history object needs to be the complete url though
	
	// #/1231123123./tate-channel/playlist/123213123./tate-channel/artist-interviews?video=&p=1&sort=popularity
	
	// default content is most popuplar
	//message('state: '+currentState.join('.'));
	if (what.indexOf(':') > -1) {
		var split = what.split('=');
		what = split[1];
	}
	
	
	currentState[where] = what;
	//message(dhtmlHistory.getCurrentLocation());
	//message(dhtmlHistory.getCurrentHash());
	
	if (where != 1) {
		//message('newHistory: '+formatURL());
		dhtmlHistory.add(formatURL(),where);
	}
}

function formatURL() {
	var output = [];
	currentState[0] == '' ? media = '' : output.push('media:'+currentState[0]);
	currentState[1] == '' ? list = '' : output.push('list:'+currentState[1]);
	currentState[2] == '' ? context = '' : output.push('context:'+currentState[2]);
	
	return output.join('&');
}


//////////////////////////////////////////////////////////
//
//	Playlists and series
//
//////////////////////////////////////////////////////////

function findVideoInActivePlaylist(vidid) {
	if (activePlaylist != null) {
		var found = -1;
		var counter = 0;
		activePlaylist.each(function(){
			if ($(this).find('a').attr('href').indexOf(vidid) > -1) {
				found = counter;
			}
			counter++;
		});
		if (found != -1) {
			scrolltoPlaylistitem(activePlaylist.parent(),found);
			PlaylistVideoActive(activePlaylistItem,found);
			activePlaylistItem = found;
		} else {
			// it's not in this playlist so remove playlist
			removeActivePlaylist();
		}
	}
}

function removeActivePlaylist() {
	activePlaylist = null;
	activePlaylistItem = 0;
	playlistElement.remove();
	playlistElement = [];
	currentState[1] = '';
	/// more code here just solve the loading of a playlist first.... we might need some more variables to differentiate between the active one and the ones in the list
}

function loadPlaylistElement(url,id) {
	//message('loading playlist element'+id);
	var movieid = id;
	if (playlistElement.length < 1) {
		if (mediaElement.length < 1) {
			$('div#content div.hr').after('<div class="outerBox" id="playlistElement"></div>');
		} else {
			mediaElement.after('<div class="outerBox" id="playlistElement"></div>');
		}
		playlistElement = $('div#content div#playlistElement');
		playlistElement.hide();
	}
	
	$.ajax({
		data: {},
		success: function(data, textStatus) {
			playlistElement.html(data);
			var playlist = playlistElement.find('li');
			if (playlist.length > 0) {
				if (movieid != null && movieid != '') {
					message('activating with movie id');
					activatePlaylist(playlist,movieid);
				} else {
					activatePlaylist(playlist);
				}
				if(playlistElement.is(":hidden")){
					playlistElement.slideDown(500);
				}
			}
			var synopsis = playlistElement.find('div.synopsis');
			if (synopsis.length > 0) {
				_activateToggle(synopsis);
			}
			addHistory(url,1);
			pageTracker._trackPageview(url+'.ajax');
		},
		error: function() {
			message('error loading playlist element');
			// we don't do anything except set the playlist history to 0
			addHistory('',1);

		},
		dataType: 'html',
		url: url+'.ajax',
		type: 'GET'
	});
	
	
	
/*	playlistElement.load(url+'.ajax',function(){
		var playlist = playlistElement.find('li');
		if (playlist.length > 0) {
			if (movieid != null && movieid != '') {
				message('activating with movie id');
				activatePlaylist(playlist,movieid);
			} else {
				activatePlaylist(playlist);
			}
			if(playlistElement.is(":hidden")){
				playlistElement.slideDown(500);
			}
		}
		var synopsis = playlistElement.find('div.synopsis');
		if (synopsis.length > 0) {
			_activateToggle(synopsis);
		}
		addHistory(url,1);
	});*/
	
}


function activateScrolling(playlist,counter) {
	if (playlist.length > 3) {
		playlist.parent().width((playlist.length*PlaylistItem)+'px');
		
		playlist.parent().wrap('<div id="videoStripWrap'+counter+'" style="width:426px;float:left;overflow:hidden;"></div>');

		var strip = playlist.parent().parent().parent().find('div#videoStripWrap'+counter);
		var stripul = strip.find('ul');
		stripul.attr('rel','idle');
		var stripnav = strip.prev();
		//message(strip);
		//message(strip.prev());
		stripnav.append('<ul><li><a class="back" id="videoStripBack'+counter+'"></a></li><li><a id="videoStripFwd'+counter+'"></a></li></ul><p>Use the buttons above to scroll.</p>');
		
		var back = stripnav.find('li a#videoStripBack'+counter);
		var fwd = stripnav.find('li a#videoStripFwd'+counter);
		
		back.click(function(me){
			me.preventDefault();
			// parse px away
			var curpos = _parsePos(stripul.css('margin-left'));
			if (stripul.attr('rel') == 'idle') {
				if (curpos != 0) {
					//stripul.css('margin-left',(curpos + PlaylistItem)+'px');
					stripul.attr('rel','animating');
					stripul.animate( { marginLeft:(curpos + PlaylistItem)+'px' }, 200, function(){
						stripul.attr('rel','idle');
					});
				}
			}
			return false;
		});
		fwd.click(function(me){
			me.preventDefault();
			var curpos = _parsePos(stripul.css('margin-left'));
			//message('fwd: '+curpos);
			//message(-(PlaylistItem*playlist.length) - (3*PlaylistItem));
			if (stripul.attr('rel') == 'idle') {
				if (curpos != -((PlaylistItem*playlist.length) - (3*PlaylistItem))) {
					//stripul.css('margin-left',(curpos - PlaylistItem)+'px');
					stripul.attr('rel','animating');
					stripul.animate( { marginLeft:(curpos - PlaylistItem)+'px' }, 200, function(){
						stripul.attr('rel','idle');
					});
				}
			}
			return false;
		});
		
	}
	
}



function scrolltoPlaylistitem(stripul,pos) {
	var curpos = _parsePos(stripul.css('margin-left'));
	//message('scrollto: '+ curpos);
	//message(pos);
	// need to limit the scrolling so we don't scroll further than the third last
	if (pos > activePlaylist.length - 3) {
		pos = activePlaylist.length -3;
	}
	
	stripul.attr('rel','animating');
	stripul.animate( { marginLeft:-(PlaylistItem*pos)+'px' }, 200, function(){
		stripul.attr('rel','idle');
	});
	
}



function activatePlaylist(playlist,movieid) {
	// activate scrolling
	activateScrolling(playlist,0);
	activePlaylist = playlist;
	avideo = 0;
	
	if (movieid != null) {
		var counter = 0;
		activePlaylist.each(function(){
			if ($(this).find('a').attr('href').indexOf(movieid) > -1) {
				avideo = counter;
			}
			counter++;
		});
	
	}
	var video = playlist.eq(avideo);
	
	loadMediaElement(video);
	
	PlaylistVideoActive(0,avideo);
	var stripul = playlist.parent();
	var counter = 0;
	if (avideo != 0) {
		scrolltoPlaylistitem(stripul,avideo);
	}
	playlist.each(function(){
		var video = $(this);
		var cnt = counter;
		$(this).find('a').click(function(me){
			me.preventDefault();
			
			brightcove.removeExperience(player);
			// some loader here
			scrolltoPlaylistitem(stripul,cnt);
			PlaylistVideoActive(activePlaylistItem,cnt);
			activePlaylistItem = cnt;
			
			loadMediaElement(video);
			return false;
		});
		counter++;
	});	

}

function PlaylistVideoActive(last,next) {
	activePlaylist.eq(last).find('img').css('opacity',1);
	activePlaylist.eq(next).find('img').css('opacity',.2);
}

function loadMediaElement(video,url) {
	
	message('Loading media element');
	
	if (mediaElement.length < 1) {
		$('div#content div.hr').after('<div class="outerBox" id="mediaElement"></div>');
		mediaElement = $('div#content div#mediaElement');
		mediaElement.hide();
	}
	
	
	if (url == null) {	
		var url = video.find('a').attr('href');
	} else {
		var url = url;
	}
	
	// make sure we are not already playing this video
	if (url.indexOf('activeVideo') == -1) {
		if (bc_video != null) {
			// hide the current video
			bc_video.setAlpha(0);
		}
		findVideoInActivePlaylist(url);
		
		
		//message(bc_player);
		if (mediaElement.find('h1').length > 0 && bc_player != null) {
			 // we've got an existing one so we're not loading everything new but we're 
			 // just chaning existing content
			//bc_video.closeMenuPage();
	
			message('were not refreshing the page');
			mediaElement.after('<div id="dummy" style="display:none;"></div>');
			
			var longdesc = mediaElement.find('div.longdescription');
			var desctoggle = mediaElement.find('div.view a');
			desctoggle.attr('rel','closed');
			longdesc.hide();
			desctoggle.html('view long description');
			
		
			
			
			var holder = $('div#dummy');
			holder.load(url+'.ajax',function(){
				addHistory(url,0);
				pageTracker._trackPageview(url);
				// here we're changing the media holder content
				mediaElement.find('div.shortdescription').html($(this).find('div.shortdescription').html());
				mediaElement.find('div.longdescription').html($(this).find('div.longdescription').html());
								
				// set page title
				//$('title').html('Tate Channel: '+mediaElement.find('div.shortdescription h1').html());
				document.title = 'Tate Channel: '+mediaElement.find('div.shortdescription h1').html();
				
				// we have to find the url using our url script
				AddThisSetup(mediaElement.find('a.addthislink'),'http://channel.tate.org.uk'+url,'Tate Channel: '+mediaElement.find('h1').html());
				// this loads the new movie
				onTemplateReady();
				
				setTimeout(function(){_removeElement(holder);},100);
			});
			
			
		} else {
			message('we are refreshing the page');
			mediaElement.load(url+'.ajax',function(){
				// call back
				//loadPlayer();
				_activateToggle(mediaElement);
				mediaElement.find('div.threeCol img').load(function(){
					addHistory(url,0);
					if(mediaElement.is(":hidden")){
						mediaElement.slideDown(500,function(){
							//$('title').html('Tate Channel: '+mediaElement.find('div.shortdescription h1').html());
							document.title = 'Tate Channel: '+mediaElement.find('div.shortdescription h1').html();
							loadPlayer();
						});
					} else {
						//$('title').html('Tate Channel: '+mediaElement.find('div.shortdescription h1').html());
						document.title = 'Tate Channel: '+mediaElement.find('div.shortdescription h1').html();
						loadPlayer();
					}
					// we have to find the url using our url script
					AddThisSetup(mediaElement.find('a.addthislink'),'http://channel.tate.org.uk'+url,'Tate Channel: '+mediaElement.find('h1').html())
				});
				pageTracker._trackPageview(url);
			});
		}
		
		
		
	}
	scrollUp();
}


//////////////////////////////////////////////////////////
//
//	Debugging
//
//////////////////////////////////////////////////////////

function message(message) {
	/*if (debug == null) {
	 	$('body').prepend('<div id="debug" style="position:absolute;top:0;left:400px;z-index:1000;background:#000;padding:10px;width:500px;overflow:hidden;"><p><b>DEBUG</b></p></div>');
	 	debug = $('div#debug');
	 	debug.click(function(){
	 		if (debug.height() < 100) {
	 			debug.css('height','auto');
	 		} else {
	 			debug.css('height','10px');
	 		}
	 	
	 	});
	}
	//document.getElementById("message").innerHTML = document.getElementById("message").innerHTML +'<br />'+ message;
	//console.log(message);
	debug.append('<p>'+message+'</p>');*/
}

//////////////////////////////////////////////////////////
//
//	Helper functions
//
//////////////////////////////////////////////////////////

function configureAjax() {
	$.ajaxSetup({
		error:function(x,e,a,t){
			if(x.status==0){
				message('AJAX: You are offline!!\n Please Check Your Network.');
			}else if(x.status==404){
				return 'Could not find URL';
				message('AJAX: Requested URL not found.');
			}else if(x.status==500){
				message('AJAX: Internal Server Error.');
			}else if(e=='parsererror'){
				message('AJAX: Error.\nParsing JSON Request failed.');
			}else if(e=='timeout'){
				message('AJAX: Request Time out.');
			}else {
				message('AJAX: Unknow Error.\n'+x.responseText);
			}
		}
	});
}


function scrollUp() {
	var targetOffset = $('div#content').offset().top;
	var bodyOffset = $('html').scrollTop() == 0 ? $('body').scrollTop() : $('html').scrollTop();
	if (bodyOffset > targetOffset) {
		$('html,body').animate({scrollTop: targetOffset}, 1000);
	}
}

function _removeElement(which) {
	which.remove();
}

function _activateToggle(element) {
	// short / long description toggle
	// <div class="view"><span class="viewInner"><a href="#">view short description</a></span></div>
	var longdesc = element.find('div.longdescription');
	//message('toggle'+longdesc);
	longdesc.after('<div class="view"><span class="viewInner"><a href="#">view long description</a></span></div>');
	var desctoggle = element.find('div.view a');
	desctoggle.attr('rel','closed');
	longdesc.hide();
	desctoggle.click(function(me){
		me.preventDefault();
		if (desctoggle.attr('rel') == 'closed') {
			desctoggle.attr('rel','open');
			longdesc.slideDown(200);
			desctoggle.html('view short description');
		} else {
			desctoggle.attr('rel','closed');
			longdesc.slideUp(200);
			desctoggle.html('view long description');
		}
		return false;
	});
}

function _parsePos(pos) {
	if (pos.indexOf('px')) {
		pos = parseInt(pos.substr(0,pos.indexOf('px')));
	}
	return pos;
}

function _isiPhone() { 
	var agent = navigator.userAgent.toLowerCase(); 
	return agent.match(/iPhone/i); 
} 

//////////////////////////////////////////////////////////
//
//	Brightcove player setup and event handling
//
//////////////////////////////////////////////////////////


function onTemplateLoaded(id)    {
	//message("EVENT: templateLoaded");

	bc_player = brightcove.getExperience(id);
	bc_video = bc_player.getModule(APIModules.VIDEO_PLAYER);
	bc_content = bc_player.getModule(APIModules.CONTENT);
	bc_menu = bc_player.getModule(APIModules.MENU);
	bc_exp = bc_player.getModule(APIModules.EXPERIENCE);
	//bc_social = bc_player.getModule(APIModules.SOCIAL);
	bc_exp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
	bc_video.addEventListener(BCMediaEvent.BUFFER_BEGIN, onVideoLoad);
	bc_video.addEventListener(BCMediaEvent.COMPLETE, onVideoComplete);
	bc_video.addEventListener(BCMediaEvent.CHANGE, onMediaChange);
	bc_video.addEventListener(BCMediaEvent.PROGRESS, onMediaProgress);
	bc_menu.addEventListener(BCMenuEvent.MENU_PAGE_CLOSE,onMenuPageClose);
	bc_menu.addEventListener(BCMenuEvent.MENU_PAGE_OPEN,onMenuPageOpen);
	bc_menu.addEventListener(BCMenuEvent.VIDEO_REQUEST,onVideoRequest);
	bc_video.addEventListener(BCMediaEvent.BEGIN,onVideoBegin);
		
	//bc_video.addEventListener(BCMediaEvent.MENU_PAGE_OPEN, onMenuPageOpen);
}

function onVideoBegin(e) {
	message('EVENT: video begin');
	if(vplayerstate == false && menu_status == 'open') {
		bc_menu.closeMenuPage();
	}
	vplayerstate = true;
}

function onVideoRequest(e) {
	message('MENUE: video request'+e.args['id']);
	//console.log(e);
	//$.get('/system/find-url.ajax?id='+e.args['id'],function(data){
	var currentVideo = bc_video.getCurrentVideo();
	message('---- current Video: '+currentVideo.id);
	$.ajax({
		data: {},
		success: function(data, textStatus) {
			if (data.indexOf('ould') != -1) {
				// page could not be found
				message('video not found');
			} else {
				message('loading video element from data');
				loadMediaElement(0,data);
			}
		},
		error: function() {
			message('error received');
			$.get('/system/find-url.ajax?id='+currentVideo.id,function(data){
				loadMediaElement(0,data);
			});

		},
		dataType: 'html',
		url: '/system/find-url.ajax?id='+e.args['id'],
		type: 'GET'
	});
	
	
	/*$.get('/system/find-url.ajax?id=23',function(data){
		message(data);
		if (data.indexOf('ould') != -1) {
			// page could not be found
			message('video not found');
		} else {
			message('loading video element from data');
			loadMediaElement(0,data);
		}
	
	});*/
}

function onMenuPageClose(e) {
	message('MENUE: page close');
	menu_status = 'closed';
	
}

function onMenuPageOpen(e) {
	message('MENUE: page open :'+vplayerstate);
	menu_status = 'open';
	
	
}
function onMediaProgress(e) {
	//message(bc_video.getVideoPosition());
	Progress = bc_video.getVideoPosition();
}

function onTemplateReady(e) {
	message('EVENT: Template ready :');
	// this assigns a video to the player once the template is ready for the first time 
	var vid = mediaElement.find('h1').attr('rel');
	// we set the video playerstate to false so we know where not supposed to open the menu screen
	vplayerstate = false;
	if(vplayerstate == false && menu_status == 'open') {
		bc_menu.closeMenuPage();
	}
	if (vid != '' && vid != null) {
		bc_video.loadVideo(vid);
		//bc_social.setLink("http://channel.tate.org.uk/media/"+vid)
		activeVideo = vid;
		
		
	}	
	
	//video.loadVideo(22448950001);
}


function onVideoComplete(e) {
	// is fired if the video is finished... we need this for the symposia player
	// which shouldn't show the element at the end but instead just switch to the next video
	// here it describes how to make a single player which supports a playlist:
	// http://developer.brightcove.com/en/articles/playlist-support-single-video-players
	// good for layout changes:
	// http://support.brightcove.com/en/docs/components-player-templates
	
	// here we replicate the playlist functionality in javascript, eg load the next video including content
	message('EVENT: Video is finished: '+parseInt(bc_video.getVideoDuration() - Progress));
	//message(Progress);
	//message(bc_video.getVideoDuration());
	//message(bc_video.getCurrentVideo().id);
	// check here if it is really finished....
	//message(bc_video.getVideoPosition());
	//message(bc_video.getVideoDuration());
	if (parseInt(bc_video.getVideoDuration() - Progress) < 2) {
		
		//message('playlist length: '+activePlaylist.length);
		// if we have a playlist
		if (activePlaylist.length > 0) {
			// which is the current active one
			//message('active playlist item:'+activePlaylistItem);
			//message(activePlaylist.length);
			if (activePlaylistItem+1 < activePlaylist.length) {
				var video = activePlaylist.eq(activePlaylistItem + 1);
				PlaylistVideoActive(activePlaylistItem,activePlaylistItem + 1);
				activePlaylistItem = activePlaylistItem+1;
				var strip = activePlaylist.parent().parent();
				var stripul = strip.find('ul');
				scrolltoPlaylistitem(stripul,activePlaylistItem);
				loadMediaElement(video);
							
			}
		}
	} else {
		bc_video.seek(Progress);
		bc_video.play();
	}
}

function onVideoLoad(evt) {
    message("EVENT: Video loaded ");
	if (bc_video.getAlpha() == 0) {
		// show the current video
		bc_video.setAlpha(1);
		// video loaded now we're alowed to use the menu again
		
	}
	
    //console.log(evt);
 	// we can do stuff such as load the other content
}

function onMediaChange(evt) {
	message('EVENT: media change event');
	message('---- active Video: '+activeVideo);
	var currentVideo = bc_video.getCurrentVideo();
	message('---- current Video: '+currentVideo.id);
	
	
	// here we can check if we just changed a video in our playlist or if it's a different way of switching the video
	
	//message(activeVideo);
	//message(activePlaylistItem);
	//message(currentVideo.id);
	
	// we need to parse the video id
	var video = activePlaylist.eq(activePlaylistItem);
	message('---- playlistVideo: '+video);
	if (activeVideo != 0) {
		// otherwise it's the first video played on this page
		if (video.find('a').attr('rel') == currentVideo.id || activeVideo == currentVideo.id) {
			message('Normal video change');
		} else {
			message('new video out of contenxt: '+currentVideo.id);
			// simply trigger load page to load new player area... check what to remove and what to add
			// maybe we can do that when we've implemented the url thing as we need to have a function to parse
			// a series sub page of the url anyway
			
		}
	}
	
}



function loadPlayer() {
	// this dynamically adds the player to the page....
	// assigning playlists works differently but I think instead of playlists you can also give a list of videos which means that 
	// we can use the same functionality for the symposia player
	
	
	message('loading player');
	element = mediaElement.find('div.playerBox');
	
	
	
	var vid = mediaElement.find('h1').attr('rel');
	element.attr('id','player'+vid);
	var h = element.find('img').height();
	if (h == null) {
		h = 418;
	}
	
	// check if we're on an iphone / ipod browser
	///message(_isiPhone());
	if (_isiPhone() == 'iphone') {
		var dl = mediaElement.find('a.downloadlink').attr('href');
		// we need an overlay here instead of just wrapping the link around the image.
		if (dl != null && dl != '') {
			element.find('img').wrap('<a href="'+dl+'"></a>');
		}
		var vid = mediaElement.find('h1').attr('rel');
		activeVideo = vid;
	
	} else {
	
		element.wrap('<div style="padding:0 5px 0 5px;background-color:#454544;height:'+h.toString()+'px;"></div>');
	
		
		var params = {};
		params.playerID = "28915011001";
		params.publisherId = "1854890877";
		//params.videoId = vid.toString();
		params.autoStart = "true";
		params.bgcolor = "#171716";
		params.width = "558";
		params.isVid = "true";
		params.height = h.toString();
		//params.isVid = "true";
		bc_player = brightcove.createElement("object");
		bc_player.id = 'player'+vid;
		var parameter;
		for (var i in params) {
			 parameter = brightcove.createElement("param");
			 parameter.name = i;
			 parameter.value = params[i];
			 bc_player.appendChild(parameter);
		}	
		brightcove.createExperience(bc_player,element[0],true);
	
	}
	
}

function loadDifferentVideo(videoId) {
	bc_video.loadVideo(videoId);
}


