﻿/// <reference name="MicrosoftAjax.js"/>

// EXPECTED PAGE TRACKING FUNCTION
// function mediaEvent(mediaName, eventName, isSilverlight) { }

Type.registerNamespace("WindowsSite.Silverlight.UserControls");

WindowsSite.Silverlight.UserControls.SingleVideoPlayer = function(element) {
	WindowsSite.Silverlight.UserControls.SingleVideoPlayer.initializeBase(this, [element]);
	currentMedia = null;
	currentMediaName = null;
	showPanelID = null;
	hidePanelID = null;
}

WindowsSite.Silverlight.UserControls.SingleVideoPlayer.prototype = {
    initialize: function() {
        WindowsSite.Silverlight.UserControls.SingleVideoPlayer.callBaseMethod(this, 'initialize');

        this.UpdateCurrentMediaData();
        if (!this.IsSilverlightPresent() && this.get_AutoPlay()) {
            //this.LoadVideo();
        }
    },
    dispose: function() {
        WindowsSite.Silverlight.UserControls.SingleVideoPlayer.callBaseMethod(this, 'dispose');
    },

    //******************************************
    //	Parameters
    //******************************************
    get_showPanelID: function() {
        return this._width;
    },
    set_showPanelID: function(value) {
        if (this.showPanelID != value) {
            this.showPanelID = value;
            this.raisePropertyChanged('ShowPanelID');
        }
    },
    get_Width: function() {
        return this._width;
    },
    set_Width: function(value) {
        if (this._width != value) {
            this._width = parseInt(value);
            this.raisePropertyChanged('Width');
        }
    },
    get_Height: function() {
        return this._height;
    },
    set_Height: function(value) {
        if (this._height != value) {
            this._height = parseInt(value);
            this.raisePropertyChanged('Height');
        }
    },
    get_DownlevelAddControlSpace: function() {
        return this._downlevelAddControlSpace;
    },
    set_DownlevelAddControlSpace: function(value) {
        if (this._downlevelAddControlSpace != value) {
            this._downlevelAddControlSpace = value;
            this.raisePropertyChanged('DownlevelAddControlSpace');
        }
    },
    get_InitParams: function() {
        return this._initParams.join(',');
    },
    set_InitParams: function(value) {
        var newvalue = value.split(',');
        if (this._initParams != newvalue) {
            this._initParams = newvalue;
            this.raisePropertyChanged('InitParams');
        }
        if (newvalue.length > 0) {
            var init_num = 0;
            while (init_num < newvalue.length) {
                try {
                    var key_array = newvalue[init_num].split("=");
                    if (key_array[0] == "PanelToShowOnEnded") {
                        var testshowPanelID = key_array[1];
                        if (testshowPanelID != "")
                            showPanelID = testshowPanelID;
                    }
                    if (key_array[0] == "PanelToHideOnEnded") {
                        var testhidePanelID = key_array[1];
                        if (testhidePanelID != "")
                            hidePanelID = testhidePanelID;
                    }
                }
                catch (ex) { }
                init_num += 1;
            }
        }
    },
    get_WmpVideoUrl: function() {
        return this._wmpVideoUrl;
    },
    set_WmpVideoUrl: function(value) {
        if (this._wmpVideoUrl != value) {
            this._wmpVideoUrl = value;
            this.raisePropertyChanged('WmpVideoUrl');
        }
    },
    get_AutoPlay: function() {
        return this._autoPlay;
    },
    set_AutoPlay: function(value) {
        if (this._autoPlay != value) {
            this._autoPlay = value;
            if (this.IsSilverlightPresent()) this.get_SilverlightObject().content.SingleVideoPlayer.AutoPlay = value;
            this.UpdateInitParam('AutoPlay', this._autoPlay);
            this.raisePropertyChanged('AutoPlay');
        }
    },
    get_WindowlessMode: function() {
        return this._windowlessMode;
    },
    set_WindowlessMode: function(value) {
        if (this._windowlessMode != value) {
            this._windowlessMode = value;
            this.raisePropertyChanged('WindowlessMode');
        }
    },
    get_SelectedMediaName: function() {
        return this._selectedMediaName;
    },
    set_SelectedMediaName: function(value) {
        if (this._selectedMediaName != value) {
            this._selectedMediaName = value;
            if (value != "") {
                this.UpdateCurrentMediaData();
            }
            this.UpdateInitParam('SelectedMediaName', this._selectedMediaName);
            this.raisePropertyChanged('SelectedMediaName');
        }
    },
    get_MediaData: function() {
        return this._mediaData;
    },
    set_MediaData: function(value) {
        if (this._mediaData != value) {
            this._mediaData = value;
            this.raisePropertyChanged('MediaData');
        }
    },
    get_XapSource: function() {
        return this._xapSource;
    },
    set_XapSource: function(value) {
        if (this._xapSource != value) {
            this._xapSource = value;
            this.raisePropertyChanged('XapSource');
        }
    },
    get_SilverlightObject: function() { return $get(this._silverlightObjectID); },
    get_SilverlightObjectID: function() {
        return this._silverlightObjectID;
    },
    set_SilverlightObjectID: function(value) {
        if (this._silverlightObjectID != value) {
            this._silverlightObjectID = value;
            this.raisePropertyChanged('SilverlightObjectID');
        }
    },
    get_VideoHost: function() { return $get(this._videoHostID); },
    get_VideoHostID: function() {
        return this._videoHostID;
    },
    set_VideoHostID: function(value) {
        if (this._videoHostID != value) {
            this._videoHostID = value;
            this.raisePropertyChanged('VideoHostID');
        }
    },
    get_WmpObject: function() { return $get(this._wmpObjectID); },
    get_WmpObjectID: function() {
        return this._wmpObjectID;
    },
    set_WmpObjectID: function(value) {
        if (this._wmpObjectID != value) {
            this._wmpObjectID = value;
            this.raisePropertyChanged('WmpObjectID');
        }
    },

    //******************************************
    //	Other functions
    //******************************************
    IsSilverlightPresent: function() {
        try {
            return (this.get_SilverlightObject() != null && this.get_SilverlightObject().content != null);
        }
        catch (ex) { return false; }
    },

    PlaySilverlight: function() {
        if (this.IsSilverlightPresent()) {
            this.get_SilverlightObject().content.SingleVideoPlayer.PlayMedia();
        }
    },

    PauseSilverlight: function() {
        if (this.IsSilverlightPresent()) {
            this.get_SilverlightObject().content.SingleVideoPlayer.PauseMedia();
        }
    },

    StopSilverlight: function() {
        if (this.IsSilverlightPresent()) {
            this.get_SilverlightObject().content.SingleVideoPlayer.StopMedia();
        }
    },

    UnloadSilverlightMedia: function() {
        if (this.IsSilverlightPresent()) {
            this.get_SilverlightObject().content.SingleVideoPlayer.UnloadMedia();
        }
    },

    UpdateCurrentMediaData: function() {
        var selectedMedia = this.GetSelectedMediaData();
        if (selectedMedia) {
            this.set_WmpVideoUrl(selectedMedia.MediaUrl);
            currentMediaName = selectedMedia.Name;
        }
    },

    GetSelectedMediaData: function() {
        for (var index in this.get_MediaData()) {
            if (this.get_MediaData()[index].Name == this.get_SelectedMediaName())
                return this.get_MediaData()[index];
        }
        return null;
    },

    SetMediaReference: function(referenceName, autoPlay) {
        this.set_AutoPlay((autoPlay != null) ? autoPlay : true);
        this.set_SelectedMediaName(referenceName);
        if (this.IsSilverlightPresent()) {
            try {
                this.get_SilverlightObject().content.SingleVideoPlayer.SetMediaReference(referenceName);
            }
            catch (e) { }
        }
        else {
            this.CreatePlayer();
            this.CreateWmpModalListener();
        }
    },
    Position: function() {
        if (this.IsSilverlightPresent()) {
            return this.get_SilverlightObject().content.SingleVideoPlayer.Position;
        }
        else return -1;
    },
    TotalDuration: function() {
        if (this.IsSilverlightPresent()) {
            return this.get_SilverlightObject().content.SingleVideoPlayer.TotalDuration;
        }
        else return -1;
    },
    SetMediaSource: function(mediaPath, alternateMediaPath) {
        if (this.IsSilverlightPresent()) {
            this.get_SilverlightObject().content.SingleVideoPlayer.SetMediaSource(mediaPath);
        }
        else {
            // if specified, alternateMediaPath will load in Wmp player.  Otherwise, mediaPath loads in either player
            var path = (f != null) ? alternateMediaPath : mediaPath;
            this.set_WmpVideoUrl(path);
            this.CreatePlayer();
        }
    },
    CreatePlayer: function() {
        var media_embed;
        if (Silverlight.isInstalled('2.0')) {
            media_embed = this.GetSilverlightMarkup();
        }
        else {
            media_embed = this.GetWmpMarkup();
        }
        this.get_VideoHost().innerHTML = media_embed;
    },
    CreateWmpModalListener: function() {
        if (!Silverlight.isInstalled('2.0')) {
            if (currentMedia) {
                if (currentMedia.controls) {
                    currentMedia.controls.stop();
                    currentMedia.detachEvent("PlayStateChange", this.wmpPlayStateChange);
                }
                else
                    currentMedia.removeEventListener("PlayStateChange", this.wmpPlayStateChange, false);
                currentMedia = null;
            }

            currentMedia = $get(this.get_WmpObjectID());
            if (currentMedia.attachEvent)
                currentMedia.attachEvent("PlayStateChange", this.wmpPlayStateChange);
            else
                currentMedia.addEventListener("PlayStateChange", this.wmpPlayStateChange, false);

        }
    },
    CreateWmp: function() {
        if (!Silverlight.isInstalled('2.0')) {
            if (currentMedia) {
                if (currentMedia.controls) {
                    currentMedia.controls.stop();
                    currentMedia.detachEvent("PlayStateChange", this.wmpPlayStateChange);
                }
                else
                    currentMedia.removeEventListener("PlayStateChange", this.wmpPlayStateChange, false);
                currentMedia = null;
            }

            var wmv_embed = this.GetWmpMarkup();

            this.get_VideoHost().innerHTML = wmv_embed;
            currentMedia = $get(this.get_WmpObjectID());
            if (currentMedia.attachEvent)
                currentMedia.attachEvent("PlayStateChange", this.wmpPlayStateChange);
            else
                currentMedia.addEventListener("PlayStateChange", this.wmpPlayStateChange, false);

        }
    },

    SetShowHide: function(panelToShow, panelToHide) {
        if (panelToShow != "") {
            showPanelID = panelToShow;
            hidePanelID = panelToHide;
        }
    },
    GetSilverlightMarkup: function() {
        var sl_embed = '<object id=' + this.get_SilverlightObjectID() + ' data="data:application/x-silverlight-2," type="application/x-silverlight-2" width=' + this.get_Width() + ' height=' + this.get_Height() + '>';
        sl_embed += '<param name="source" value="' + this.get_XapSource() + '"/>';
        sl_embed += '<param name="onerror" value="onSilverlightError" />';
        sl_embed += '<param name="background" value="black" />';
        sl_embed += '<param name="minRuntimeVersion" value="2.0.31005.0" />';
        sl_embed += '<param name="autoUpgrade" value="true" />';
        sl_embed += '<param name="windowless" value="' + ((this.get_WindowlessMode()) ? 'true' : 'false') + '" />';
        sl_embed += '<param name="initParams" value="' + this.get_InitParams() + '" />';
        sl_embed += '</object>';
        return sl_embed;
    },
    GetWmpMarkup: function() {
        var autoplay = '1';
        if (!this.get_AutoPlay())
            autoplay = '0';
        var height = this.get_Height();
        if (this.get_DownlevelAddControlSpace()) height += 64;
        var wmv_embed = '<object width="' + this.get_Width() + '" height="' + height + '" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" '
        wmv_embed += 'type="application/x-ms-wmp" id="' + this.get_WmpObjectID() + '">'; ;
        wmv_embed += '<param value="' + this.get_WmpVideoUrl() + '" name="url" id="wmv_url" />'; //mjr 080905 for testing only
        wmv_embed += '<param value="false" name="ShowStatusBar"/>';
        wmv_embed += '<param value="' + autoplay + '" name="autoStart"/>';
        wmv_embed += '<param value="true" name="stretchToFit"/>';
        wmv_embed += '<param value="true" name="windowlessVideo"/>';
        wmv_embed += '<embed width="' + this.get_Width() + '" height="' + height + '" autosize="true" autostart="1" ';
        wmv_embed += 'showstatusbar="false" showdisplay="0" showcontrols="true" ';
        wmv_embed += 'name="MediaPlayer" id="' + this.get_WmpObjectID() + '" ';
        wmv_embed += 'src="' + this.get_WmpVideoUrl() + '" '; //mjr 080905 for testing only
        wmv_embed += 'pluginspage="http://www.microsoft.com/Windows/MediaPlayer/" ';
        wmv_embed += 'type="application/x-mplayer2" />';
        wmv_embed += '</object>';
        return wmv_embed;
    },

    DestroyPlayer: function() {

        if (!Silverlight.isInstalled('2.0')) {
            currentMedia = $get(this.get_WmpObjectID());
            if (currentMedia) {
                if (currentMedia.controls) {
                    currentMedia.controls.stop();
                    currentMedia.detachEvent("PlayStateChange", this.wmpPlayStateChange);
                }
                else
                    currentMedia.removeEventListener("PlayStateChange", this.wmpPlayStateChange, false);

            }
        }
        else {
            this.get_VideoHost().innerHTML = "";
        }
    },

    UpdateInitParam: function(key, value) {
        for (var i in this._initParams) {
            var keyValuePair = key + '=' + value;
            var parts = this._initParams[i].split('=');
            if (parts[0] == key) {
                this._initParams[i] = keyValuePair;
                return;
            }
            Array.add(this._initParams, keyValuePair);
        }
    },

    // for interaction with Windows Ajax controls
    _onControlCommand: function(sender, args) {
        switch (args.get_CommandName()) {
            case "SetMediaReference":
                this.SetMediaReference(args.get_CommandArgument());
                break;
        }
    },

    wmpPlayStateChange: function(newState) {
        // NOTE: this = window, not object
        var videoPos = 1;
        var videoLength = 1;
        // On End Event the CurrentMedia is Null
        try {
            videoPos = Math.round(currentMedia.controls.currentPosition);
            videoLength = Math.round(currentMedia.currentMedia.duration);
        }
        catch (ex) { }
        switch (newState) {
            case 1:
                var fireEvent = this._isVideoStarted;
                this._isVideoStarted = false;
                // stopped code here
                if (fireEvent) {
                    try { mediaEventHandler(currentMediaName, "Stopped", videoPos, false); } catch (ex) { }
                }
                break;
            case 2:
                // paused code here
                try { mediaEventHandler(currentMediaName, "Paused", videoPos, false); } catch (ex) { }
                break;
            case 3:
                // playing code here
                if (!this._isVideoStarted) {
                    this._isVideoStarted = true;
                    // started code here
                    try { mediaEventHandler(currentMediaName, "Started", videoLength, false); } catch (ex) { }
                }
                else {
                    try { mediaEventHandler(currentMediaName, "Restarted", videoLength, false); } catch (ex) { }
                }
                break;
            case 8:
                this._isVideoStarted = false;
                // ended code here
                try {
                    mediaEventHandler(currentMediaName, "Ended", null, false);
                    if (showPanelID) {
                        var sPanel = $get(showPanelID);
                        sPanel.style.display = "block";
                        var hPanel = $get(hidePanelID);
                        hPanel.style.display = "none";

                    }
                } catch (ex) { }
                break;
        }
    }
}
function SilverlightMediaControlHandler(mediaName, eventName, eventArgs) {
    switch (eventName) {	
		case "MediaStarted":
			try { mediaEventHandler(mediaName, "Started", eventArgs, true); } catch (ex) { }
			break;        case "MediaRestarted":            try { mediaEventHandler(mediaName, "Restarted", eventArgs, true); } catch (ex) { }            break;
        case "MediaEnded":            try {                if (showPanelID) {                    var sPanel = $get(showPanelID);                    sPanel.style.display = "block";
                    var hPanel = $get(hidePanelID);                    hPanel.style.display = "none";                }                mediaEventHandler(mediaName, "Ended", eventArgs, true);            } catch (ex) { }            break;
		case "MediaStopped":
			try { mediaEventHandler(mediaName, "Stopped", eventArgs, true); } catch (ex) { }
			break;
		case "MediaPaused":
			try { mediaEventHandler(mediaName, "Paused", eventArgs, true); } catch (ex) { }
			break;
	}
}

WindowsSite.Silverlight.UserControls.SingleVideoPlayer.registerClass('WindowsSite.Silverlight.UserControls.SingleVideoPlayer', Sys.UI.Behavior);

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();