﻿// Register the namespace for the control.
Type.registerNamespace('SilverlightControls');

SilverlightControls.Player = function(element) { 
    SilverlightControls.Player.initializeBase(this, [element]);

    this._controlID;
    this._width;
    this._height;
    this._background;
    this._isWindowLess;
    this._skin;
    this._mediaURL;
    this._autoPlay;
    this._volumeInProcent;
    this._mute;
}
SilverlightControls.Player.prototype = {
    initialize : function() {
        SilverlightControls.Player.callBaseMethod(this, 'initialize');
        
        var videoPlayerScene = new VideoPlayer.Scene();
            videoPlayerScene.mediaURL = this._mediaURL;
            videoPlayerScene.autoPlay = this._autoPlay;
            videoPlayerScene.volumeInProcent = this._volumeInProcent;
            videoPlayerScene.mute = this._mute;
        
        Silverlight.createObject(
        this._skin,                                                            
        document.getElementById(this._controlID),                               
        this._controlID + 'Player',                                         
        {                                                                      
            width:String(this._width),                                        
            height:String(this._height),                                    
            background:this._background,                                       
            isWindowless:String(this._isWindowLess),                            
            version:'1.0'                                                       
        },
        {
            onError:null,                                                     
            onLoad:Silverlight.createDelegate(videoPlayerScene, videoPlayerScene.handleLoad)                                                                               
        },
        null);                                                                  
        
    },
    dispose : function() {
        SilverlightControls.Player.callBaseMethod(this, 'dispose');
    },
    get_controlID : function() {
        return this._controlID;
    },
    set_controlID : function(value) {
        if (this._controlID !== value) {
            this._controlID = value;
            this.raisePropertyChanged('controlID');
        }
    },  
    get_width : function() {
        return this._width;
    },
    set_width : function(value) {
        if (this._width !== value) {
            this._width = value;
            this.raisePropertyChanged('width');
        }
    },
    get_height : function() {
        return this._height;
    },
    set_height : function(value) {
        if (this._height !== value) {
            this._height = value;
            this.raisePropertyChanged('height');
        }
    },
    get_background : function() {
        return this._background;
    },
    set_background : function(value) {
        if (this._background !== value) {
            this._background = value;
            this.raisePropertyChanged('background');
        }
    },
    get_isWindowLess : function() {
        return this._isWindowLess;
    },
    set_isWindowLess : function(value) {
        if (this._isWindowLess !== value) {
            this._isWindowLess = value;
            this.raisePropertyChanged('isWindowLess');
        }
    },
    get_skin : function() {
        return this._skin;
    },
    set_skin : function(value) {
        if (this._skin !== value) {
            this._skin = value;
            this.raisePropertyChanged('skin');
        }
    },
    get_mediaURL : function() {
        return this._mediaURL;
    },
    set_mediaURL : function(value) {
        if (this._mediaURL !== value) {
            this._mediaURL = value;
            this.raisePropertyChanged('mediaURL');
        }
    },
    get_autoPlay : function() {
        return this._autoPlay;
    },
    set_autoPlay : function(value) {
        if (this._autoPlay !== value) {
            this._autoPlay = value;
            this.raisePropertyChanged('autoPlay');
        }
    },
    get_volumeInProcent : function() {
        return this._volumeInProcent;
    },
    set_volumeInProcent : function(value) {
        if (this._volumeInProcent !== value) {
            this._volumeInProcent = value;
            this.raisePropertyChanged('volumeInProcent');
        }
    },
    get_mute : function() {
        return this._mute;
    },
    set_mute : function(value) {
        if (this._mute !== value) {
            this._mute = value;
            this.raisePropertyChanged('mute');
        }
    }
}
SilverlightControls.Player.registerClass('SilverlightControls.Player', Sys.UI.Behavior);

if (!window.VideoPlayer)
	window.VideoPlayer = {};

VideoPlayer.Scene = function() 
{
    this.mediaURL = '';
    this.mute = false;
    this.volumeInProcent = 0.0;
    this.autoPlay = false;
    this.mediaElementWidth = 0;
    this.mediaElementHeigth = 0;
    this.playerStartPosTop = 0;
    this.playerStartPosLeft = 0;
}
VideoPlayer.Scene.prototype =
{
	handleLoad: function(plugIn, userContext, rootElement) 
	{
		this.plugIn = plugIn;
		var player = plugIn.content.findName('media');
		try
		{
		    player.source = this.mediaURL;
		    player['Volume'] = (this.volumeInProcent / 100);
		    player['IsMuted'] = this.mute;
		    player['AutoPlay'] = this.autoPlay;
    		
		    var volumeButtom = plugIn.content.findName('VolumeButtom');
		    var volumeSlider = plugIn.content.findName('VolumeSlider');

		    if(volumeButtom != null && volumeSlider != null)
		    {
		        volumeButtom['Canvas.Left'] += Math.round((volumeSlider.width * player['Volume']));
		    }
		    this.plugIn.content.onFullScreenChange = onFullScreenChanged;
		}
		catch(e)
		{
		    alert('Error initing the player \n' + e.message);
		}
	}
}
var isMediaOpened = false;
var isMouseDown = false;
var isVolumeMouseDown = false;
var beginX = 0;

function ExternalPlayEvent(hostelement, mediaURL)
{
    var plugin = document.getElementById(hostelement);             
    var player = plugin.content.findName("media"); 
    player['Source'] = mediaURL;
    player['AutoPlay'] = true;
    player.play();
}
function VolumeButtomMouseLeftButtonDown(sender, mouseEventArgs)
{
    beginX = mouseEventArgs.getPosition(null).x;
    isVolumeMouseDown = true;
    sender.captureMouse();
}
function VolumeButtomMouseLeftButtonUp(sender, mouseEventArgs)
{   
    isVolumeMouseDown = false;
    sender.releaseMouseCapture();
}
function VolumeButtomMouseMove(sender, mouseEventArgs)
{
    if (isVolumeMouseDown == true)
    {
        var volumeSlider = sender.findName('VolumeSlider');
        var volumeButton = sender.findName('VolumeButtom');
        var currX = mouseEventArgs.getPosition(null).x;
        
        sender["Canvas.Left"] += currX - beginX; 
        beginX = currX;
       
        if(parseInt(volumeSlider['Canvas.Left']) > parseInt(volumeButton['Canvas.Left']))
        {
            volumeButton['Canvas.Left'] = volumeSlider['Canvas.Left']; 
        }
        if(parseInt(volumeButton['Canvas.Left']) + parseInt(volumeButton.width) > parseInt(volumeSlider['Canvas.Left']) + parseInt(volumeSlider.width))
        {
            volumeButton['Canvas.Left'] = String((parseInt(volumeSlider['Canvas.Left']) + parseInt(volumeSlider.width)) - parseInt(volumeButton.width));
        }
        sender.findName("media")['Volume'] = Math.round((volumeSlider['Canvas.Left'] + volumeSlider.width) / 100) * ((currX - volumeSlider['Canvas.Left']) * 0.01);   
    }  
}
function ProgressIndicatorMouseLeftButtonDown(sender, mouseEventArgs) 
{
    var player = sender.findName('media');
    if (player.currentState == 'Playing')
    {
        sender.captureMouse();
        beginX = mouseEventArgs.getPosition(null).x;
        isMouseDown = true;
    }
}
function ProgressIndicatorMouseMove(sender, mouseEventArgs)
{
    if (isMouseDown == true)
    {
        var progressIndicator = sender.findName('ProgressIndicator');
        var progressbar = sender.findName('Progressbar');
        var progressSlider = sender.findName('ProgressSlider');
        var currX = mouseEventArgs.getPosition(null).x;
        
        sender["Canvas.Left"] += currX - beginX;
        
        beginX = currX;
       
        if(parseInt(progressSlider['Canvas.Left']) > parseInt(progressIndicator['Canvas.Left']))
        {
           progressIndicator['Canvas.Left'] = progressSlider['Canvas.Left'];  
        }
        if(parseInt(progressIndicator['Canvas.Left']) + parseInt(progressIndicator.width) > parseInt(progressSlider['Canvas.Left']) + parseInt(progressSlider.width))
        {
            progressIndicator['Canvas.Left'] = String((parseInt(progressSlider['Canvas.Left']) + parseInt(progressSlider.width)) - parseInt(progressIndicator.width));
        }
        if(progressbar)
        {
            progressbar.width = parseInt(progressIndicator['Canvas.Left']) - (progressIndicator.width / 2);
        }
    }
}
function ProgressIndicatorMouseLeftButtonUp(sender, mouseEventArgs) 
{  
    var progressSlider = sender.findName('ProgressSlider');
    var progressIndicator = sender.findName('ProgressIndicator');
         
    var procent = Math.round(100/(parseInt(progressSlider.width) - parseInt(progressIndicator.width)) * (parseInt(progressIndicator['Canvas.Left']) - parseInt(progressSlider['Canvas.Left'])));

    var player = sender.findName('media');
                   
    var seekTo = Math.round((player.naturalDuration.seconds/100)*procent);        

    var position = player.position;
    
    position.seconds = seekTo;
    
    if(player.naturalDuration.seconds > position.seconds)
    {
        player.position = position;
    }
    
    isMouseDown = false;
    sender.releaseMouseCapture();    
}
function PlayVideo(sender, mouseEventArgs)
{
    var player = sender.findName('media');

    if(player.currentState != 'Paused' && player.currentState != 'Stopped') 
    {
        player.pause();
        
    }else
    {
        player.play();   
    }
}
function StopVideo(sender, mouseEventArgs)
{
    var player = sender.findName('media');
    
    if(player.currentState != 'Paused' && player.currentState != 'Stopped') 
    {
        player.stop();
    }
}
function FastForwardUpEventHandler(sender, mouseEventArgs)
{
    var player = sender.findName('media');
    
    if (player.currentState == 'Playing')
    {
        var position = player.position;
        position.seconds = position.seconds + skipInterval;
        if(player.naturalDuration.seconds > position.seconds)
        {
            player.position = position;
        }
    }
}
function RewindForwardUpEventHandler(sender, mouseEventArgs)
{
    var player = sender.findName('media');
    
    if (player.currentState == 'Playing')
    {
        var position = player.position;
        position.seconds = position.seconds - skipInterval;
        if(player.naturalDuration.seconds > position.seconds)
        {
            player.position = position;
        }
    }
}
function OnMediaEnded(sender, args)
{
    sender.stop();  
}
function OnMediaOpened(sender, args)
{
    isMediaOpened = true;  
}
function OnMediaStateChanged(sender, eventArgs)
{   
    switch(sender.currentState)
    {
        case 'Stopped':
            sender.findName('PlayButton').Visibility = 'Visible';
            sender.findName('PauseButton').Visibility = 'Collapsed';
            sender.findName('TimeStatusText').Text = timeFormatPattern.replace('hh', '00').replace('mm', '00').replace('ss', '00').replace('ff', '00');
            sender.findName('Progressbar').width = 0;
            sender.findName('ProgressIndicator').setValue('Canvas.Left', sender.findName('ProgressSlider')['Canvas.Left']);
        break;
        case 'Paused':
            sender.findName('PlayButton').Visibility = 'Collapsed';
            sender.findName('PauseButton').Visibility = 'Visible';
        break;
        case 'Buffering':
            sender.findName('TimeStatusText').Text = 'Buffering..';    
        break;
        case 'Playing':
            sender.findName('PlayButton').Visibility = 'Visible';
            sender.findName('PauseButton').Visibility = 'Collapsed';
        break;
    }
}
function OnMouseOver(sender, mouseEventArgs)
{
    switch(sender.Name)
    {
        case 'ForwardButton':
            sender.Source = forwardButtonOver;    
        break;
        case 'ToStartButton':
            sender.Source = toStartButtonOver;
        break;
        case 'Rewind':
            sender.Source = backButtonOver;
        break;
        case 'PlayButton':
            if(sender.findName('media').currentState == 'Playing')
            {
                sender.Source = pauseButtonOver;    
            }else
            {
                sender.Source = playButtonOver;
            }
        break;
        case 'MainCanvas':
            isVolumeMouseDown = false;
            isMouseDown = false;
        break;
    }
}
function OnMouseLeave(sender, mouseEventArgs)
{
    switch(sender.Name)
    {
        case 'ForwardButton':
            sender.Source = forwardButton;  
        break;
        case 'ToStartButton':
            sender.Source = toStartButton;
        break;
        case 'Rewind':
            sender.Source = backButton;
        break;
        case 'PlayButton':
            if(sender.findName('media').currentState == 'Playing')
            {
                sender.Source = pauseButton;    
            }else
            {
                sender.Source = playButton;
            }
        break;
    }
}
function Mute(sender, mouseEventArgs)
{
    var mediaElement = sender.findName('media');
    if(mediaElement.IsMuted)
    {
        mediaElement.IsMuted = false;
        sender.findName('MuteOff').Visibility = 'Visible';
        sender.findName('MuteOn').Visibility = 'Collapsed';
    }else
    {
       mediaElement.IsMuted = true;
        sender.findName('MuteOff').Visibility = 'Collapsed';
        sender.findName('MuteOn').Visibility = 'Visible';     
    }
}
function FullScreen(sender, mouseEventArgs)
{
    var plugin = sender.getHost();
    plugin.content.fullScreen = !plugin.content.fullScreen;
}
function onFullScreenChanged(sender, eventArgs)
{
    var plugin = sender.getHost();
    var playerControls = sender.findName("PlayerControls");
    var media = sender.findName("media");
    var mediaElementCanvas = sender.findName("MediaElement");
    
    if (plugin.content.fullScreen)
    {
        this.mediaElementWidth = media.width;
        this.mediaElementHeigth = media.height;
        this.playerStartPosTop = playerControls.getValue("Canvas.Top");
        this.playerStartPosLeft = playerControls.getValue("Canvas.Left");
        
        media.width = plugin.content.actualWidth;
        media.height = plugin.content.actualHeight;
        mediaElementCanvas.setValue("Canvas.ZIndex", 1);
        playerControls.setValue("Canvas.ZIndex", 5);
        playerControls.setValue("Canvas.Top", (parseInt(plugin.content.actualHeight) - parseInt(playerControls.height)));
        playerControls.setValue("Canvas.Left", (plugin.content.actualWidth / 2) - (playerControls.width / 2));
        
    }else
    {
        media.width = this.mediaElementWidth;
        media.height = this.mediaElementHeigth;
        mediaElementCanvas.setValue("Canvas.ZIndex", 5);
        playerControls.setValue("Canvas.ZIndex", 1);
        playerControls.setValue("Canvas.Top", this.playerStartPosTop);
        playerControls.setValue("Canvas.Left", this.playerStartPosLeft);
    }
}
function MainLoopCompleted(sender, args)
{
    var player = sender.findName('media');
    var progressbar = sender.findName('Progressbar');
    var progressSlider = sender.findName('ProgressSlider');
    var progressIndicator = sender.findName('ProgressIndicator');
    
    if (isMediaOpened)
    {         
        if (player.currentState == 'Playing')
        {
            var percent = player.position.seconds / player.naturalDuration.seconds;
            var progressIndicatorPos = ((parseInt(progressSlider.width) - parseInt(progressIndicator.width)) / 100) * (percent * 100)

            if(!isMouseDown)
            {
                progressIndicator['Canvas.Left'] = parseInt(progressSlider['Canvas.Left']) + progressIndicatorPos;
                if(progressbar)
                {
                    progressbar.width = (parseInt(progressSlider['Canvas.Left']) + progressIndicatorPos) - (progressIndicator.width / 2);
                }   
            }
            sender.findName('TimeStatusText').Text = GetTimeFormat(player.position.seconds, player.naturalDuration.seconds);   
        }   
    }
    sender.begin();
}
function GetTimeFormat(SecIn)
{
	var HH,MM,SS,FF;
	if (SecIn > 0) 
	{
		HH = Math.floor(SecIn/3600);
		MM = Math.floor((SecIn - HH*3600)/60);
		SS = Math.floor((SecIn - HH*3600)-(MM*60));
		FF = Math.round((SecIn - MM*60 - HH*3600 - SS)/0.04);
		if (FF > 24) { FF = 0;SS+=1;}
		
	} else
	{
		HH=0;MM=0;SS=0;FF=0;
	}
	if (HH < 10) { HH = '0' + HH;}
	if (MM < 10) { MM = '0' + MM;}
	if (SS < 10) { SS = '0' + SS;}
	if (FF < 10) { FF = '0' + FF;}
	
	return timeFormatPattern.replace('hh', HH).replace('mm', MM).replace('ss', SS).replace('ff', FF);
	//return HH + ':' + MM + ':' + SS + ':' + FF;
}
if (!window.Silverlight) 
	window.Silverlight = {};

Silverlight.createDelegate = function(instance, method) {
	return function() {
        return method.apply(instance, arguments);
    }
}
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();