/* This notice must be untouched at all times.

cvs_movieplayer.js    v. 2.1		26-11-2007

Copyright (c) 2005 - 2007 Clear Voice Systems Ltd. All rights reserved.

Provides Loadmovie, Seekmovie and Movieplayer classes.

Many functions in the Movieplayer class are wrappers to the native Windows Movie Player functions.

Requires WMP version 7.0 Active-X control or later

*/


// CLASS DEFINITION


//
// Class Loadmovie

function Loadmovie(instance) {

  this.instance='loadmovie';
  this.stage = 0;
  this.loadthread = null;
  this.dpthread = null;
  // downloadstate values: -1 - Undetermined | 0 - Download in progress| 1 - Download complete
  // Only relevant if movie is being accessed using progressive download.
  this.downloadstate = -1;
  this.movieloadtime = 0.25;
  this.movie1_DP = '';
  this.startposition = 0;
  this.endposition = null;
  this.playduration  = null;

  this.start = function start(stage) {
    if ( stage != null ) this.stage = stage;

    switch (this.stage) {
      case 0:
      this.stage=1;
	  if ( connection.isstreamed && QUERYSTRING['viewclip'] == 'true' ) {
	  	//Allow seek to position before play if using streaming protocol in viewclip mode
	    window.setTimeout("movie1.setCurrentPosition(" + this.startposition +");", 700);
	  }
      movie1.Play();
	  if ( connection.isonline )
	    document.getElementById('idClipplaystate2').style.visibility='visible';
	  this.loadthread = window.setTimeout(this.instance + ".start();", 100);
	  break;
  
      case 1:
	  if ( movie1.getCurrentPosition() >= this.startposition+this.movieloadtime ) {
	    movie1.mediaplaying = true;
	    this.stage = 2;
	    this.loadthread = window.setTimeout(this.instance + ".start();", 100);
      } else {
	    this.loadthread = window.setTimeout(this.instance + ".start();", 100);
	  }
      break;
	
      case 2:
	  this.getplayinfo();
			
      if (!loadstate ) {
		// Only do these steps once when movie is played for first time
		loadstate = true;
	    movie1.showhideplayer('show');
        movie1.Mute(false);
		document.getElementById('playbttn2').style.display='none';
		document.getElementById('idClipplaystate2').style.visibility='hidden';
	  }
	  playstate = 'Playing';
	  //Start the captioner from caption line 1
	  //captioner.start(1);

	  // Start thread to animate timeline seek thumb
	  movieseekthread = window.setInterval("setmovieseekthumb()", 100);
	  
	  // Redo seekIndex to ensure we have set correct index point for the indexer
	  index.seekIndex(this.startposition);
	  
     //Start the indexer
      indexer.start();

	  // HTTP PROGRESSIVE DOWNLOAD mode
	  if ( connection.isonline && !connection.isstreamed) {
        // Register functions to handle events for seek thumb 
  		document.getElementById('bttnseek').onmouseover=tiptexthandler;
 		document.getElementById('bttnseek').onmouseout=tiptexthandler;
  		// Register functions to handle events for the Forward05/30 and Rewind05/30 buttons  
  		registerhandlers('bttnrewind05', 'tiptexthandler', 'onmouseover,onmouseout,onclick');
  		registerhandlers('bttnrewind30', 'tiptexthandler', 'onmouseover,onmouseout,onclick');
  		registerhandlers('bttnforward05', 'tiptexthandler', 'onmouseover,onmouseout,onclick');
  		registerhandlers('bttnforward30', 'tiptexthandler', 'onmouseover,onmouseout,onclick');
  		// Register functions to handle events for TSM control buttons
  		registerhandlers('bttntsmdec', 'tiptexthandler', 'onmouseover,onmouseout,onclick');
 		registerhandlers('bttntsminc', 'tiptexthandler', 'onmouseover,onmouseout,onclick');
		
	  	// Start thread to monitor download progress
		this.downloadstate = 0;		// Downloading in progress
		this.dpthread = window.setInterval(this.instance + ".monitorDP();", 1000);
		
		// Make the streaming progress bar display
		document.getElementById('idStreamingprogress').style.visibility="visible";
		
	  // OFFLINE AND STREAM modes	
	  }else if (!connection.isonline || (connection.isonline && connection.isstreamed )  ) {	
	    // Allow timeline slider to be dragged
	    objtimelinesliderbttn.setDraggable(true);   

        // Register function for onclick event for index search points
	    for ( i = 0; i < index.n; i++ ) {
	      searchnodename = 'sp' + i;
	      eval('document.getElementById("'+searchnodename+'").onclick=SeekIndex');
	    }

        // Register functions to handle events for seek thumb 
  		document.getElementById('bttnseek').onmouseover=mouseover;
 		document.getElementById('bttnseek').onmouseout=mouseout;
        // Register functions to handle events for the Forward05/30 and Rewind05/30 buttons  
  		registerhandlers('bttnrewind05', 'Rewind', 'onmouseover,onmouseout,onclick');
  		registerhandlers('bttnrewind30', 'Rewind', 'onmouseover,onmouseout,onclick');
  		registerhandlers('bttnforward05', 'Forward', 'onmouseover,onmouseout,onclick');
  		registerhandlers('bttnforward30', 'Forward', 'onmouseover,onmouseout,onclick');
  		// Register functions to handle events for TSM control buttons
  		registerhandlers('bttntsmdec', 'DecRate', 'onmouseover,onmouseout,onclick');
 		registerhandlers('bttntsminc', 'IncRate', 'onmouseover,onmouseout,onclick');
	  }
	  break;
    }
  }
  
  this.monitorDP = function monitorDP() {
  
    this.movie1_DP = document.getElementById('wmpmovie').network.downloadProgress;

    if ( this.movie1_DP == 100) {
	  this.downloadstate = 1;	// Download complete
	  // Allow timeline slider to be dragged
	  objtimelinesliderbttn.setDraggable(true); 

      // Register function for onclick event for index search points
	  for ( i = 0; i < index.n; i++ ) {
	    searchnodename = 'sp' + i;
	    eval('document.getElementById("'+searchnodename+'").onclick=SeekIndex');
	  }

      // Register functions to handle events for seek thumb 
      document.getElementById('bttnseek').onmouseover=mouseover;
 	  document.getElementById('bttnseek').onmouseout=mouseout;
      // Register functions to handle events for the Forward05/30 and Rewind05/30 buttons  
      registerhandlers('bttnrewind05', 'Rewind', 'onmouseover,onmouseout,onclick');
  	  registerhandlers('bttnrewind30', 'Rewind', 'onmouseover,onmouseout,onclick');
  	  registerhandlers('bttnforward05', 'Forward', 'onmouseover,onmouseout,onclick');
  	  registerhandlers('bttnforward30', 'Forward', 'onmouseover,onmouseout,onclick');
  	  // Register functions to handle events for TSM control buttons
  	  registerhandlers('bttntsmdec', 'DecRate', 'onmouseover,onmouseout,onclick');
 	  registerhandlers('bttntsminc', 'IncRate', 'onmouseover,onmouseout,onclick');
	  
	  // Hide the streaming progress bar after 1s
	  window.setTimeout("document.getElementById('idStreamingprogress').style.visibility='hidden';", 1000);
	  
	  // Clear download progress monitor thread
	  window.clearInterval(this.dpthread);
	  
	  // Ensure tip text is removed
	  tiptext.removetiptext();
	}
  }  

  this.getplayinfo = function getplayinfo() {
    // Find index point that lies before the start position
    index.seekIndex(this.startposition);	// calling seekIndex sets the index.line and index.last values

    if ( QUERYSTRING['viewclip']=='true' ) {
      // In viewclip mode, tead the time code of the index point that lies after the start position to determine end positiion
	  if ( !index.last ) {
	    index.nextIndex(index.line);
	    this.endposition = index.start;
	  }else{
		// If no index points lies after startposition, just use total movie duration to determine end position
	    this.endposition=movie1.getDuration();
      }
	  // Calculate play duration
	  this.playduration = this.endposition - this.startposition;
    }else {
	  // If not playing in viewclip mode, always set end position to be movie duration
	  this.endposition=movie1.getDuration();
      // Calculate play duration
	  this.playduration = this.endposition - 0;
	}

  }

}

//
// Class Seekmovie

function Seekmovie(instance) {

  this.instance='seekmovie';
  this.position;				// Desired Play-head position to seek to
  this.currentposition;		 	// Current Play-head position (not used)
  this.currentplaystate;		// Current Play-state

  
  this.start = function start(position) {
    if ( position != null ) {
	  this.position=position;
	  if (playstate != 'Seeking' ) {
	    this.currentplaystate = playstate;
	  }
	  playstate = 'Seeking';
	  movie1.setCurrentPosition(this.position);
	  playstate = this.currentplaystate
	}
  }
}


//
// CLass Movieplayer

function Movieplayer(instance) {

  // PUBLIC MEMBER PROPERTIES
  
  this.mediabaseURL = '.';		//Override this.
  this.versionString = null;	// WMP version string. Set when a media item is opened with Open()
  this.version = null;			// WMP major version number. Set as above
  this.mediaplaying = false;
  this.mediastopped = false;
  this.finished = false;
  this.playrateindex = 2;
  this.playrate = 1.0;
  this.wmpObj = null;
  this.mediaopen = false;
  
  // Call the constructor function
  if ( instance ) {
    this.wmpObj=initialize(instance);
  }

  var playstate = new Array(
	'Undefined',
	'Stopped', 
	'Paused',
	'Playing',
	'ScanForward', 
	'ScanReverse',
	'Buffering',
	'Waiting', 
	'Finished', 
	'Preparing', 
	'Ready',
	'Reconnecting'
	);

  var playratestring = new Array(
	'Slowest',
	'Slower', 
	'Normal Speed',
	'Faster',
	'Fastest'
	);

  this.PLAYRATEMIN = 0.66;
  this.PLAYRATEMAX = 1.4;
  
  var playratevalue = new Array(
	this.PLAYRATEMIN,
	0.8, 
	1.0,
	1.2,
	this.PLAYRATEMAX
	);
  
  var openstate = new Array(
    'Undefined', 
    'Changing playlist',
    'Locating playlist',
    'Connecting to playlist',
    'Loading playlist',
    'Opening playlist', 
    'Playlist open', 
    'Playlist changed',
    'Changing media', 
    'Locating media item',
    'Connecting to server', 
    'Loading media item', 
    'Opening Media item', 
    'Media item open', 
    'Opening codec', 
    'Codec downloaded', 
    'Downloading DRM license', 
    'DRM license downloaded', 
    'Begin DRM Individualization', 
    'DRM individualization completed', 
    'Waiting for media item', 
    'Opening unknown URL type'); 

  
  // Constructor function (PRIVATE)
  function initialize(wmpObj){
    return(document.getElementById(wmpObj));	  
  }

  //
  // PUBLIC MEMBER FUNCTIONS
  //
  
  // Open()
  this.Open=function Open(URL) {
    this.wmpObj.URL = this.mediabaseURL + URL;
    this.getVersion();			// Set the version and versionString properties
  }

  // Close()
  this.Close=function Close() {  
    this.wmpObj.close();
  }

  // Play()
  this.Play=function Play() {
    if ( this.getPlayState() == 'Playing' ) return (false);
    this.wmpObj.controls.play();
  }

  // Stop()
  this.Stop=function Stop() {
    this.wmpObj.controls.stop();
  }

  // Pause()
  this.Pause=function Pause() {
    this.wmpObj.controls.pause();
  }

  // Mute()
  this.Mute=function Mute(mutestate) {
	if ( mutestate == null ) mutestate=true;
    this.wmpObj.settings.mute = mutestate;
  }
  
  // setVolume()
  this.setVolume=function setVolume(volume) {
	if ( volume >= 0 && volume <= 100 ) {
      this.wmpObj.settings.volume = volume;
	}
  }
  
  // getPlayState()
  this.getPlayState=function getPlayState() {
    var intplaystate, strplaystate='', downloadprogress, openstate;

    intplaystate = this.wmpObj.playState;
    switch (intplaystate) {
		
	  case 0: //Undefined
	  case 1:
	  case 2:
	  case 3:
	  case 4:
	  case 5:
	  case 10:
	  strplaystate='';
	  break;
	  
	  case 7:	//Waiting
	  case 9:	//Preparing
	  strplaystate=this.getOpenState();
	  break;	
	  
	  case 6:	//Buffering
	  bufferingprogress = this.wmpObj.network.bufferingProgress
	  strplaystate=playstate[intplaystate] + ' (' + bufferingprogress + '%)';
	  break;
	  
	  default:
	  strplaystate=playstate[intplaystate];
    }

    return (strplaystate);  
  }

  // getOpenState()
  this.getOpenState=function getOpenState() {
    var intopenstate, stropenstate='';
	intopenstate = this.wmpObj.openState
    if ( intopenstate >=0 && intopenstate<= 21 ) {
      stropenstate=openstate[intopenstate];
    }
	// Added this condition to suppress the Unknown URL type error (Player Open State = 21)that occurs in Vista 
	if ( intopenstate == 21 )
	  stropenstate='';
    return (stropenstate);   
  }

  // tgetCurrentPosition()
  this.tgetCurrentPosition=function tgetCurrentPosition() {
    var tPosition;

    tPosition = int2time(this.wmpObj.controls.currentPosition);
    return (tPosition);
  }

  // getCurrentPosition()
  this.getCurrentPosition=function getCurrentPosition() {
    var intPosition;

    intPosition = this.wmpObj.controls.currentPosition;
    return (intPosition);
  }
  
  // setCurrentPosition
  this.setCurrentPosition=function setCurrentPosition(Position) {
    if ( !isNaN(Position) ) {
     if ( Position == 0 || Position == '')
	   Position = 1.001;	// Due to bug in Microsoft SDK can't set seek to the zero position. Set seek to 1.001S from beginning instead.
     this.wmpObj.controls.currentPosition = Position;
	}
  }

  // tgetDuration()
  this.tgetDuration=function tgetDuration() {
	var tDuration;  
	  
	tDuration = int2time(this.wmpObj.currentMedia.duration);
    return (tDuration);
  }

  // getDuration()
  this.getDuration=function getDuration() {
	var intDuration;  
	  
	intDuration = this.wmpObj.currentMedia.duration;
    return (intDuration);
  }

  //
  // getClipinfo
  //
  this.getClipinfo=function getClipinfo() {
    var clipinfo = new Array();
    var strTitle, strAuthor, strCopyright;

    strTitle = this.wmpObjTitle;
    strAuthor = this.wmpObj.Author;
    strCopyright = this.wmpObj.Copyright;

	// Set to "none" if return value is null
	if(strTitle == "") strTitle="none";
    if(strAuthor == "")	strAuthor="none";
    if(strCopyright == "") strCopyright="none";

    //Setup values in clipinfo array and return it
    clipinfo['strTitle'] = strTitle; clipinfo['strAuthor'] = strAuthor; clipinfo['strCopyright'] = strCopyright;
    return (clipinfo);   
  }
 
  //
  // Function to probe availablility of named player features
  //
  this.isAvailable=function isAvailable(name) {
    var is = this.wmpObj.settings.isAvailable(name);
	return (is);
  } 

  // setRate(index) - Set the this.version and this.versionString properties
  this.setRate=function setRate(index) {
      if ( index >=0 && index <=4 ) {
        this.playrate = playratevalue[index];
        this.playrateindex = index;
        this.wmpObj.settings.rate=this.playrate;
    }
  }

  // getRate([mode])
  // Optional mode flag determines value returned.
  //   Mode=0 (Default) returns rate as a float value
  //   Mode=1 returns mode as a string for rate values = {0.65, 0.8, 1.0, 1.2, 1.4}
  this.getRate=function getRate(mode) {
	if (mode==null) mode=0;
    var rate = this.wmpObj.settings.rate;
	rate = Math.round(rate*100);	// Fix for Vista because rate value now returns an unrounded float
	if (mode==0) return(parseFloat(rate));

	if (rate == playratevalue[2]*100) return (playratestring[2]);
	else if (rate == playratevalue[0]*100) return (playratestring[0]);
	else if (rate == playratevalue[1]*100) return (playratestring[1]);
	else if (rate == playratevalue[3]*100) return (playratestring[3]);
	else if (rate == playratevalue[4]*100) return (playratestring[4]);
	return(null);
  }
  
  // showhideplayer()
  this.showhideplayer=function showhideplayer(option) {
    if (option == 'hide') {
      this.wmpObj.style.visibility='hidden';
    }else if (option == 'show') {
      this.wmpObj.style.visibility='visible';
    }else
      ;
  }

    
  // getVersion() - Sets the this.version and this.versionString properties
  this.getVersion=function getVersion() {
	intV = new Array();
    this.versionString = this.wmpObj.versionInfo;
	intV = this.versionString.split('\.');
	isNaN(parseInt(intV[0])) ? this.version = 0 : this.version = intV[0];
  }  

  // getisMediaOnline() - Set the this.isMediaOnline property
  this.getMediaOnlineStatus=function getMediaOnlineStatus() {
	if ( (this.wmpObj.network.sourceProtocol == '' | this.wmpObj.network.sourceProtocol == 'file') )
	  return (false);
	else
	  return (true);
  }
  
}
