﻿var PLAYERSTATE = {
	Buffering: 1,
	Closed: 2,
	Error: 3,
	Opening: 4,
	Paused: 5,
	Playing: 6,
	Stopped: 7,
	Completed: 8		
};


var AbstractPlayer = new Class({

  elementId: null,
  player: null,
  evtHandles: null,
  currentState: "Closed",
  
  // Both in seconds
  elapsed: 0,
  duration: 0,
  startParams: null,

  config: {
    height: '400',
    width: '480',
    file: null,
    overstretch: 'true',
    shownavigation: 'false',
    showdigits: 'false',
    usefullscreen: 'false',
    linkfromdisplay: 'true',
    autostart: 'false',
    windowless: 'true'
  },

  addListeners: function() {	  
	if (this.player.view || this.player.addModelListener) {      
		//Time en State listeners toevoegen voor verschillende players
		this.addPlayerListeners();
    }
    else {    	
      this.addListeners.create({ bind: this, delay: 50 })();
    }
  },

  start: function(params) {	  
	this.startParams = params;    
    this.play();
  },  
  
  getElapsed: function() {
  	return this.elapsed;
  },
  
  play: function() {	  
	  this.player.sendEvent("PLAY");	  
  },
	  
  pause: function() {	  
	this.player.sendEvent("PLAY");
  },

  
  stop: function() {  	
	  this.player.sendEvent("STOP");
  },

  // Starts playing again when the player is already paused
  switchMute: function() {
    this.player.sendEvent("MUTE");
  },
  
  //update variables
  onTick: function(elapsed, duration) {	  
	//round floats to int, example:
  	//13,8 -> 13800  (13 seconds and 800 milliseconds)    
	this.elapsed = Math.ceil(elapsed * 1000);
    this.duration = Math.ceil(duration * 1000);
    // check whether the videoplayer initialized completely
    if (this.duration != 0)
    	this.dispatchEvents("tick", { elapsed:this.elapsed, duration: this.duration });
  },

  onStateChange: function(oldState, newState) {	  
	  oldState = oldState.toLowerCase().capitalize();
	  newState = newState.toLowerCase().capitalize();	  
	  this.currentState = newState;
  	// TODO: can be done with custom events
  	if (newState == "Playing" && this.startParams != null) {
  		this.executeStartParams();
  	}
  	
    this.dispatchEvents(newState, {oldState: oldState, newState: newState});
  },
  
  executeStartParams: function() {	  
	  if (this.startParams.sec)		  
		  this.moveTo.create({ bind: this, arguments: this.startParams.sec, delay: 500 })();
	  if (this.startParams.mute)
		  this.switchMute.create({bind: this, delay: 500})();
	  this.startParams = null;
  },
  
  //Custom Events  
  addEvent: function(evtName, handle, handleParams) {	  
	  this.evtHandles.push({evtName: evtName, handle: handle, handleParams: handleParams});
  },
  
  dispatchEvents: function(evtName, params) {
  	//loop through all event handles
  	for ( var i = 0; i < this.evtHandles.length; i++){
			// match event names
  		if (this.evtHandles[i].evtName == evtName) {
				// prepare handle params
  			var handleParams = this.evtHandles[i].handleParams || {arguments:[]};
				for (var param in params)
					handleParams.arguments.push(params[param]);
				// fire
				this.evtHandles[i].handle.create(handleParams)();
			}
  	}
  }
});

var SilverlightPlayer = new Class({
	Extends: AbstractPlayer,
	
	initialize: function(elementId, config) {
		this.evtHandles = [];
		this.elementId = elementId;
	    this.config = $merge(this.config, config);
	    this.player = new jeroenwijering.Player($(elementId), '/static/js/videoplayer/wmvplayer.xaml', this.config);
	    this.addListeners();
  	},  	
  	  
  	addPlayerListeners: function() {
      this.player.addListener('STATE', this.onStateChange.create({ bind: this }));
      this.player.addListener('TIME', this.onTick.create({ bind: this }));
  	},
  	
  	moveTo: function(sec) {	
  	    this.player.sendEvent("SCRUB", sec);    
  	}
});

var Mp4Player = new Class({
	Extends: AbstractPlayer,
	
	initialize: function(elementId, config) {

	this.evtHandles = [];
	this.elementId = elementId;
    this.config = $merge(this.config, config);
        
    var swfObject = new SWFObject('static/swf/swfplayer.swf', elementId + '-Player',config.width,config.height,'9','#ffffff');
    swfObject.addParam('allowfullscreen','true');
    swfObject.addParam('allowscriptaccess','always');    
    swfObject.addParam('wmode','opaque');
    swfObject.addVariable('enableThumbLink','true');
    swfObject.addVariable('controlbar','none');
    swfObject.addVariable('file', config.file);
    swfObject.addVariable('displayclick','none');
    swfObject.addVariable('image','static/img/preview.png');
    swfObject.addVariable('streamer','rtmpe://stream10.bevd.prolocation.net/simplevideostreaming');
    swfObject.write(elementId);
    
    this.player = document.getElementById(elementId).childNodes[0];    
    
    this.addListeners();
  },  	  
  addPlayerListeners: function() {	  
	  	  this.player.addModelListener('STATE', "flashStateChangeProxy");
		  this.player.addModelListener('TIME', "test");
  },
  
  moveTo: function(sec) {		  
		  this.player.sendEvent("SEEK", sec);
  }
	  
});

function test(obj)
{
	var video = getVideoElement(obj);	
	video.onTick(obj.position,obj.duration);
}

function flashStateChangeProxy(obj)
{
	var video = getVideoElement(obj);
	video.onStateChange(obj.oldstate, obj.newstate);
}

function getVideoElement(obj)
{
	var video;
	
	if (this.videos) {		
		video = videos.filter(function(v) {
			return v.elementId == obj.id.replace("-Player", ""); 
		})[0];
	} else if (this.game){		
		video = this.game.videoplayer;
	}
	
	return video;
}
