/**
 * @file aut0poietic-media.js
 * Part of the aut0poietic-media WordPress plugin.
 * @version v2.0 
 * @requires:
 *		jQuery JavaScript Library v1.4.2 http://jquery.com/
 *		SWFObject v2.2 <http://code.google.com/p/swfobject/>
 */ 

// Ignore this "console" code. It just keeps IE happy when I'm debugging.
if( !console ) { var console = { } ; console.debug = function( ) { } ;  console.log = function( ) { } ; }


// POST-FIX properties to locate items by ID
var object_str 			= 	"_videoObject" ;
var container_str 		= 	"_videoContainer" ;
var videoobject_str 	= 	"_videoembed" ;
var altcontent_str 		= 	"_alternativeContent" ;
var accStatement_str 	= 	"_accStatement" ;

// a few misc variables 
var flashCSSClass 		= 	"flashvideo" ;

// HTML Content-as-strings
var isAccessible		=	'HTML video player accessibility is active. Use the buttons below the player to control playback. Screen Reader users should tab into the the toolbar controls below and enable pass-through mode (for JAWS this is Insert + Z, Window Eyes this is Ctrl + Shift + A).  The progress bar will allow you to adjust the progress of the video by tabbing to that item and then pressing right arrow to skip forward 15 seconds, or left arrow to skip back 15 seconds.' ;
var startVideoToolbar 	= 	'<div class="playerControl">' ;
var endVideoToolbar		=  	'</div>' ;
var playButton			= 	'<a class="playButton a0button play" href="#play_pause" title="Play video">Play</span></a>'	;
var backButton			= 	'<a class="backButton a0button seekback" href="#back" title="Step backwards 15 seconds in the video">Step Backwards</a>' ;
var forwardButton		= 	'<a class="forwardButton a0button seekforward" href="#forward"title="Step forward 15 seconds in the video">Step Forward</a>' ;
var captionButton		= 	'<a class="captionButton a0button captionsOff" href="#showhidecaptions" title="Display closed captions">View Closed Captions</a>' ;
var progressBar			= 	'<a href="#adjustprogress" class="progressContainer" title="Progress 0% Complete"><div class="progressbar"><div class="progressinicator">&nbsp;</div></div></a>' ;

//Class Names used to locate elements using jquery.find() 
var videoContentClass		= 	".videoContent" ;
var playButtonClass			= 	".playButton" ;
var backButtonClass			=	".backButton" ;
var captionButtonClass		= 	".captionButton" ;
var forwardButtonClass		= 	".forwardButton" ;
var progressContainerClass	=	".progressContainer" ;
var progressBarClass		= 	".progressbar" ;
var progressIndicator		= 	".progressinicator" ;
var playerControlClass		= 	".playerControl" ;

// Class Names used to add/remove classes 
var backActiveClass		= 	"seekback" ;
var forwardActiveClass	= 	"seekforward" ;

/**
 * Returns the outermost div for the player with the given unique id 
 */
function getInstanceParent( uid )
{
	return jQuery( "#" + uid + container_str ) ;
}
/**
 * Returns the video player associated with the given child control 
 */
function getAssociatedVideoPlayer( uid )
{
	return swfobject.getObjectById( uid + object_str ) ;
}
/**
 *	initializes an aut0poietic_media instance
 *	Parameters:
 *		uid 			- a unique id, typically generated by wordpress
 *		url 			- the url to the movie (either http:// or rtmp://
 *		width / height 	- width & height of move
 *		caption_url		- (optional) url to the Timed-Text Caption file
 *		preview			- (optional) url to a preview image
 *		fullscreen		- Boolean; true to allow full screen
 *		autoplay		- Boolean; if true, the movie will begin playing with no user interaction
 */
function init_aut0poietic_media( flashpath,  uid , url , width, height, caption_url , preview , fullscreen , autoplay, accessible )
{
	jQuery(document).ready
	( 
		function()
		{
			playerInit( flashpath,  uid , url , width, height, caption_url , preview , fullscreen , autoplay, accessible )
		}
	) ;	
}

function playerInit( flashpath,  uid , url , width, height, caption_url , preview , fullscreen , autoplay, accessible )
{
	var instance = getInstanceParent( uid ) ;
	var player = getAssociatedVideoPlayer( uid ) ;
	
	if(instance == null || player == null || player.useAccessibleUI == null)
	{
		setTimeout(playerInit, 100, flashpath, uid, url, width, height, caption_url, preview, fullscreen, autoplay, accessible) ;
		return ;
	}
	if(accessible)
	{
		
		instance.height(height + 85) ;
		
		jQuery(player).height( height ) ;
		player.height = height ;
		
		instance.find(".clipper").height(height) ;
		
		instance.append( progressBar ) ;
		var controls = startVideoToolbar + playButton + backButton + forwardButton;
		if(caption_url != "" && caption_url != null)
		{
			controls += captionButton ;	
		}
		controls += endVideoToolbar ;
		instance.append( controls ) ;
		
		setARIA(uid) ;
		player.useAccessibleUI() ;
	}
}


/**
 * MUST ONLY BE CALLED FROM THE PLAYER INSTANCE
 * Initializes the controls and associates them with the player specified by uid
**/
function playerReady( uid )
{
	var instance = getInstanceParent( uid ) ;
	
	console.log(instance) ;
	console.log(instance.find( playButtonClass).length) ;
	
	if(instance.find(playButtonClass).length == 0 || instance == null)
	{
		setTimeout(playerReady, 100, uid) ;
		return ;
	}
	
	jQuery( "#" + uid + accStatement_str).text(isAccessible) ;
	
	instance.find( playButtonClass ).click
	( 
		function( event )
		{
			event.preventDefault( ) ;
			var videoPlayer = getAssociatedVideoPlayer( uid ) ;
			videoPlayer.playPauseVideo( ) ;
		}
	);

	instance.find( backButtonClass ).click
	(
		function( event )
		{
			event.preventDefault( ) ;
			if( jQuery( this ).hasClass( backActiveClass ) )
			{
				var videoPlayer = getAssociatedVideoPlayer( uid ) ;
				videoPlayer.seekBack( ) ;
			}
		}
	);
	
	instance.find( forwardButtonClass ).click
	(
		function( event )
		{
			event.preventDefault( ) ;
			if( jQuery( this ).hasClass( forwardActiveClass ) )
			{
				var videoPlayer = getAssociatedVideoPlayer( uid ) ;
				videoPlayer.seekForward() ;
			}
		}
	);
	instance.find( captionButtonClass ).click
	(
		function( event )
		{
			event.preventDefault( ) ;
			var videoPlayer = getAssociatedVideoPlayer( uid ) ;
			videoPlayer.toggleCaptions() ;
		}
	);
	
	instance.find( progressContainerClass ).click
	(
		function( event )
		{
			event.preventDefault( ) ;
			
			var parent = jQuery( this ).parents( videoContentClass ) ;
			
			var clickX = event.pageX - jQuery( this ).offset( ).left  - 10;
			var seekPercent = clickX / parent.find( progressBarClass ).width( ) ;
			
			var videoPlayer = getAssociatedVideoPlayer( uid ) ;
			videoPlayer.seekToPercent( seekPercent ) ;
		}
	);
	instance.find(progressContainerClass).keydown
	(
		function( event )
		{
			if ( event.keyCode == '39' ) //right arrow
			{
				event.preventDefault( ) ;
				var videoPlayer = getAssociatedVideoPlayer( uid ) ;
				videoPlayer.seekForward() ;
			}
			else if ( event.keyCode == '37' ) //left arrow
			{
				event.preventDefault() ;
				var videoPlayer = getAssociatedVideoPlayer( uid ) ;
				videoPlayer.seekBack() ;
			}
		}
	);
}
/**
 * SHOULD ONLY BE CALLED FROM THE PLAYER INSTANCE
 * Synchronizes the state of the controls with that of the associated video 
**/
function videoStateChanged( uid , playing , atStart , atEnd , captionsUp )
{
	var instance = getInstanceParent( uid ) ;

	( playing == "true" ) 		? 	activatePauseButton( instance ) 		: 	activatePlayButton( instance ) ;
	( atStart == "true" ) 		? 	disableBackButton( instance ) 			: 	enableBackButton( instance ) ;
	( atEnd == "true" ) 		? 	disableForwardButton( instance ) 		: 	enableForwardButton( instance ) ;
	( captionsUp == "true" ) 	? 	activateCaptionsHideButton( instance )	: 	activateCaptionsShowButton( instance ) ;
}
/**
 * SHOULD ONLY BE CALLED FROM THE PLAYER INSTANCE
 * Synchronizes the state of the controls with that of the associated video 
**/
function videoProgressChanged( uid , progress )
{
	var instance = getInstanceParent( uid ) ;
	var percentNumber = parseFloat( progress ) ;
	var viewedPercent = Math.round( percentNumber * 100 ) / 100 ;
	var indicatorWidth = ( ( percentNumber / 100 ) * instance.find( progressBarClass ).width( ) ) + 1 ;
	
	( percentNumber > 0 ) 		?	enableBackButton( instance ) : disableBackButton( instance ) ;
	( percentNumber == 100 ) 	?	disableForwardButton( instance ) : enableForwardButton( instance ) ;
	
	instance.find( progressContainerClass ).attr( "aria-valuenow" , viewedPercent ) ;
	instance.find( progressContainerClass ).attr( "aria-valuetext" , "Progress: " + viewedPercent + "% Complete" ) ;
	instance.find( progressContainerClass ).attr( "title" , "Progress: " + viewedPercent + "% Complete" ) ;
	instance.find( progressIndicator ).width( indicatorWidth ) ;
}
/**
 * Sets the default ARIA settings for all controls.
**/
function setARIA( uid )
{
	var instance = getInstanceParent( uid ) ;
	
	instance.find( playButtonClass ).attr( "role" , "button" ) ;
	instance.find( playButtonClass ).attr( "aria-disabled" , "false" ) ;
	instance.find( playButtonClass ).attr( "aria-live" , "polite" ) ;
	instance.find( playButtonClass ).attr( "aria-controls" , uid + videoobject_str ) ;
	instance.find( playButtonClass ).attr( "aria-relevant" , "text" ) ;
	
	instance.find( backButtonClass ).attr( "role" , "button" ) ;
	instance.find( backButtonClass ).attr( "aria-disabled" , "false" ) ;
	instance.find( backButtonClass ).attr( "aria-live" , "polite" ) ;
	instance.find( backButtonClass ).attr( "aria-controls" , uid + videoobject_str ) ;
	instance.find( backButtonClass ).attr( "aria-relevant" , "text" ) ;
	
	instance.find( forwardButtonClass ).attr( "role" , "button" ) ;
	instance.find( forwardButtonClass ).attr( "aria-disabled" , "false" ) ;
	instance.find( forwardButtonClass ).attr( "aria-live" , "polite" ) ;
	instance.find( forwardButtonClass ).attr( "aria-controls" , uid + videoobject_str ) ;
	instance.find( forwardButtonClass ).attr( "aria-relevant" , "text" ) ;
	
	instance.find( captionButtonClass ).attr( "role" , "button" ) ;
	instance.find( captionButtonClass ).attr( "aria-disabled" , "false" ) ;
	instance.find( captionButtonClass ).attr( "aria-live" , "polite" ) ;
	instance.find( captionButtonClass ).attr( "aria-controls" , uid + videoobject_str ) ;
	instance.find( captionButtonClass ).attr( "aria-relevant" , "text" ) ;
	
	instance.find( progressContainerClass ).attr( "role" , "progressbar" ) ;
	instance.find( progressContainerClass ).attr( "aria-valuemax" , "100" ) ;
	instance.find( progressContainerClass ).attr( "aria-valuemin" , "0" ) ;
	instance.find( progressContainerClass ).attr( "aria-valuenow" , "0" ) ;
	instance.find( progressContainerClass ).attr( "aria-valuetext" , "Progress: 0% Complete" ) ;
	instance.find( progressContainerClass ).attr( "aria-disabled" , "false" ) ;
	instance.find( progressContainerClass ).attr( "aria-live" , "polite" ) ;
	instance.find( progressContainerClass ).attr( "aria-controls" , uid + videoobject_str ) ;
	instance.find( progressContainerClass ).attr( "aria-relevant" , "text" ) ;
	
	instance.find( playerControlClass ).attr( "role" , "toolbar" ) ;
	instance.find( playerControlClass ).attr( "aria-disabled" , "false" ) ;
	instance.find( playerControlClass ).attr( "aria-live" , "polite" ) ;
	instance.find( playerControlClass ).attr( "aria-relevant" , "text" ) ;
}
/**
 * Helper method
**/
function setObjectState( obj , oldClass , newClass , newText , params )
{
	jQuery( obj ).removeClass( oldClass ) ;
	jQuery( obj ).addClass( newClass ) ;
	if( newText != null )
	{
		jQuery( obj ).text( newText ) ;	
	}
	for ( var i = 0 ; i < params.length ; i++ )
	{
		var param = params[ i ] ;
		jQuery( obj ).attr( param.key , param.value ) ;
	}
}
/* **************************************************************************** STATE METHODS */
function activatePauseButton( parent )
{
	setObjectState
	(
		jQuery( parent ).find( playButtonClass ), 
		"play", 
		"pause", 
		"Pause Video", 
		[
			{ key : "title", value : "Pause Video" }
		]
	) ;
}


function activatePlayButton( parent ) 
{
	setObjectState
	(
		jQuery( parent ).find( playButtonClass ), 
		"pause", 
		"play", 
		"Play Video", 
		[
			{ key : "title", value : "Play Video" }
		]
	) ;
}

function disableBackButton( parent )
{
	setObjectState
	(
		jQuery( parent ).find( backButtonClass ), 
		"seekback", 
		"seekbackDisabled", 
		null, 
		[
			{ key : "title", value : "Disabled: Step backwards 15 seconds in the video" },
			{ key : "aria-disabled", value : "true" }
		]
	) ;
}

function enableBackButton( parent )
{
	setObjectState
	(
		jQuery( parent ).find( backButtonClass ), 
		"seekbackDisabled", 
		"seekback", 
		null, 
		[
			{ key : "title", value : "Step backwards 15 seconds in the video" },
			{ key : "aria-disabled", value : "false" }
		]
	) ;
}

function disbleForwardButton( parent )
{
	setObjectState
	(
		jQuery( parent ).find( forwardButtonClass ), 
		"seekforward", 
		"seekforwardDisabled", 
		null, 
		[
			{ key : "title", value : "Disabled: Step forward 15 seconds in the video" },
			{ key : "aria-disabled", value : "true" }
		]
	) ;	
}

function enableForwardButton( parent ) 
{
	setObjectState
	(
		jQuery(parent).find( forwardButtonClass ) , 
		"seekforwardDisabled" , 
		"seekforward" , 
		null , 
		[
			{ key : "title", value : "Step forward 15 seconds in the video" } ,
			{ key : "aria-disabled", value : "false" }
		]
	) ;	
}

function activateCaptionsHideButton( parent ) 
{
	setObjectState
	(
		jQuery( parent ).find( captionButtonClass ), 
		"captionsOff", 
		"captionsOn", 
		"Hide closed captions", 
		[
			{ key : "title", value : "Hide closed captions" }
		]
	) ;
}

function activateCaptionsShowButton( parent )
{
	setObjectState
	(
		jQuery( parent ).find( captionButtonClass ), 
		"captionsOn", 
		"captionsOff", 
		"Show closed captions", 
		[
			{ key : "title", value : "Show closed captions" }
		]
	) ;
}


