
if (!window.CwcPlayer)
	window.CwcPlayer = {};

CwcPlayer.Scene = function(aTargetObject, aBgImage) {
    this.BgImage = aBgImage;
    this.startWidth = 0;
    this.startHeight = 0;
    this.startPosition = 0;
    this.plugIn = null;
    this.targetObject = aTargetObject;
    this.clip = "";
    this.isScrubbing = false;
    this.isAudioScrubbing = false;
    this.isPP = false;
    this.oldState = 0;
}

CwcPlayer.Scene.prototype =
{
    Init: function(plugIn, userContext, rootElement) {
        this.plugIn = plugIn;
        this.plugIn.content.onFullScreenChange = this.handleFullScreenChanged;
        this.plugIn.content.onResize = this.handleResize;

        this.theCanvas = rootElement.children.findName("theCanvas");
        this.GridBackgroundImage= rootElement.children.findName("GridBackgroundImage");
        this.backgroundImage = rootElement.children.findName("BackgroundImage");
        if (this.BgImage != "") try { this.backgroundImage.Source = this.BgImage; } catch (ex) { }

        this.timer = rootElement.children.findName("theTimer");
        this.timer.addEventListener("Completed", Silverlight.createDelegate(this, this.UpdateMediaPosition));
        this.timer.begin();
        this.scrubber = rootElement.children.findName("scrubber");
        this.scrubber.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleStartScrub));
        this.scrubber.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.handleEndScrub));

        // Sample button event hookup: Find the button and then attach event handlers
        this.playButton = rootElement.children.findName("playButton");
        this.playButton.addEventListener("MouseEnter", Silverlight.createDelegate(this, this.handleMouseEnterPlayPauseCanvas));
        this.playButton.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleMouseDownPlayPauseCanvas));
        this.playButton.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.handleMouseUpPlayPauseCanvas));
        this.playButton.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.handleMouseLeavePlayPauseCanvas));
        this.playPauseCanvas = rootElement.children.findName("PlayPauseCanvas");

        this.mediaPlayer = rootElement.children.findName("MediaElementPlayer");
        this.mediaPlayer.BufferingTime = "00:00:05";
        this.mediaPlayer.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.handleMouseUpPlayPauseCanvas));
        this.mediaPlayer.addEventListener("CurrentStateChanged", Silverlight.createDelegate(this, this.handleCurrentStateChanged));
        this.mediaPlayer.addEventListener("BufferingProgressChanged", Silverlight.createDelegate(this, this.handleBufferingProgressChanged));
        this.mediaPlayer.addEventListener("MarkerReached", Silverlight.createDelegate(this, this.handleMarkerReached));
        this.mediaPlayer.addEventListener("MediaFailed", Silverlight.createDelegate(this, this.handleMediaPlayerError));
        this.mediaPlayer.addEventListener("MediaEnded", Silverlight.createDelegate(this, this.handleMediaEnded));
        this.mediaPlayer.addEventListener("MediaOpened", Silverlight.createDelegate(this, this.handleMediaOpened));

        this.controlBarGradient = rootElement.children.findName("controlBarGradient");
        this.controlBar = rootElement.children.findName("ControlBar");
        this.controlBar.addEventListener("MouseMove", Silverlight.createDelegate(this, this.handleScrub));
        this.controlBar.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.ReleaseScrubbers));

        this.progressBar = rootElement.children.findName("progressBar");
        this.mediaPosition = rootElement.children.findName("TextBlockMediaPosition")

        this.muteButton = rootElement.children.findName("muteButton");
        this.muteButton.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.toggleMute));

        this.audioLevelBar = rootElement.children.findName("audioLevelBar");
        this.audioLevelBar.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleStartAudioScrub));
        this.audioLevelBar.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.handleEndAudioScrub));

        this.audioLevels = rootElement.children.findName("audioLevels");
        this.audioLevel = new Array(rootElement.children.findName("audioLevel_1"),
		                                rootElement.children.findName("audioLevel_2"),
		                                rootElement.children.findName("audioLevel_3"),
		                                rootElement.children.findName("audioLevel_4"),
		                                rootElement.children.findName("audioLevel_5"),
		                                rootElement.children.findName("audioLevel_6"),
		                                rootElement.children.findName("audioLevel_7"),
		                                rootElement.children.findName("audioLevel_8"));
        this.fullScreenButton = rootElement.children.findName("fullScreenButton");
        this.fullScreenButton.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.ToggleFullscreen));
        this.mediaPlayer.volume = 1.0;
        this.UpdateVolume(this.mediaPlayer.volume);

        if (this.clip != "") this.LoadMovie(this.clip, this.startPosition);
        if (this.startWidth > 0) this.UpdateLayout(this.startWidth, this.startHeight);
    },

    //When the end of the movie is reached, return the movie to the start and play it again
    handleMediaEnded: function(sender, eventArgs) {
        if (!this.isPP) {
            sender.Position = "00:00:00";
            sender.play();
        }
    },

    handleBufferingProgressChanged: function(sender, eventArgs) {
        this.SetBufferingProgress();
    },

    SetBufferingProgress: function() {
        this.mediaPosition.Text = "        " + Math.round(this.mediaPlayer.BufferingProgress * 100) + "%";
    },

    ReleaseScrubbers: function(sender, args) {
        if (this.isScrubbing) {
            this.isScrubbing = false;
            sender.findName("deHighlightScrubber").begin();
        }
        this.isAudioScrubbing = false;
    },

    LoadMovie: function(aClip, aPosition) {
        this.clip = aClip;
        this.startPosition = aPosition;
        if (this.clip.indexOf(".wmv") < 0 && this.clip.indexOf(".asf") < 0) this.isPP = true; else this.isPP = false;
        if (this.mediaPlayer) {
            this.mediaPlayer.Source = this.clip;
            if (this.isPP) {
                this.scrubber.Visibility = "Collapsed";
                this.progressBar.Visibility = "Collapsed";
            } else {
                this.progressBar.Visibility = "Visible";
                this.scrubber.Visibility = "Visible";
            }
        }
    },

    handleMediaOpened: function(sender, args) {
        if (this.startPosition > 0) this.SetMediaPosition(this.startPosition);
        this.startPosition = 0;

    },

    handleMarkerReached: function(sender, args) {
        try { DoScriptCommand(args.marker.type, args.marker.text); } catch (e) { }
    },

    UpdateLayout: function(aWidth, aHeight) {
        if (this.startWidth == 0) this.startWidth = aWidth;
        if (this.startHeight == 0) this.startHeight = aHeight;
        try {
            this.mediaPlayer.Width = aWidth;
            this.mediaPlayer.Height = aHeight;
            this.GridBackgroundImage.Width = aWidth;
            this.GridBackgroundImage.Height = aHeight;
            this.controlBar.Width = aWidth;
            this.controlBar["Canvas.Top"] = aHeight;
            this.controlBarGradient.Width = aWidth;
            this.scrubber.Width = aWidth - 100;
            this.mediaPosition["Canvas.Left"] = aWidth / 2 - 60;
            this.muteButton["Canvas.Left"] = aWidth - 70;
            this.audioLevels["Canvas.Left"] = aWidth - 50;
            this.fullScreenButton["Canvas.Left"] = aWidth - 18;
            this.UpdateScrubber(this, this.mediaPlayer.Position.Seconds);
            this.audioLevelBar["Canvas.Left"] = aWidth - 55;
            if (aWidth > this.backgroundImage.Width && this.backgroundImage.Width > 0 && aWidth > 0) {
                this.backgroundImage["Canvas.Left"] = aWidth / 2 - this.backgroundImage.Width / 2;
                this.backgroundImage["Canvas.Top"] = aHeight / 2 - this.backgroundImage.Height / 2;
            } else {
                this.backgroundImage["Canvas.Left"] = 0;
                this.backgroundImage["Canvas.Top"] = 0;
            }
        } catch (ex) { }
    },

    UpdateVolume: function(volume) {
        var volume = volume * 8;
        for (var i = 0; i < 8; i++) {
            if (i < volume)
                this.audioLevel[i].Opacity = 1.0;
            else
                this.audioLevel[i].Opacity = 0.3;
        }
    },

    handleResize: function(sender, args) {
        scene.UpdateLayout(scene.plugIn.content.ActualWidth, scene.plugIn.content.ActualHeight - 20);
    },

    ToggleFullscreen: function(sender, args) {
        if (!this.isScrubbing) this.plugIn.content.fullScreen = !this.plugIn.content.fullScreen;
    },

    IsFullScreen: function() {
        if (this.plugIn != null)
            return this.plugIn.content.fullScreen;
        else
            return false;
    },

    toggleMute: function(sender, args) {
        this.mediaPlayer.IsMuted = !this.mediaPlayer.IsMuted;
        if (this.mediaPlayer.IsMuted) {
            sender.findName("muteOn").begin();
            this.UpdateVolume(0);
        } else {
            sender.findName("muteOff").begin();
            this.UpdateVolume(this.mediaPlayer.volume);
        }
    },

    handleFullScreenChanged: function(sender, args) { if (scene.plugIn.content.fullScreen) scene.UpdateLayout(scene.plugIn.content.ActualWidth, scene.plugIn.content.ActualHeight - 20); },
    handleMouseEnterPlayPauseCanvas: function(sender, eventArgs) { sender.findName("mouseEnterPlayPauseCanvas").begin(); },
    handleMouseDownPlayPauseCanvas: function(sender, eventArgs) { sender.findName("mouseDownPlayPauseCanvas").begin(); },
    handleMouseLeavePlayPauseCanvas: function(sender, eventArgs) { sender.findName("mouseLeavePlayPauseCanvas").begin(); },
    handleMouseUpPlayPauseCanvas: function(sender, eventArgs) {
        sender.findName("mouseUpPlayPauseCanvas").begin();
        if (this.mediaPlayer.currentState == "Playing") {
            if (this.isPP) {
                this.mediaPlayer.Stop();
            } else {
                this.mediaPlayer.Pause();
            }
        } else
            this.mediaPlayer.Play();
    },


    handleCurrentStateChanged: function(sender, args) {
        var newState = 0;
        if (this.isPP && this.mediaPlayer.CurrentState == "Closed") {
            this.mediaPlayer.Source = this.clip;
            this.mediaPlayer.Play();
        }
        else if (this.mediaPlayer.CurrentState == "Playing") {
            sender.findName("playAnim").begin();
            newState = 2;
        }
        else if (this.mediaPlayer.CurrentState == "Opening") {
            this.SetBufferingProgress();
        }
        else {
            if (this.mediaPlayer.CurrentState == "Paused" || this.mediaPlayer.CurrentState == "Stopped") {
                sender.findName("pauseAnim").begin();
            } else {
                sender.findName("playAnim").begin();
                newState = 2;
            }

            this.mediaPosition.Text = "        " + this.mediaPlayer.CurrentState;
        }
        if (this.isPP) {
            if (this.mediaPlayer.CurrentState == "Stopped")
                this.playPauseCanvas.Visibility = "Visible";
        }
        DoPlayerStateChange(this.oldState, newState);
        this.oldState = newState;
    },

    UpdateMediaPosition: function(sender, args) {
        if (this.mediaPlayer.CurrentState == "Playing" && !this.isScrubbing) {
            this.UpdateScrubber(sender, this.mediaPlayer.Position.Seconds);
        }
        this.timer.begin();
    },

    changeMediaPosition: function(sender, args) {
        var pt = args.getPosition(this.scrubber);
        var newPos = this.mediaPlayer.Position;
        newPos.Seconds = (pt.x / (this.scrubber.Width - 2) * this.mediaPlayer.NaturalDuration.Seconds);
        if (newPos.Seconds > this.mediaPlayer.NaturalDuration.Seconds) newPos.Seconds = this.mediaPlayer.NaturalDuration.Seconds - 1;
        if (newPos.Seconds < 0) newPos = 0;

        //update mediaPlayer and scrubber
        this.mediaPlayer.Position = newPos;
        this.UpdateScrubber(sender, newPos.Seconds);
    },

    handleMediaPlayerError: function(sender, args) {
        if (this.isPP) this.LoadMovie(this.clip);
    },

    UpdateScrubber: function(sender, newPos) {
        //update ui
        if (this.isPP)
            this.mediaPosition.Text = "          streaming"; //Live";
        else {
            if (newPos < 0) newPos = 0;
            var newSize = Math.round(newPos / this.mediaPlayer.NaturalDuration.Seconds * (this.scrubber.Width - 2));
            if (newSize >= 0) this.progressBar.Width = newSize;
            this.mediaPosition.Text = this.GetTimeFromSeconds(newPos) + " / " + this.GetTimeFromSeconds(this.mediaPlayer.NaturalDuration.Seconds)
        }

    },

    GetTimeFromSeconds: function(aSeconds) {
        var hours = Math.floor(aSeconds / 3600) % 60;
        if (hours < 1) hours = "0:"; else hours += ":";
        var minutes = Math.floor(aSeconds / 60) % 60;
        if (hours.length > 0 && minutes < 10) minutes = "0" + minutes;
        var seconds = Math.floor(aSeconds) % 60;
        if (seconds < 10) seconds = "0" + seconds;
        return "" + hours + minutes + ":" + seconds;
    },

    handleStartAudioScrub: function(sender, args) {
        this.isAudioScrubbing = true;
    },

    handleEndAudioScrub: function(sender, args) {
        this.handleScrub(sender, args);
        this.isAudioScrubbing = false;
    },

    handleStartScrub: function(sender, args) {
        this.isScrubbing = true;
        sender.findName("highlightScrubber").begin();
    },

    handleEndScrub: function(sender, args) {
        this.isScrubbing = false;
        this.changeMediaPosition(sender, args);
        sender.findName("deHighlightScrubber").begin();
    },

    handleScrub: function(sender, args) {
        if (this.isScrubbing) {
            var pt = args.getPosition(this.scrubber);
            var newPos = this.mediaPlayer.Position;
            newPos.Seconds = (pt.x / (this.scrubber.Width - 2) * this.mediaPlayer.NaturalDuration.Seconds);
            if (pt.x < 0) newPos.Seconds = 0;
            if (newPos.Seconds > this.mediaPlayer.NaturalDuration.Seconds) newPos.Seconds = this.mediaPlayer.NaturalDuration.Seconds - 1;
            if (newPos.Seconds < 0) newPos = 0;
            this.UpdateScrubber(sender, newPos.Seconds);
        }
        if (this.isAudioScrubbing) {
            var newVolume = args.getPosition(this.audioLevelBar).x / 30;
            if (newVolume < 0) newVolume = 0;
            if (newVolume > 1) newVolume = 1;
            this.mediaPlayer.volume = newVolume;
            if (this.mediaPlayer.IsMuted) {
                sender.findName("muteOff").begin();
                this.mediaPlayer.IsMuted = false;
            }
            this.UpdateVolume(this.mediaPlayer.volume);
        }
    },

    SetMediaPosition: function(aPos) {
        if (aPos == NaN) aPos = 0;
        //update mediaPlayer and scrubber
        var newPos = this.mediaPlayer.Position
        newPos.Seconds = aPos;
        this.mediaPlayer.Position = newPos
        this.UpdateScrubber(this.plugIn, aPos);
    },

    SetBackgroundImage: function(aBgImage) {
        this.BgImage = aBgImage;
        try { this.backgroundImage.Source = this.BgImage; } catch (ex) { }
    }
}

 
