/**
 * MediaPlayer for Silverlight and Windows Media
 * Copyright (c) 2007, MediaEvent Services GmbH & Co. KG
 * http://mediaeventservices.com
 */
 
var player;
 
/* VB Plugin detection */
var detectableWithVB = false;

// Here we write out the VBScript block for MSIE Windows
if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)) {
    document.writeln('<script language="VBscript">');

    document.writeln('\'do a one-time test for a version of VBScript that can handle this code');
    document.writeln('detectableWithVB = False');
    document.writeln('If ScriptEngineMajorVersion >= 2 then');
    document.writeln('  detectableWithVB = True');
    document.writeln('End If');

    document.writeln('\'this next function will detect most plugins');
    document.writeln('Function detectActiveXControl(activeXControlName)');
    document.writeln('  on error resume next');
    document.writeln('  detectActiveXControl = False');
    document.writeln('  If detectableWithVB Then');
    document.writeln('     detectActiveXControl = IsObject(CreateObject(activeXControlName))');
    document.writeln('  End If');
    document.writeln('End Function');

    document.writeln('</scr' + 'ipt>');
    }

function detectPlugin() {
    // allow for multiple checks in a single pass
    var daPlugins = detectPlugin.arguments;
    // consider pluginFound to be false until proven true
    var pluginFound = false;
    // if plugins array is there and not fake
    if (navigator.plugins && navigator.plugins.length > 0) {
	var pluginsArrayLength = navigator.plugins.length;
	// for each plugin...
	for (pluginsArrayCounter=0; pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++ ) {
	    // loop through all desired names and check each against the current plugin name
	    var numFound = 0;
	    for(namesCounter=0; namesCounter < daPlugins.length; namesCounter++) {
		// if desired plugin name is found in either plugin name or description
		if( (navigator.plugins[pluginsArrayCounter].name.indexOf(daPlugins[namesCounter]) >= 0) ||
		    (navigator.plugins[pluginsArrayCounter].description.indexOf(daPlugins[namesCounter]) >= 0) ) {
		    // this name was found
		    numFound++;
		}
	    }
	    // now that we have checked all the required names against this one plugin,
	    // if the number we found matches the total number provided then we were successful
	    if(numFound == daPlugins.length) {
		pluginFound = true;
		// if we've found the plugin, we can stop looking through at the rest of the plugins
		break;
	    }
	}
    }
    return pluginFound;
} // detectPlugin

/**
 * Prevent returning old positions while a seek is pending
 */
function plGetSafePosition() {
  var realPosition = this.getPosition();
  var seekTolerance = 10;
  
  if (this.lastSeekAction && (new Date()).getTime() < this.lastSeekAction.getTime() + seekTolerance * 1000
  	&& (realPosition < this.lastSeekTarget || realPosition > this.lastSeekTarget + seekTolerance)) {
  	return this.lastSeekTarget;
  }
  else
  	return realPosition;
}

/* Silverlight Player */
function hasSilverlightPlayer() {
  return Silverlight.isInstalled("1.0");
}

function canHasSilverlightPlayer() {
  return true; /* browser detection was removed starting with Silverlight 2 */ //Silverlight.supportedUserAgent();
}

function SilverlightPlayer(parentElement) {
  slEmbed(parentElement);
  
  this.iSilverlight = document.getElementById("SilverlightPlugin");
  
  this.startVideo = slStartVideo;
  this.stopVideo = slStopVideo;
  this.pauseVideo = slPauseVideo;
  this.getPosition = slGetPosition;
  this.getSafePosition = plGetSafePosition;
  this.setPosition = slSetPosition;
  this.handlePlayStateChange = slHandlePlayStateChange;
  this.getDuration = slGetDuration;
  this.getVolume = slGetVolume;
  this.setVolume = slSetVolume;
  this.loadMovie = slLoadMovie;
  this.hasInitializationCallback = true;
  this.currentState = 'Loading';
  this.lastSeekAction = undefined;
  this.lastSeekTarget = undefined;
  
  return this;
}

function slEmbed(parentElement) {
  Silverlight.createObject(
  	// Dynamisches Laden des XAML funktioniert nur im IE
        "js/player/slplayer.xaml",      // Source property value.
        parentElement,                  // DOM reference to hosting DIV tag.
        "SilverlightPlugin",         	// Unique plug-in ID value.
        {                               // Per-instance properties.
            width:'320',                // Width of rectangular region of 
                                        // plug-in area in pixels.
            height:'240',               // Height of rectangular region of 
                                        // plug-in area in pixels.
            inplaceInstallPrompt:false, // Determines whether to display 
                                        // in-place install prompt if 
                                        // invalid version detected.
            background:'#FFFFFF',       // Background color of plug-in.
            isWindowless:'false',       // Determines whether to display plug-in 
                                        // in Windowless mode.
            framerate:'24',             // MaxFrameRate property value.
            version:'1.0'               // Silverlight version to use.
        },
        {
            onError:null,               // OnError property value -- 
                                        // event handler function name.
            onLoad:null                 // OnLoad property value -- 
                                        // event handler function name.
        },
        null);                          // Context value -- event handler function name.
}

function SilverlightInplaceInstaller(parentElement) {
  Silverlight.createObject(
        "",      // Source property value.
        parentElement,                  // DOM reference to hosting DIV tag.
        "SilverlightInstaller",        	// Unique plug-in ID value.
        {                               // Per-instance properties.
            width:'320',                // Width of rectangular region of 
                                        // plug-in area in pixels.
            height:'240',               // Height of rectangular region of 
                                        // plug-in area in pixels.
            inplaceInstallPrompt:true, // Determines whether to display 
                                        // in-place install prompt if 
                                        // invalid version detected.
            background:'#FFFFFF',       // Background color of plug-in.
            isWindowless:'false',       // Determines whether to display plug-in 
                                        // in Windowless mode.
            framerate:'24',             // MaxFrameRate property value.
            version:'1.0'               // Silverlight version to use.
        },
        {
            onError:null,               // OnError property value -- 
                                        // event handler function name.
            onLoad:null                 // OnLoad property value -- 
                                        // event handler function name.
        },
        null);                          // Context value -- event handler function name.
}

function slMediaPlayerLoaded(sender, args) {
  player.iMediaPlayer = player.iSilverlight.content.findName("MediaPlayer");
  player.handlePlayStateChange('Initialized');
}

function slStartVideo() {
  if (this.iMediaPlayer)
  	this.iMediaPlayer.play();
}

function slStopVideo() {
  if (this.iMediaPlayer)
	  this.iMediaPlayer.stop();
}

function slPauseVideo() {
  if (this.iMediaPlayer)
	  this.iMediaPlayer.pause();
}

function slCurrentStateChanged(sender, args) {
 if (player != undefined)
  player.handlePlayStateChange(player.iMediaPlayer.CurrentState);
}

function slHandlePlayStateChange(newState) {
 this.currentState = newState;
 if (this.onPlayStateChanged != undefined)
  this.onPlayStateChanged(newState);
}

function slGetPosition() {
  if (this.iMediaPlayer)
	return this.iMediaPlayer.Position.Seconds;
  else
  	return 0;
}

function slSetPosition(i) {
    // http://channel9.msdn.com/wiki/default.aspx/Channel9.SilverlightFAQ
   if (!this.iMediaPlayer)
   	return;
    
    var position = this.iMediaPlayer.Position;
    position.seconds = i;
    this.iMediaPlayer.position = position;
    this.lastSeekAction = new Date();
    this.lastSeekTarget = i;
}

function slGetDuration() {
   if (this.iMediaPlayer)
	return this.iMediaPlayer.NaturalDuration.Seconds;
   else
   	return 0;
}

function slGetVolume() {
   if (this.iMediaPlayer)
	return this.iMediaPlayer.Volume;
   else
   	return 0;
}

function slSetVolume(i) {
   if (this.iMediaPlayer)
	this.iMediaPlayer.Volume = i;
}

function slLoadMovie(url) {
   if (this.iMediaPlayer) {
	  /* 5 => 3 Seconds buffer */
	  var bufferingTime = this.iMediaPlayer.BufferingTime;
	  bufferingTime.seconds = 3;
	  this.iMediaPlayer.BufferingTime = bufferingTime;
   
 	  this.iMediaPlayer.Source = url;
 }
}

/* Windows Media Player */
function hasWindowsMediaPlayer() {
    /* Note: Incompatible, old Netscape version is called "Windows Media Player Plug-in Dynamic Link Library" (npdsplay.dll) */
    pluginFound = detectPlugin('Windows Media Player Firefox Plugin');
    
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
	pluginFound = detectActiveXControl('WMPlayer.OCX'); /* v7+, see http://support.microsoft.com/kb/279022 */
    }
    return pluginFound;
}

function canHasWindowsMediaPlayer() {
    return isWin() && (isIE() || isFF());
}

function WindowsMediaPlayer(parentElement) {
  wmEmbed(parentElement);
  
  this.iMediaPlayer = document.getElementById("MediaPlayer");

  // http://developer.apple.com/internet/webcontent/eventmodels.html
  // Alternative: script for="MediaPlayer" event=playStateChange(NewState)
  if (isIE()) {
  	MediaPlayer.attachEvent("playstatechange", OnDSPlayStateChangeEvt);
  }
  	
  this.startVideo = wmStartVideo;
  this.stopVideo = wmStopVideo;
  this.pauseVideo = wmPauseVideo;
  this.getPosition = wmGetPosition;
  this.getSafePosition = plGetSafePosition;
  this.setPosition = wmSetPosition;
  this.handlePlayStateChange = wmHandlePlayStateChange;
  this.getDuration = wmGetDuration;
  this.getVolume = wmGetVolume;
  this.setVolume = wmSetVolume;
  this.loadMovie = wmLoadMovie;
  this.hasInitializationCallback = true;
  this.initCallback = wmInitCallback;
  this.lastSeekAction = undefined;
  this.lastSeekTarget = undefined;
  
  //this.currentState = 'Initialized';  
  this.currentState = 'Loading';
  var thisObj = this;
  this.loadTimer = window.setTimeout( function(){ thisObj.initCallback() }, 200);
  
  return this;
}

function wmInitCallback() {
	if (this.iMediaPlayer.playState != undefined) {
		window.clearTimeout(this.loadTimer);
  		this.handlePlayStateChange('Initialized');
	}
}


function wmStartVideo() {
  this.iMediaPlayer.controls.play();
}

function wmStopVideo() {
  this.iMediaPlayer.controls.stop();
}

function wmPauseVideo() {
  this.iMediaPlayer.controls.pause();  
}

function wmGetPosition() {
  return this.iMediaPlayer.controls.currentPosition;
}

/**
 * function wmSetPosition()
 *
 * Springt zu der übergebenen Position im Video
 */
function wmSetPosition(i) {
  this.iMediaPlayer.controls.currentPosition = i;
  this.lastSeekAction = new Date();
  this.lastSeekTarget = i;
}

function wmGetDuration() {
 return this.iMediaPlayer.currentMedia.duration;
}

function wmHandlePlayStateChange(newState) {
 this.currentState = newState;
 if (this.onPlayStateChanged != undefined)
  this.onPlayStateChanged(newState);
}

function wmEmbed(parentElement) {
 // v7+
 parentElement.innerHTML = 
          '<OBJECT ID="MediaPlayer" WIDTH=320 HEIGHT=240 ' + (isIE() ? 'classid="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6"' : '')
        + 'type="application/x-ms-wmp">'
        + '   <PARAM NAME="autoSize" VALUE="1">'
        + '   <PARAM NAME="autoStart" VALUE="TRUE">'
        + '   <PARAM NAME="uiMode" VALUE="none">'
        + '</OBJECT>';
}

// Eigentlich nur Firefox, nutzen wir für IE jetzt aber auch (Constructor)
// Siehe http://msdn.microsoft.com/archive/en-us/samples/internet/imedia/netshow/events2/default.asp?frame=true
function OnDSPlayStateChangeEvt(newState) {
	if (player != undefined) {
		var msg;
		
		switch (newState) {
		  case 0: msg = 'Undefined';
		  	  break;
		  case 1: msg = 'Stopped';
		  	  break;
		  case 2: msg = 'Paused';
		  	  break;
		  case 3: msg = 'Playing';
		  	  break;
		  case 4: msg = 'ScanForward';
		  	  break;
		  case 5: msg = 'ScanReverse';
		  	  break;
		  case 6: msg = 'Buffering';
		  	  break;
		  case 7: msg = 'Waiting';
		  	  break;
		  case 8: msg = 'MediaEnded';
		  	  break;
		  case 9: msg = 'Transitioning';
		  	  break;
		  case 10: msg = 'Ready';
		  	  break;
		  case 11: msg = 'Reconnecting';
		  	  break;
		}
		
		if (msg)
			player.handlePlayStateChange(msg);
	}
}

function wmGetVolume() {
 return this.iMediaPlayer.settings.volume / 100;
}

function wmSetVolume(i) {
 this.iMediaPlayer.settings.volume = i * 100;
}

function wmLoadMovie(url) {
 this.iMediaPlayer.URL = url;
}