// Windows Media support

// if the movie has no synchronized content. Set curTimeStamp[0] = -1
var curTimeStamp = new Array(); curTimeStamp[0] = -1;
var curSyncContent = new Array();
var isMOZILLA = navigator.productSub;
var ASImplementationVersion = 1;

var myWin;

var bufferingProgressThread = null;	// progress bar
var checkEventThread = null;
var preTimerThread = null;
var g_bPaused = false;
var vid_init = false;
var currentTime = 0;
var duration  = 0;
var flashErrCode = false;

var durationSentForCurrentVideoFlag = false;

// default player location
var videoPlayerOffsetX = 0;
var videoPlayerOffsetY = 0;


var _fDOM = "bodyFlash";
var _FL = "_level0."; // default flash layer index
var _swfDOM;

var _newWindowComponents = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1";



//player plugin
var playerObj;

function getMediaPlugin() {
	var mp = getDOM("Player");
	if ( mp != null && mp.controls != null ) {
		return mp;
	} else {
		D ( "undef  :  mp" + mp  + " ctrl " + mp.controls );
	}

	return mp;
}


function hideLayer() {
	var ps = getDOM("videoLayer").style;
	// getDOM("videoLayer").style.top = three thousand
	if ( isIE ) {
		ps.left="-400px";
		//ps.display = "none";
	} else {
		ps.visibility = "hidden";
	}

}

function showLayer(){

	var ps = getDOM("videoLayer").style;
	// getDOM("videoLayer").style.top = three thousand
	if ( isIE ) { 
		ps.left= "0px";
		//ps.display = "block";
	} else {
		ps.visibility = "visible";
	}

	// resumeMe();
}


// sets video player location at startup
// presume; initMediaPlugin has already initialized
function setVideoPlayerLocationOffset( offsetX, offsetY ) {

	try {
		// globals called by checkMediaPluginLoaded()
		videoPlayerOffsetX += offsetX;
		videoPlayerOffsetY += offsetY;

		var videoLayer = getDOM("videoLayer");

		//if(  plugin  ) {

		// take existing coords, parse, add distance delta vectors
		videoLayer.style.left = parseInt ( videoLayer.style.left ) + parseInt ( videoPlayerOffsetX);
		videoLayer.style.top =  parseInt ( videoLayer.style.top ) + parseInt ( videoPlayerOffsetY);

		//}

	} catch (e) {

	}

}



// toggles video fullscreen

function fullScreen() {

	if (Player.playState == 3) {
		Player.uiMode = "none";
		Player.fullScreen = true;

		if (myWin != undefined) {
			if (!myWin.closed ) {
				myWin.close()
			}
		}
	}

}

function exitFullScreen(){

	if ( Player.playState == 3) {
		Player.uiMode = "none";
		Player.fullScreen = false;

	}
}


function initMediaPlugin() {

	// Mozilla needs a document.Player variable defined . ActiveX puts it
	if ( !isIE ) {
		Player = getDOM("Player");
	}

	_swfDOM = (isIE) ? window [ _fDOM ] : document.embeds[ _fDOM ];

	// may be slight chance FLASH didn't yet load. retry
	if ( ! _swfDOM ) {
		setTimeout(initMediaPlugin, 100);
	}

	hideLayer();

}




// Initializes the video
function initVideo( URL, videoID)
{

	if ( ! preTimerThread ) {
		window.clearInterval( checkEventThread );
		durationSentForCurrentVideoFlag = false;

		showActiveInVideoLayer("Player");
		// invoke separate thread :: FFx quirk
		// Firefox needs sleeping pills : pathetic workaround
		setTimeout ( function(){ initVideoDelayedAction ( URL )}, 0 );

	}

}

function initVideoDelayedAction ( URL ) {

	Player.close();
	Player.settings.autoStart = false
	Player.enableContextMenu=false;
	Player.URL = URL;

	preTimerThread = window.setInterval("preStartCheck();",500);
	hideVideoTopInfo();

}


function showActiveInVideoLayer ( type ) {
	var videoPlayerDOM = getDOM("Player"); 
	var canvasDOM = getDOM ("videoLayerCanvas");
	var canvasImageDOM = getDOM ("videoLayerCanvasImage");
	
	if ( type == "videoLayerCanvas" ) {
		// hide video layer, show content canvas
		videoPlayerDOM.style.display = "none";
		canvasDOM.style.display = "block";

	}

	else if ( type == "Player" ) {
		// show video layer, hide content canvas
		videoPlayerDOM.style.display = "block";
		canvasDOM.style.display = "none";

	}

}



// show a picture in the media player area
function showImage(imageURL, captionText, captionDate ) {

	showLayer();
	showVideoTopInfo();

	showActiveInVideoLayer("videoLayerCanvas");


	if ( imageURL ) {

		var canvasImageDOM = getDOM ("videoLayerCanvasImage");
		canvasImageDOM.src = imageURL;
		canvasImageDOM.width = 400;
		canvasImageDOM.height = 300;

	} else {
		canvasImageDOM.src = canvasImageDOM.getAttribute("defaultsrc");	// blank image
	}
}



// Clears the event timer

function shutDown(){
	window.clearInterval( checkEventThread );
}

function setVolume(level) {
	Player.settings.volume = level;
}

function getVolume() {
	return Player.settings.volume;
}

// Waits until movie can play and starts the movie

function preStartCheck()
{
	
	// Is playlist open and ready to play?
	if (Player.openState == 6) {
		window.clearInterval( preTimerThread );
		preTimerThread= null;
		
		playVideo();
		//hideLayer();
	}
}

// send playback stats
function checkEvent() {

// only if playing
	if (Player.playState == 3 && ! durationSentForCurrentVideoFlag ) {
		durationSentForCurrentVideoFlag = true;
		duration = Player.currentMedia.duration;
		sendDuration( duration );
	}


// for live events during intro/outro show run time	
	if ( Player.controls) {
		currentTime = Math.round(Player.controls.currentPosition);
		sendRunTime( currentTime );
	}

}


// buffer indicator
function startBufferProgressThread() {
	showBuffering();
	bufferingProgressThread = window.setInterval("showBuffering()", 1000);
}

function endBufferProgressThread() {
	// kill any existing thread  : safety
	shutDown();

	// D("stop buffering thread ------------ " + bufferingProgressThread );
	window.clearInterval( bufferingProgressThread );
	bufferingProgressThread = null;

	// NEXT ---- resume 
	checkEventThread = window.setInterval("checkEvent()", 1000);
	showLayer();
	showVideoTopInfo();
}



function endLoading() {
	// kill any existing thread  : safety
	shutDown();
	window.clearInterval(bufferingProgressThread);
	checkEventThread = window.setInterval("checkEvent()", 1000);
	showLayer();
	showVideoTopInfo();
}



// Windows Media video controls

// restart current
function restartVideo(){
	showLayer();
	stopMe();
	Player.controls.play();
}

// plays
function playVideo ()
{
	Player.controls.play();
}

function pauseMe()
{
	Player.controls.pause();
}

function resumeMe(){
	Player.controls.play();
}

function stopMe(){
	if ( Player.controls ) {
		Player.controls.stop();
	} else {
		D ("player control empty for " + Player );
	}
}

// Handles FSCommand messages from flash
function bodyFlash_DoFSCommand(command, args) {

	var v = args.split(",");
	var formattedArgs = ( args != null && args.length>1 && args !="null" ) ? "<font color='#cc5522'>" + v.join("<font color='#555555'>&nbsp;|&nbsp;</font>") + "</font>"  : "<font color='#777777'>null</font>";
	var flashMessageText = "<font color='#0000aa'>Flash</font>";
	var commandMessageText = "<font color='#8888ff'>" + command + "</font>";

	D( flashMessageText + " " + commandMessageText + ":" + formattedArgs );


	if (command == "playVideo") {
		videoURL = v[0]
		videoID  = v[1]

		// flash does not provide videoURL - bug :(
		if ( ! videoURL ) {
			D (  "no video URL for " + videoID);
			return;
		}

		stopMe();
		flashErrCode = false;

		initVideo(videoURL, videoID);
		sendBufferingPercent( 0 );
	}



	else if (command == "setVideoPositionAtTime") {
		var t  = parseFloat ( v[0] );
	
		// flash does not provide videoURL - bug :(
		if ( ! t ) {
			return;
		}
		
		Player.controls.CurrentPosition = t;

		/*
		stopMe();
		flashErrCode = false;

		initVideo(videoURL, videoID);
		sendBufferingPercent( 0 );
		*/
	}

	// imageURL , captionText, captionDate
	else if (command == "showImage") {

		var imageURL = v[0]
		var captionDateTime = v[1]

		var captionDate = captionDateTime != null ? new Date ( parseInt ( captionDateTime )) : null;

		if ( ! imageURL ) {
			D(  "! no image showImage()");
			return;
		}

		// no processing
		shutDown();

		stopMe();
		flashErrCode = false;

		showImage(imageURL, captionDate );
	}



	else if (command == "pauseVideo") {
		pauseMe();
	} else if (command == "resumeVideo") {
		resumeMe();
	} else if (command == "stopVideo") {
		stopMe();
		hideLayer();
		shutDown();
	} else if (command == "stopTimer") {
		shutDown();
	} else if (command == "fullScreen") {
		fullScreen();
		resumeMe();
	} else if (command == "exitFullScreen") {
		exitFullScreen();
	} else if (command == "restartVideo") {
		restartVideo();

	} else if (command == "setVolume") {
		setVolume( parseInt(v[0]));

	} else if (command == "hideLayer") {
		hideLayer()

	} else if (command == "showLayer") {
		showLayer();
	}

	else if (command == "setVideoPlayerLocationOffset") {
		setVideoPlayerLocationOffset(parseInt(v[0]), parseInt(v[1]));
	}


	// popup : vidXML, currentSlideIdx
	else if (command == "openVideoSynchronizationWindowSlide" ) {
		var status = videoSyncManager.commandLoad ( v[0], v[1], v[2] );
		// and report back if popup is avail
		_JS_F( "setWindowStatusVideoSynchronizationWindow", [ status ] );

	} else if (command == "closeVideoSynchronizationWindow" ) {
		videoSyncManager.commandClose ();
	}
	// event triggered slide change
	else if (command == "showVideoSynchronizationWindowSlide" ) {
		videoSyncManager.commandSlideChange ( v[0] );
	}

	else if (command == "launchExternalLink") {
		externalLink(args);
	}

	else if (command == "sendReporting") {
		sendReporting( v[0], v[1], v[2], v[3], v[4] );
	}

	else if (command == "alert") {
		//alert(args);    
		// instantiates initializer
	} else if (command == "SWF_onloadEvent") {
		SWF_onloadEvent();
	// adjust WMV view
	} else if (command == "setMediaPluginPositionOffset") {
		setMediaPluginPositionOffset( v[0], v[1] );
		
	} else if(command == "sendFeedback"){
		sendTo = v[0];
		subject = v[1];
		message ="mailto:"+ sendTo + "?SUBJECT=" +subject;
		window.location = message; 
	} else if(command == "windowLocation"){
		
		var url = findPortalBaseUrl();
		_JS_F("setWindowLocation", [url]);
	} else if(command == "reloadBrowser"){
		reloadBrowser();
	}
}


// current video run time
function sendRunTime( time){
	_JS_F( "showVideoRunTime", [ time ] );
}

function sendPlayState(state){
	_JS_F( "getVideoState", [ state ] );
}

// video duration
function sendDuration(time){
	_JS_F( "showVideoDuration", [ time ]);
}




// send buffering %
function sendBufferingPercent( pct ){
	_JS_F( "showBuffering", [ pct ] );
}

function sendVideoTopInfo(arg){
	var argsList = new Array;
	argsList.push ( arg );
	_JS_F( "showTopVideoInfo", argsList );
}

function sendVideoError (arg) {
	var argsList = new Array;
	argsList.push ( arg );
	_JS_F( "videoError", [ ] );
}




// on change Slide
function sendScriptCommand(type,param) {
	if ( type.toLowerCase() == "slide") {
		_JS_F( "sendSlideEvent", [ param ] );
	}
	else if(type.toLowerCase() == "caption" || type.toLowerCase() == "text"){
	var matchTag = /<[^>]+>/g;
	caption = param
	caption = caption.replace(matchTag , '');
	_JS_F( "showClosedCaption",[caption] );
	}
}

// for video only
function setMediaPluginPositionOffset( dx, dy) {
	dx = parseInt(dx ); dy = parseInt(dy);
	var mediaPluginLayer = document.getElementById ("videoLayer");
	// adjust, requires PX
 if ( isMOZILLA ) {
	 mediaPluginLayer.style.top = parseInt(mediaPluginLayer.style.top ) +  dy + "px";
 }
 // leave IE alone
	
	}

// final binding to call back to AS layer
function _JS_F ( ASFunction, params ) {
	var msg = [ _FL  + ASFunction , params.join(",") ].join(",");
	var ASHandler = "System.externalFunction.call";

	if ( isIE ) {
		_swfDOM.SetVariable( ASHandler, msg );
		// mozilla
	} else {
		eval("document." + _fDOM ).SetVariable( ASHandler, msg);
	}

}




// send buffering signal
function showBuffering(){
	// D(" ffx ===============================   show buffering : " + Player.network.bufferingProgress  + " nt " + Player.network + "sss " + Player );
	sendBufferingPercent( Player.network.bufferingProgress ); _JS_F( "show", [ ] );
}

function showVideoTopInfo(){
	D("show video top info");
	sendVideoTopInfo( 1 );
}

function hideVideoTopInfo(){
	D("hide video top info");
	sendVideoTopInfo( 0 );
}


function renderMediaPlugin ( w, h ) {
	var s = "";

	if (isIE) {

		var s ='<OBJECT id="Player" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" type="video/x-ms-wmv" ';
		s += 'width="' + w + '" ';
		s += 'height="' + h + '" ';
		s += '>';

		s += tag_param("autoStart", "1");    
		s += tag_param("uiMode", "none");    
		
		s += '</OBJECT>';

		// plugin : http://port25.technet.com/pages/windows-media-player-firefox-plugin-download.aspx
	} else if ( isMOZILLA ) {

		s = '<object id="Player" type="application/x-ms-wmp" width="' + w + '" height="' + h + '">'; 
		s += tag_param("autoStart", "1");    
		s += tag_param("uiMode", "none");    
		
		s += '</object>';


	}

	document.write(s);
}

function tag_param (k,v) {
	return "<PARAM NAME=\"" + k + "\" VALUE=\"" + v + "\">\n";
}


if ( isIE ) {

// Flash -> IE JS
	document.write(
				  '<SCRIPT LANGUAGE=VBScript> \n' +
				  'on error resume next \n' +
				  'Sub bodyFlash_FSCommand(ByVal command, ByVal args)\n' +
				  'call bodyFlash_DoFSCommand(command, args)\n' +
				  'end sub\n' +
				  '</SCRIPT>\n' );


}
