/* ########################################################################### *
/* ***** DOCUMENT INFO ******************************************************* *
/* ########################################################################### *
 * ##### NAME:  media.js
 * ##### VERSION: v1.0
 * ##### UPDATED: 22/01/09 (Damian Keeghan, Eclipse)
/* ########################################################################### *

/* ########################################################################### *
/* ***** INDEX *************************************************************** *
/* ########################################################################### *
/* ##### GLOBAL JS CONFIGURATION
/* ##### INITIALISATION
/* ##### TEG MEDIA PLAYER
/* ##### MODAL MEDIA PLAYER
/* #####
/* ##### MODAL WINDOW
/* ##### JQUERY & OTHER UTILITIES
/* ########################################################################### */

/* ########################################################################### *
/* ##### GLOBAL JS CONFIGURATION
/* ########################################################################### */

var ecl_videoPlayerWidth = 550;
var ecl_videoPlayerHeight = 308;

var ecl_flashAssetsPath = "/Style%20Library/teg/flash/";

//Original TEG Configuration
var DIV_HTML = "<div id='flashVideoPlaceholderWrapper'><div id='flashVideoPlaceholder'></div><div class='clearfix'><ul class='mediaLeftLinks'><li class='first'><a href='#'>View transcript</a></li></ul><ul class='mediaRightLinks'></ul></div></div>";
var DEMO_HTML = "<div id='flashDemoPlaceholderWrapper'><div id='flashDemoPlaceholder'></div></div>";
var WIDTH_RATIO = 0.5625;
var ecl_pauseOnLoad = true;	// Used by showVideo, showAudio, showDemo and below onReady function to determine if the media element being clicked is on page load.
var htmlNodes = '#flashVideoPlaceholderWrapper,#flashDemoPlaceholderWrapper';

// Because of IE bug need to explicitly remove the embed element.
if ($.browser.msie)
{
	htmlNodes = '#flashVideoPlaceholderWrapper,#flashVideoPlaceholderWrapper embed,#flashDemoPlaceholderWrapper,#flashDemoPlaceholderWrapper embed';	
}

/* ########################################################################### *
/* ##### INITIALISATION
/* ########################################################################### */

// Additional functionality for media pages executed on load.
$(document).ready(function(){
	//ecl_init_modalWindow();					   
	ecl_init_mediaPlayer();
	init_productSections();
});

$(window).load(function()
{
	// Get all media links
	var mediaLinks = $(".mediaList a:contains('Video:'),.mediaList a:contains('Audio:'),.mediaList a:contains('Flash:')");
	init_media(mediaLinks);
});

/* ########################################################################### *
/* ##### TEG MEDIA PLAYER
/* ########################################################################### */

function init_media(mediaLinks){
	// Add background to all media items to indicate expandability
	$(mediaLinks).parent().addClass("media");

	var primeMediaLinks = $(".prime a");
	
	// Activate the first (if any) video or audio element marked as prime
	if ($(primeMediaLinks).length > 0)
	{
		$(primeMediaLinks[0]).trigger('onclick');
		ecl_pauseOnLoad = false;
	}
	else
	{
		ecl_pauseOnLoad = false;
	}	
}

function showVideo (mediaUrl, downloadUrl, subscribeUrl, blogUrl, moreInformationUrl, insertafter) {
	var mediaHtmlNodes = $(htmlNodes);
	$(mediaHtmlNodes).remove();
	
	if (!mediaUrl) return true;
	if (!downloadUrl) return true;
	if (!insertafter) return true;
	if ($(insertafter).parent().hasClass('on')) {
		$(insertafter).parent().removeClass('on');
	}
	else {
		$('.mediaList li').removeClass('on');
		$(insertafter).parent().addClass('on');
		
		// Write the flashVideoPlaceholder in to this list item.
		$(insertafter).after(DIV_HTML);
		
		// Determine the Width and Height of the movie.
		movieWidth = $(insertafter).parent().width();
		movieHeight = Math.round(WIDTH_RATIO*movieWidth);
							
		// Set the width and height of the flashVideoPlaceholder div so we can still use transition effects. 	
		//$('#flashVideoPlaceholder').css({width: movieWidth, height: movieHeight});
			
		// Determine the href for the moviePlayer download link, and the "View the Transcript" link.
		transcriptHref = $(insertafter)[0].href;
		$('#flashVideoPlaceholderWrapper ul.mediaLeftLinks a')[0].href = transcriptHref;
		
		// If the video has a subscribe link, append it to the list
		if (subscribeUrl)
		{
			$('#flashVideoPlaceholderWrapper ul.mediaLeftLinks').append("<li><a href='" + subscribeUrl + "'>Subscribe</a></li>")
		}
		
		// If the video has a blog link, append it to the list
		if (blogUrl)
		{
			$('#flashVideoPlaceholderWrapper ul.mediaLeftLinks').append("<li><a href='" + blogUrl + "'>View blog</a></li>");
		}
		
		if (moreInformationUrl)
		{
			$('#flashVideoPlaceholderWrapper ul.mediaRightLinks').append("<li class='first'><a class='pdfLink' href='" + moreInformationUrl + "'>More Information</a></li>");
		}
		
		// Show the video (transition effects aren't working with the Flash)
		$('#flashVideoPlaceholderWrapper').show();
		
		// Write the flash movie over the flashVideoPlaceholder div.
		// Check if the video should pause on load (instead of auto playing, this is used for page load)
		if (ecl_pauseOnLoad)
		{
			$('#flashVideoPlaceholder').flash({
					src: ecl_flashAssetsPath+'videoPlayer.swf',
					width: movieWidth,
					height: movieHeight,
					allowFullScreen: "true",
					version: 8,
					flashvars: {
						displayWidth: movieWidth,
						displayHeight: movieHeight,
						videoFile: mediaUrl, 
						downloadLink: downloadUrl,
						pauseOnLoad: "true"
					}
				}
			);
		} 
		else 
		{
			$('#flashVideoPlaceholder').flash({
					src: ecl_flashAssetsPath+'videoPlayer.swf',
					width: movieWidth,
					height: movieHeight,
					allowFullScreen: "true",
					version: 8,
					flashvars: {
						displayWidth: movieWidth,
						displayHeight: movieHeight,
						videoFile: mediaUrl, 
						downloadLink: downloadUrl,
						pauseOnLoad: "false"
					}
				}
			);	
		}
	}
	if (insertafter.blur) insertafter.blur();
	// Return false to prevent the link click navigation occuring.
	return false;
}

function showAudio (mediaUrl, subscribeUrl, blogUrl, insertafter) 
{
	// Remove any already open content (audio, video or demo)
	// NB: Must remove the embed element else a bug in IE will continue to play the audio even though the wrapper element is removed (this only happens if the user scrubs the playback head).
	var mediaHtmlNodes = $(htmlNodes);
	$(mediaHtmlNodes).remove();
	
	if (!mediaUrl) return true;
	if (!insertafter) return true;
	if ($(insertafter).parent().hasClass('on'))
	{

		$(insertafter).parent().removeClass('on');
	}
	else 
	{
		$('.mediaList li').removeClass('on');
		$(insertafter).parent().addClass('on');
			
		// Write the flashVideoPlaceholder in to this list item.
		$(insertafter).after(DIV_HTML);
		
		// Set the width and height of the flashVideoPlaceholder div so we can still use transition effects. 	
		//$('#flashVideoPlaceholder').css({width: 265, height: 60});
			
		// Determine the href for the moviePlayer download link, and the "View the Transcript" link.
		transcriptHref = $(insertafter)[0].href;
		$('#flashVideoPlaceholderWrapper ul.mediaLeftLinks a')[0].href = transcriptHref;

		// If the audio has a subscribe link, append it to the list
		if (subscribeUrl)
		{
			$('#flashVideoPlaceholderWrapper ul.mediaLeftLinks').append("<li><a href='" + subscribeUrl + "'>Subscribe</a></li>")
		}
		
		// If the audio has a blog link, append it to the list
		if (blogUrl)
		{
			$('#flashVideoPlaceholderWrapper ul.mediaLeftLinks').append("<li><a href='" + blogUrl + "'>View blog</a></li>")
		}

		$('#flashVideoPlaceholderWrapper ul.mediaRightLinks').hide();
		
		// Show the video (transition effects aren't working with the Flash)
		$('#flashVideoPlaceholderWrapper').show();
		
		// Write the flash movie over the flashVideoPlaceholder div.
		// Check if the video should pause on load (instead of auto playing, this is used for page load)
		if (ecl_pauseOnLoad) 
		{	
			$('#flashVideoPlaceholder').flash(
				{
					src: ecl_flashAssetsPath+'audioPlayer.swf',
					width: 265,
					height: 60,
					version: 8,
					flashvars: {
						audioFile: mediaUrl,
						pauseOnLoad: "true"						
					}
				}
			);
		}
		else
		{
			$('#flashVideoPlaceholder').flash(
				{
					src: ecl_flashAssetsPath+'audioPlayer.swf',
					width: 265,
					height: 60,
					version: 8,
					flashvars: {
						audioFile: mediaUrl,
						pauseOnLoad: "false"
					}
				}
			);			
		}
	}
	if (insertafter.blur) insertafter.blur();
	// Return false to prevent the link click navigation occuring.
	return false;
}

function showDemo (mediaUrl, insertafter) 
{
	var mediaHtmlNodes = $(htmlNodes);
	$(mediaHtmlNodes).remove();
	
	if (!mediaUrl) return true;
	if (!insertafter) return true;
	if ($(insertafter).parent().hasClass('on')) {
		$(insertafter).parent().removeClass('on');
	}
	else {
		$('.mediaList li').removeClass('on');
		$(insertafter).parent().addClass('on');
		
		// Write the flashDemoPlaceholder in to this list item.
		$(insertafter).after(DEMO_HTML);
		
		$('#flashVideoPlaceholderWrapper ul.mediaRightLinks').hide();
		
		// Show the video (transition effects aren't working with the Flash)
		$('#flashDemoPlaceholderWrapper').show();
		
		// Write the flash movie over the flashVideoPlaceholder div.
		$('#flashDemoPlaceholder').flash(
			{
				src: mediaUrl,
				version: 8
			}
		);
	}
	if (insertafter.blur) insertafter.blur();
	// Return false to prevent the link click navigation occuring.
	return false;
}

/* ########################################################################### *
/* ##### PRODUCT SECTIONS
/* ########################################################################### */
var DEMO_FLASH = "<div id='flashDemoPlaceholderWrapper'><div id='flashDemoPlaceholder'></div></div>";

function init_productSections()
{
	$('.prodDetails').hide();
	$('.prodSubHead').addClass('expand');
	$('.prodSubHead:first').addClass('open');
	$('.prodSubHead:first').next('.prodDetails').show();
	
	// Find the H2.prodSubHead and give them the generic event handler.
	$('h2.prodSubHead').click(genericProdSubHead_Click);	
		
	// Find the H2 with a .prodDetails next, containing a .demo inside it.
	$('.prodSubHead').next('.prodDetails').find('.demoLink').each(function(){
		// We step up to the prodSection, then look for the first H2:
		var prodSectionH2 = $(this).parent().parent().parent().find('h2.prodSubHead')[0];
		
		// Remove the generic event handler, and attach the specific event handler.
 		$(prodSectionH2).unbind('click', genericProdSubHead_Click);
		$(prodSectionH2).click(demoProdSubHead_Click);
	});
}

function genericProdSubHead_Click ()
{
	//alert($(this)[0].innerHTML);
	if ($(this).hasClass('open')) {
		$(this).next('.prodDetails').hide();
		$(this).removeClass('open');
	}
	else {
		// Remove any playing demos
		$('#flashDemoPlaceholderWrapper').remove();
		// Remove any playing videos
		$('#flashVideoPlaceholderWrapper').remove();
		$('.mediaList li').removeClass('on');
		// Hide any open sections
		$('.prodDetails').hide();
		$('.prodSubHead').removeClass('open');
		// Show the clicked section
		$(this).next('.prodDetails').slideDown();
		$(this).addClass('open');
	}
}

function demoProdSubHead_Click ()
{
	if ($(this).hasClass('open')) {
		// Remove any playing demos
		$('#flashDemoPlaceholderWrapper').remove();
		// Remove any playing videos
		$('#flashVideoPlaceholderWrapper').remove();
		$('.mediaList li').removeClass('on');
		// Show the clicked section
		$(this).next('.prodDetails').hide();
		$(this).removeClass('open');
	}
	else {
		// Remove any playing demos
		$('#flashDemoPlaceholderWrapper').remove();
		// Remove any playing videos
		$('#flashVideoPlaceholderWrapper').remove();
		$('.mediaList li').removeClass('on');
		// Hide any open sections
		$('.prodDetails').hide();
		$('.prodSubHead').removeClass('open');
		//movieWidth = $(this).next('.prodDetails').width();
		demoUrlArray = $(this).next('.prodDetails').find('.demoLink').attr("href");
		$(this).next('.prodDetails').append(DEMO_FLASH);
		$('#flashDemoPlaceholderWrapper').show();
		
		// A collection of links contained in prodDetails that end in swf
		var countSWF = $(this).next('.prodDetails').find('a[href$=swf]').length;
		var hasSWFLink = countSWF > 0;
		// A collection of links contained in prodDetails that end in flv
		var countFLV = $(this).next('.prodDetails').find('a[href$=flv]').length;
		var hasFLVLink = countFLV > 0;
		
		if (hasSWFLink) {
			//alert('found a swf link');
			$('#flashDemoPlaceholder').flash({
					src: demoUrlArray,
					width: 450,
					version: 8
				}
			);
		}
		else if (hasFLVLink) {
			// Define the width and height of the movie.
			var WIDTH_RATIO = 0.5625;
			movieWidth = 450;
			movieHeight = Math.round(WIDTH_RATIO*movieWidth);
			//alert('found a flv link');
			$('#flashDemoPlaceholder').flash({
					src: ecl_flashAssetsPath+'videoPlayer.swf',
					width: movieWidth,
					height: movieHeight,
					allowFullScreen: "true",
					version: 8,
					flashvars: {
						displayWidth: movieWidth,
						displayHeight: movieHeight,
						videoFile: demoUrlArray				    
					}
				}
			);
		}
		
		
		$(this).next('.prodDetails').find('.demoLink').parent().hide();
		$(this).next('.prodDetails').show();
		$(this).addClass('open');
	}
}

/* ########################################################################### *
/* ##### MODAL MEDIA PLAYER
/* ########################################################################### */

function ecl_init_mediaPlayer()
{
	// Wire up the links
	$(".ecl_showMediaLink").each(function(){
		$(this).click(function(){
			ecl_launchMedia($(this).attr("href"), $(this).text());
			return false;
		});
	});
}

function ecl_launchMedia(href, title)
{
	// Grab the query string values from the <a> tag
	var queryVars = $.query(href);
	
	// Assign variables / flash params
	var mediaUrl = queryVars["videoUrl"];
	var downloadUrl = queryVars["downloadUrl"];
	var descriptionText = queryVars["description"];
	var moreUrl = queryVars["moreUrl"];

	var modalWidth = String(ecl_videoPlayerWidth+20)+"px";

	// Display media in modal window
	ecl_launchModalWindow(unescape(title), modalWidth, function()
  	{ 
		// Set the width and height of video - by setting the #contentContainer
		$("#contentContainer").width(String(ecl_videoPlayerWidth)+"px");
		$("#contentContainer").height(String(ecl_videoPlayerHeight)+"px");
		
		if(moreUrl!=undefined){
			$("#contentContainer").after("<p class='videoLink'><a href='"+moreUrl+"'>Find out more</a></p>");
		}
		
		if(descriptionText!=undefined){
			$("#contentContainer").after("<p class='videoDescription'>"+descriptionText+"</p>");
		}
		
		var height = $("#modalContainer").height()-20;
		var borderHeight = ($.browser.msie) ? height : height-1;
		
		if(descriptionText!=undefined){
			var borderHeight = ($.browser.msie) ? height : height+0.5;
		}
		
		$("#modalContainer .border_l, #modalContainer .border_r").height(borderHeight);	
		
		// Show the media in page
		showVideoInModal(mediaUrl, downloadUrl, "contentContainer", descriptionText, moreUrl);
  	});
	
	return false;	
}

function showVideoInModal(mediaUrl, downloadUrl, containerId){
	$("#" + containerId).hide();
	
	$("#" + containerId).flash({
			src: ecl_flashAssetsPath+'videoPlayer.swf',
			width: String(ecl_videoPlayerWidth)+"px",
			height: String(ecl_videoPlayerHeight)+"px",
			allowFullScreen: "true",
			version: 8,
			flashvars: {
				displayWidth: ecl_videoPlayerWidth,
				displayHeight: ecl_videoPlayerHeight,
				videoFile: mediaUrl, 
				downloadLink: downloadUrl,
				pauseOnLoad: "false"
			}
		}
	);	
	
	$("#" + containerId).show();
}

/* ########################################################################### *
/* ##### MODAL WINDOW
/* ########################################################################### */

// Modal window
function ecl_launchModalWindow(title, windowWidth, callBack)
{
	var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
	var borderHTML = (!badBrowser) ? '<div class="border_tl"></div><div class="border_tr"></div><div class="border_bl"></div><div class="border_br"></div><div class="border_t"></div><div class="border_b"></div><div class="border_l"></div><div class="border_r"></div>' : "";
	var modalHtml = borderHTML+'<div style="display:none"><a href="#" title="Close" class="modalCloseX modalClose">Close X</a><div class="content form-container"><h2 class="title"></h2><div class="loading" style="display:none"></div><div class="message" style="display:none"></div><div id="contentContainer"><p><strong>Sorry, you require the <a href="http://www.adobe.com/go/getflash">Adobe Flash</a> player to view this content.</strong></p><div id="buttonRow" class="hidden clearfix"><button id="buttClose" title="Close window" class="buttStandard modalClose">Close</button></div></div></div></div>';

	var modal = {
		message: null,
		open: function (dialog) {
			dialog.overlay.fadeIn(500, function () {
				
				// Set the width of the window
				$(dialog.container).width(windowWidth);

				// Set the title of the window
				$(dialog.container).find('h2.title').html(title);

				dialog.container.show();
				dialog.content.show();																	 
			
				// Execute the callBack function
				if (typeof callBack == "function")
				{
					// execute callBack function
					callBack();
				}
				$(dialog.container).find('#buttClose').focus();
				
			});
		},
		close: function (dialog) {
			$("#contentContainer").hide();
			
			dialog.content.hide();
			dialog.container.hide();
			dialog.overlay.fadeOut(500, function () 
				{
					$.modal.remove(dialog);
				});
		
		}
	};
	
	// create a modal dialog with the data
	$(modalHtml).modal({
		close: true,
		overlay: 70,
		overlayId: 'modalOverlay',
		containerId: 'modalContainer',
		iframeId: 'modalIframe',
		onOpen: modal.open,
		onClose: modal.close
	});

}


/* ########################################################################### *
/* ##### JQUERY & OTHER UTILITIES
/* ########################################################################### */

// Supply a query string and parse it into a key value pairs

jQuery.query = function(s) 
{
		var r = {};
		if (s) {
				var q = s.substring(s.indexOf('?') + 1); // remove everything up to the ?
				q = q.replace(/\&$/, ''); // remove the trailing &
				jQuery.each(q.split('&'), function() {
						var splitted = this.split('=');
						var key = splitted[0];
						var val = splitted[1];
						// convert numbers
						if (/^[0-9.]+$/.test(val)) val = parseFloat(val);
						// convert booleans
						if (val == 'true') val = true;
						if (val == 'false') val = false;
						// ignore empty values
						if (typeof val == 'number' || typeof val == 'boolean' || val.length > 0) r[key] = val;
				});
		}
		return r;
};


jQuery.fn.replaceWith = function(replacement) {
  return this.each(function(){
    element = $(this);
    $(this)
      .after(replacement).next()
      .attr('class', element.attr('class')).attr('id',element.attr('id'))
      .html(element.html())
      .prev().remove();
  });
};

/* FIN */