﻿//Global video player variable
var moviePlayer;

//Constructor for movie player object.
var SilverlightMoviePlayer = function(agPlayerObject)
{
    this.playerContainer = agPlayerObject;
    this.playerContainer["Visibility"] = "Collapsed";
    
    this.playerControls = this.playerContainer.findName("PlayerControls");
    this.playerControlsHideTimeoutDuration = 3000;

    // set and store inital size/position values for full screen functionality
    this.SetInitialSizeAndPosition();
    this.initialZIndex = this.playerContainer["Canvas.ZIndex"];

    this.player = this.playerContainer.findName("VideoWindow");
    this.player.AddEventListener("MediaFailed", delegate(this, this.MovieFailed));
    this.player.AddEventListener("MediaOpened", delegate(this, this.MediaOpened));
    this.player.AddEventListener("CurrentStateChanged", delegate(this, this.MediaStateChanged));
    this.player.AddEventListener("DownloadProgressChanged", delegate(this, this.MediaDownloadProgressChanged));

    this.playPauseButton = this.playerContainer.findName("PlayPauseButton");
    this.stopButton = this.playerContainer.findName("StopButton");
    this.muteButton = this.playerContainer.findName("MuteButton");

    this.playPauseButton.AddEventListener("MouseLeftButtonDown", delegate(this, this.PlayPauseButton_MouseDown));

    // Event handlers for toggling player controls' visibility
    this.playerControls.AddEventListener("MouseEnter", delegate(this, this.PlayerControls_MouseEnter));
    this.playerControls.AddEventListener("MouseMove", delegate(this, this.PlayerControls_MouseMove));
    this.playerContainer.AddEventListener("MouseMove", delegate(this, this.PlayerContainer_MouseMove));
    this.playerContainer.AddEventListener("MouseLeave", delegate(this, this.PlayerContainer_MouseLeave));
    
    // Add generic event handlers
    this.playPauseButton.AddEventListener("MouseEnter", delegate(this, this.GenericButton_MouseEnter));
    this.playPauseButton.AddEventListener("MouseLeave", delegate(this, this.GenericButton_MouseLeave));
    this.playPauseButton.AddEventListener("MouseLeftButtonUp", delegate(this, this.GenericButton_MouseUp));
    this.stopButton.AddEventListener("MouseEnter", delegate(this, this.GenericButton_MouseEnter));
    this.stopButton.AddEventListener("MouseLeave", delegate(this, this.GenericButton_MouseLeave));
    this.stopButton.AddEventListener("MouseLeftButtonUp", delegate(this, this.GenericButton_MouseUp));
    this.stopButton.AddEventListener("MouseLeftButtonDown", delegate(this, this.GenericButton_MouseDown));
    this.muteButton.AddEventListener("MouseEnter", delegate(this, this.GenericButton_MouseEnter));
    this.muteButton.AddEventListener("MouseLeave", delegate(this, this.GenericButton_MouseLeave));
    this.muteButton.AddEventListener("MouseLeftButtonUp", delegate(this, this.GenericButton_MouseUp));
    this.muteButton.AddEventListener("MouseLeftButtonDown", delegate(this, this.GenericButton_MouseDown));
    this.playerContainer.findName("PreviousButton").AddEventListener("MouseEnter", delegate(this, this.GenericButton_MouseEnter));
    this.playerContainer.findName("PreviousButton").AddEventListener("MouseLeave", delegate(this, this.GenericButton_MouseLeave));
    this.playerContainer.findName("PreviousButton").AddEventListener("MouseLeftButtonUp", delegate(this, this.GenericButton_MouseUp));
    this.playerContainer.findName("PreviousButton").AddEventListener("MouseLeftButtonDown", delegate(this, this.GenericButton_MouseDown));
    this.playerContainer.findName("NextButton").AddEventListener("MouseEnter", delegate(this, this.GenericButton_MouseEnter));
    this.playerContainer.findName("NextButton").AddEventListener("MouseLeave", delegate(this, this.GenericButton_MouseLeave));
    this.playerContainer.findName("NextButton").AddEventListener("MouseLeftButtonUp", delegate(this, this.GenericButton_MouseUp));
    this.playerContainer.findName("NextButton").AddEventListener("MouseLeftButtonDown", delegate(this, this.GenericButton_MouseDown));

    this.pluginContent = this.playerContainer.getHost().content;
    this.pluginContent.onFullScreenChange = delegate(this, this.onFullScreenChanged);
    this.playerContainer.findName("FullScreenButtonPNG").AddEventListener("MouseEnter", delegate(this, this.FullScreenButton_MouseEnter));
    this.playerContainer.findName("FullScreenButtonPNG").AddEventListener("MouseLeave", delegate(this, this.FullScreenButton_MouseLeave));
    this.playerContainer.findName("FullScreenButtonPNG").AddEventListener("MouseLeftButtonDown", delegate(this, this.FullScreenButton_MouseDown));

    this.timeline = this.playerContainer.findName("Timeline");
    this.timeHandle = this.playerContainer.findName("TimeThumb");
    this.timeHandle.AddEventListener("MouseLeftButtonDown", delegate(this, this.TimeHandle_MouseDown));
    this.timeHandle.AddEventListener("MouseLeftButtonUp", delegate(this, this.TimeHandle_MouseUp));
    this.timeHandle.AddEventListener("MouseMove", delegate(this, this.TimeHandle_MouseMove));
    this.timeHandleIsDragging = false;
    this.timeHandleLastPoint = null;

    this.volumeSlider = this.playerContainer.findName("VolumeSlider");
    this.volumeHandle = this.playerContainer.findName("VolumeThumb");
    this.volumeHandle.AddEventListener("MouseLeftButtonDown", delegate(this, this.VolumeHandle_MouseDown));
    this.volumeHandle.AddEventListener("MouseLeftButtonUp", delegate(this, this.VolumeHandle_MouseUp));
    this.volumeHandle.AddEventListener("MouseMove", delegate(this, this.VolumeHandle_MouseMove));

    this.playerControlsDisplayed = false;
}
//Prototype declaration of movie player object.
SilverlightMoviePlayer.prototype = {
    //Load movie method.
    LoadMovie: function(url, top, left, height, width)
    {
        this.SetInitialSizeAndPosition(top, left, height, width);
        this.player.IsMuted = false;
        this.player.Source = url;
        this.playerContainer["Visibility"] = "Visible";
        this.ShowControls(true);
    },
    //Unload movie method.
    UnloadMovie: function()
    {
        this.ShowControls(false);
        this.player.Source = null;
        this.playerContainer["Visibility"] = "Collapsed";
    },
    //Size and position method.
    SetInitialSizeAndPosition: function(top, left, height, width)
    {
        this.playerContainer["Canvas.Top"] = (top || top == 0 ? top : 194);
        this.playerContainer["Canvas.Left"] = (left || left == 0 ? left : 340);
        this.playerContainer["Height"] = (height ? height : 255);
        this.playerContainer["Width"] = (width ? width : 340);
        
        this.initialTop = this.playerContainer["Canvas.Top"];
        this.initialLeft = this.playerContainer["Canvas.Left"];
        this.initialHeight = this.playerContainer["Height"];
        this.initialWidth = this.playerContainer["Width"];
        
        this.playerControls_initialTop = this.playerControls["Canvas.Top"];
        this.playerControls_initialLeft = this.playerControls["Canvas.Left"];
        this.playerControls_initialHeight = this.playerControls["Height"];
        this.playerControls_initialWidth = this.playerControls["Width"];
    },
    //Event handler for a failed video load.
    MovieFailed: function(sender, eventArgs)
    {
        alert('Movie not yet available');
        this.UnloadMovie();
    },
    //Event handler for video opened.
    MediaOpened: function(sender, eventArgs)
    {
        sender.findName("PlaySymbol_Hide").Begin();
        sender.findName("PauseSymbol_Show").Begin();
    },
    //Event handler for changing download progress of video.
    MediaDownloadProgressChanged: function(sender, eventArgs)
    {
        sender.findName("DownloadProgressSlider").Width = Math.floor(this.player.downloadProgress * this.timeline.width * 1000) / 1000;
    },
    //Generic Mouse event for handling child event requests.
    GenericButton_MouseEvent: function(sender, eventArgs, eventName)
    {
        // Derive and begin storyboard
        var storyboardName = sender.Name + "_" + eventName;
        if (this.playerContainer.findName(storyboardName))
            this.playerContainer.findName(storyboardName).Begin();
        
        // Call any special functions attached for this event
        switch(storyboardName)
        {
            case "StopButton_MouseDown": this.StopButton_MouseDown(sender, eventArgs); break;
            case "MuteButton_MouseDown": this.MuteButton_MouseDown(sender, eventArgs); break;
        }
    },
    //Generic mouse enter event.
    GenericButton_MouseEnter: function(sender, eventArgs)
    {
        this.GenericButton_MouseEvent(sender, eventArgs, "MouseEnter");
    },
    //Generic mouse leave event.
    GenericButton_MouseLeave: function(sender, eventArgs)
    {
        this.GenericButton_MouseEvent(sender, eventArgs, "MouseLeave");
    },
    //Generic mouse up event.
    GenericButton_MouseUp: function(sender, eventArgs)
    {
        this.GenericButton_MouseEvent(sender, eventArgs, "MouseUp");
    },
    //Generic mouse down event.
    GenericButton_MouseDown: function(sender, eventArgs)
    {
        this.GenericButton_MouseEvent(sender, eventArgs, "MouseDown");
    },
    //Event handler for play & pause button click.
    PlayPauseButton_MouseDown: function(sender, eventArgs)
    {
        if (this.player.CurrentState == "Paused" || this.player.CurrentState == "Stopped")
            this.player.Play();
        else if (this.player.CurrentState == "Playing")
            this.player.Pause();
    },
    //Event handler for stop button click.
    StopButton_MouseDown: function(sender, eventArgs)
    {
        this.playerContainer.findName("PauseSymbol_Hide").Begin();
        this.playerContainer.findName("PlaySymbol_Show").Begin();
        this.player.Stop();
    },
    //Event handler for mute button click.
    MuteButton_MouseDown: function(sender, eventArgs)
    {
        var muted = !this.player.IsMuted;
        this.player.IsMuted = muted;        
        this.playerContainer.findName("Mute" + (!muted ? "On" : "Off") + "Symbol_Hide").Begin();
        this.playerContainer.findName("Mute" + (muted ? "On" : "Off") + "Symbol_Show").Begin();
        
    },
    //Event handler for toggling the shown state of the player container.
    PlayerContainer_MouseMove: function(sender, eventArgs)
    {
        if (!this.playerControlsDisplayed)
            this.ShowControls(true);
        if (this.playerControlsHideTimeout)
            clearTimeout(this.playerControlsHideTimeout);
        this.playerControlsHideTimeout = setTimeout("moviePlayer.ShowControls(false);", this.playerControlsHideTimeoutDuration);
    },
    //Event handler for mousing off of the player container.
    PlayerContainer_MouseLeave: function(sender, eventArgs)
    {   
        clearTimeout(this.playerControlsHideTimeout);
        this.playerControlsHideTimeout = setTimeout("moviePlayer.ShowControls(false);", this.playerControlsHideTimeoutDuration);
    },
    //Event handler for mousing over the player controls.
    PlayerControls_MouseEnter: function(sender, eventArgs)
    {
        clearTimeout(this.playerControlsHideTimeout);
        this.playerControlsHideTimeout = setTimeout("moviePlayer.ShowControls(false);", this.playerControlsHideTimeoutDuration);
    },
    //Event handler for toggling the shown state of the player controls.
    PlayerControls_MouseMove: function(sender, eventArgs)
    {
        if (!this.playerControlsDisplayed)
            this.ShowControls(true);
        if (this.playerControlsHideTimeout)
            clearTimeout(this.playerControlsHideTimeout);
        this.playerControlsHideTimeout = setTimeout("moviePlayer.ShowControls(false);", this.playerControlsHideTimeoutDuration);
    },
    //Function to toggle the  visibility of the video player controls.
    ShowControls: function(visible)
    {
        if (this.playerControlsDisplayed == visible) return;
        this.playerControlsDisplayed = visible;
        
        if (visible)
            this.playerContainer.findName("PlayerControls_Show").Begin();
        else
            this.playerContainer.findName("PlayerControls_Hide").Begin();
    },
    //Event handler for mouse over of the full screen button.
    FullScreenButton_MouseEnter: function(sender, eventArgs)
    {
        sender.findName("FullScreenButton_MouseLeave").Stop();
        sender.findName("FullScreenButton_MouseEnter").Begin();        
    },
    //Event handler for mouse out of the full screen button.
    FullScreenButton_MouseLeave: function(sender, eventArgs)
    {
        sender.findName("FullScreenButton_MouseEnter").Stop();
        sender.findName("FullScreenButton_MouseLeave").Begin();
    },
    //Event handler for a click of the full screen button.
    FullScreenButton_MouseDown: function(sender, eventArgs)
    {
        this.pluginContent.fullscreen = true;
    },
    //Event handler resising the video player when full screen changes.
    onFullScreenChanged: function (sender, eventArgs)
    {
        if (this.pluginContent.fullscreen)
        {
            this.playerContainer["Canvas.Top"] = 0;
            this.playerContainer["Canvas.Left"] = 0;
            this.playerContainer["Width"] = this.pluginContent.actualWidth;
            this.playerContainer["Height"] = this.pluginContent.actualHeight;

            this.playerControls["Canvas.Left"] = Math.floor((this.playerContainer["Width"] / 2 - 712.913 / 2) * 1.5 * 1000) / 1000;
            this.playerControls["Canvas.Top"] = this.playerControls_initialTop * this.playerContainer["Height"] / this.initialHeight;
            
            this.playerContainer["Canvas.ZIndex"] = 500;
            sender.findName("FullScreenButton").Visibility = "Collapsed";
            sender.findName("PlayerControls_Show_FullScreen").Begin();
        }
        else
        {
            this.playerContainer["Canvas.Top"] = this.initialTop;
            this.playerContainer["Canvas.Left"] = this.initialLeft;
            this.playerContainer["Width"] = this.initialWidth;
            this.playerContainer["Height"] = this.initialHeight;
            this.playerContainer["Canvas.ZIndex"] = this.initialZIndex;
            this.playerControls["Canvas.Top"] = this.playerControls_initialTop;
            this.playerControls["Canvas.Left"] = this.playerControls_initialLeft;

            sender.findName("FullScreenButton").Visibility = "Visible";
            sender.findName("PlayerControls_Hide_FullScreen").Begin();
        }
    
        this.player.width =  this.playerContainer["Width"];
        this.player.height = this.playerContainer["Height"];
    },
    //Event handler firing when the state of the media element changes.
    MediaStateChanged: function(sender, eventArgs)
    {    
        if (this.player.CurrentState == "Paused" || this.player.CurrentState == "Stopped")
        {
            this.playerContainer.findName("PauseSymbol_Hide").Begin();
            this.playerContainer.findName("PlaySymbol_Show").Begin();
        }
        else if (this.player.CurrentState == "Playing")
        {
            this.playerContainer.findName("PlaySymbol_Hide").Begin();
            this.playerContainer.findName("PauseSymbol_Show").Begin();
        }            
        if (sender.CurrentState == "Playing" && sender.CanSeek)
        {
            this.timelineUpdateInterval = setInterval("moviePlayer.SetTimelinePosition()", 100);
        }
        else if (this.timelineUpdateInterval)
        {
            clearInterval(this.timelineUpdateInterval);
        }
    },
    //Function for handling timeline dragging.
    SetTimelinePosition: function()
    {
        if (!this.timeHandleIsDragging && this.player.NaturalDuration.Seconds > 0)
        {
            if (this.player.Position.Seconds > this.player.NaturalDuration.Seconds)
                this.player.Position.Seconds = this.player.NaturalDuration.Seconds;
            var percentComplete = this.player.Position.Seconds / this.player.NaturalDuration.Seconds;
            var thumb = this.player.findName("TimeThumb");
            
            if (!this.timelineThumbLeftPad)
                this.timelineThumbLeftPad = thumb["Canvas.Left"];

            thumb["Canvas.Left"] = Math.floor((this.timeline.width * percentComplete - thumb.width / 2) * 1000) / 1000;
        }
    },
    //Event handler for clicking on time handle.
    TimeHandle_MouseDown: function(sender, mouseEventArgs)
    {
        if (this.player.CanSeek)
        {
            this.timeHandle.CaptureMouse();
            this.timeHandleLastPoint = mouseEventArgs.GetPosition(this.timeline);
            this.timeHandleIsDragging = true;
        }
    },
    //Event handler to handle the mouse button being released after a click on the time handle.
    TimeHandle_MouseUp: function(sender, mouseEventArgs)
    {
        if (this.player.CanSeek)
        {
            this.timeHandle.ReleaseMouseCapture();
            this.timeHandleIsDragging = false;
            
            // translate handle position to movie position
            if (this.timeHandleLastPoint.X > this.timeline.width)
                this.timeHandleLastPoint.X = this.timeline.width;
            var percentComplete = this.timeHandleLastPoint.X / this.timeline.width;
            var seconds = percentComplete * this.player.NaturalDuration.Seconds;
            
            var hrs = (Math.floor(seconds / 3600) < 10 ? "0" : "") + Math.floor(seconds / 3600);
            seconds = seconds - (hrs * 3600);
            var min = (Math.floor(seconds / 60) < 10 ? "0" : "") + Math.floor(seconds / 60);
            seconds = (Math.floor(seconds) < 10 ? "0" : "") + (seconds - (min * 60));
            if (seconds.length > 4)
                seconds = seconds.substring(0,4);

            this.player.Position = "" + hrs + ":" + min + ":" + seconds;
        }
    },
    //Event handler to handle dragging of the time handle.
    TimeHandle_MouseMove: function(sender, mouseEventArgs)
    {
        if (this.timeHandleIsDragging && this.player.CanSeek)
        {
            var point = mouseEventArgs.GetPosition(this.timeline);
            if (point.X > this.timeline.width)
                point.X = this.timeline.width;
            if (point.X >= 0 && point.X <= this.timeline.width)
            {
                this.timeHandle["Canvas.Left"] = point.X - (this.timeHandle.Width / 2);        
                this.timeHandleLastPoint = point;
            }            
        }
    },
    //Event handler to handle a mouse down on the volume handle.
    VolumeHandle_MouseDown: function(sender, mouseEventArgs)
    {
        this.volumeHandle.CaptureMouse();
        this.volumeHandleLastPoint = mouseEventArgs.GetPosition(this.volumeSlider);
        this.volumeHandleIsDragging = true;
    },
    //Event handler to handle a mouse up on the volume handle.
    VolumeHandle_MouseUp: function(sender, mouseEventArgs)
    {
        this.volumeHandle.ReleaseMouseCapture();
        this.volumeHandleIsDragging = false;
    },
    //Event handler to handle a mouse move while the volume handle is dragging.
    VolumeHandle_MouseMove: function(sender, mouseEventArgs)
    {
        if (this.volumeHandleIsDragging)
        {
            var point = mouseEventArgs.GetPosition(this.volumeSlider);
            if (point.X >= 0 && point.X <= this.volumeSlider.width)
            {
                this.volumeHandle["Canvas.Left"] = point.X - (this.volumeHandle.Width / 2);                
                this.volumeHandleLastPoint = point;
                // set volume to nearest hundredth
                this.player.volume = Math.floor(point.X / this.volumeSlider.width * 100) / 100;
            }
            
        }
    }
};