﻿/// <reference name="MicrosoftAjax.js"/>

function MediaPlayer(parentId, mediaSource, captionConfig) {
    this._hostname = ExpressionPlayer.Player._getUniqueName("xamlHost");
    Silverlight.createObjectEx( {   source: 'player.xaml', 
                                    parentElement: $get(parentId ||"divPlayer_0"), 
                                    id:this._hostname, 
                                    properties:{ width:'899px', height:'450px', version:'1.0', background:'#B6AC86', isWindowless:'true', inplaceInstallPrompt:true }, 
                                    events:{ onLoad:Function.createDelegate(this, this._handleLoad) } } );
    this._currentMediainfo = -1;
    this._mediaSource = mediaSource;
    getCaptionData(captionConfig);
}

MediaPlayer.prototype = {
    _handleLoad: function(plugin, userContext, sender) {
        this._player = $create(ExtendedPlayer.Player,
                                  { // properties
                                      autoPlay: false,
                                      muted: this.mutedParam(),
                                      enableCaptions: this.enableCaptionsParam(),
                                      volume: 1.0
                                  },
                                  { // event handlers
                                      mediaEnded: Function.createDelegate(this, this._onMediaEnded),
                                      mediaFailed: Function.createDelegate(this, this._onMediaFailed),
                                      mediaOpened: Function.createDelegate(this, this._onMediaOpened),
                                      currentStateChanged: Function.createDelegate(this, this._onStateChanged),
                                      markerReached: Function.createDelegate(this, this._onMarkerReached)
                                  },
                                  null, $get(this._hostname));
        this._player.set_mediaSource(this._mediaSource);
        this._video = this._player.get_mediaElement();
        this._control = sender;



        // Setup the click event of the What is bar
        sender.findName("WhatIsDynamicsBar").addEventListener('MouseLeftButtonUp', Function.createDelegate(this, this._onWhatIsDynamicsClick));

        // Setup other event handlers
        sender.findName("CaptionToggleButton").addEventListener('MouseLeftButtonUp', Function.createDelegate(this, this._onCaptionToggleClick));
        this._video.addEventListener("DownloadProgressChanged", Function.createDelegate(this, this._onDownloadProgressChanged));
        sender.findName("StopButton").addEventListener('MouseLeftButtonUp', Function.createDelegate(this, this._stopPlayer));
    },

    start: function() {
        try {
            var overlayDiv = document.getElementById('overlayContent');
            var overlayDivStart = document.getElementById('overlayContentStart');
            var overlayDivEnd = document.getElementById('overlayContentEnd');
            if (overlayDiv != null)
                overlayDiv.style.display = 'none';
            if (overlayDivStart != null)
                overlayDivStart.style.display = 'none';
            if (overlayDivEnd != null)
                overlayDivEnd.style.display = 'none';
            this._video.play();
        }
        catch (e) { };
    },

    /* When the media is opened up, load caption text */
    _onMediaOpened: function(sender, eventArgs) {
        if (this._video.markers.count == 0) {
            for (var i = 0; i < ccData.length; i++) {
                var marker = this._video.getHost().content.createFromXaml("<TimelineMarker/>");
                marker.Type = "caption";
                marker.Text = ccData[i].Text;
                marker.Time = ccData[i].Time;
                this._video.markers.add(marker);
            }
        }
    },
    _stopPlayer: function(sendr, eventArgs) {

        this._player.stop();
        this._onMediaEnded();
    },

    _onMediaEnded: function(sender, eventArgs) {

        try {
            this._player.stop();
            var overlayDiv = document.getElementById('overlayContent');
            var overlayDivStart = document.getElementById('overlayContentStart');
            var overlayDivEnd = document.getElementById('overlayContentEnd');
            if (overlayDiv != null)
                overlayDiv.style.display = '';
            if (overlayDivStart != null)
                overlayDivStart.style.display = 'none';
            if (overlayDivEnd != null)
                overlayDivEnd.style.display = '';
        }
        catch (e) { };
    },

    _onMediaFailed: function(sender, eventArgs) {
    alert('The requested media file failed to load in time.  Please refresh the page and try again.');
    },

    _onMarkerReached: function(sender, eventArgs) {
        if (eventArgs.get_marker().type == "caption") {
            this._resizeCaptionText();
        }
    },

    _onDownloadProgressChanged: function(sender, eventArgs) {
        var dld = Math.round(this._video.DownloadProgress * 100);
        var max = this._control.findName("TimeSlider").Width;
        this._control.findName("DownloadProgressSlider").Width = Math.round(max * dld / 100);
    },

    _resizeCaptionText: function() {
        var canvasObj = this._control.findName("CaptionArea");
        if (canvasObj.Visibility == "Visible") {
            canvasObj.Width = "899";
            canvasObj.Height = "30";
            canvasObj.setValue("Canvas.Left", 0);
            canvasObj.setValue("Canvas.Top", 378);

            var textbox = this._control.findName("CaptionText");

            while (textbox.ActualWidth > textbox.Width) {
                textbox.FontSize -= 0.5;
            }

            var newLeft = ((textbox.Width - textbox.ActualWidth) / 2);

            textbox.SetValue("Canvas.Left", newLeft);

            var newTop = ((textbox.Height - textbox.ActualHeight) / 2);

            textbox.SetValue("Canvas.Top", newTop);
        }
    },

    _onStateChanged: function(sender, eventArgs) {
        var state = this._video.CurrentState;
        if (state != this.state) {
            this.state = state;
            this.duration = Math.round(this._video.NaturalDuration.Seconds * 10) / 10;
            if (state != "Playing" && state != "Buffering" && state != "Opening") {
                clearInterval(this.timeint);
            } else {
                this.timeint = setInterval(Function.createDelegate(this, this.timeChanged), 100);
            }
        }
    },

    _onWhatIsDynamicsClick: function() {
        ms.showOffscreen('whatisDynamics');
        TurnOffPopupBackground('popup_background');
        TogglePopupBackground('popup_background');
    },

    _onCaptionToggleClick: function() {
        this.captionStateOn = !this.captionState;
        if (this.captionStateOn) {
            this._control.findName("CaptionArea").Background = "#FF000000";
            this._control.findName("CaptionText").Foreground = "#FFFFFFFF";
        }
        else {
            this._control.findName("CaptionArea").Background = "#00000000";
            this._control.findName("CaptionText").Foreground = "#00FFFFFF";
        }

        this._resizeCaptionText();
    },

    timeChanged: function() {
        var elapsed = Math.round(this._video.Position.Seconds * 10) / 10;
        var max = this._control.findName("TimeSlider").Width;
        if (this.duration > 0) {
            var pos = Math.round(max * elapsed / this.duration);

            this._control.findName("ElapsedText").Text = this.timeString(elapsed) + "/";
            this._control.findName("RemainingText").Text = this.timeString(this.duration - elapsed);
            this._control.findName("TimeHighlight").Width = pos;
        } else {
            this._control.findName("TimeThumb")["Canvas.Left"] = 0;

        }
    },

    timeString: function(stp) {
        var hrs = Math.floor(stp / 3600);
        var min = Math.floor(stp % 3600 / 60);
        var sec = Math.round(stp % 60);
        var str = "";
        sec = sec < 0 ? 0 : sec;
        sec > 9 ? str += sec : str += "0" + sec;
        min = min < 0 ? 0 : min;
        min > 9 ? str = min + ":" + str : str = "0" + min + ":" + str;
        hrs > 0 ? str = hrs + ":" + str : null;
        return str;
    },

    autoPlayParam: function() {
        var autoPlay = true;
        try {
            eval("autoPlay=('True'!=='False')");
        } catch (e) { }
        return autoPlay;
    },

    enableCaptionsParam: function() {
        var enableCaptions = true;
        try {
            eval("enableCaptions=('True'!=='False');");
        } catch (e) { }
        return enableCaptions;
    },

    mutedParam: function() {
        var muted = false;
        try {
            eval("muted=('False'!=='False');");
        } catch (e) { }
        return muted;
    }
}

function StartWithParent(parentId, appId) {
    new MediaPlayer(parentId);
}


function rgbToHex(rgb)
{
	var strHex="0123456789ABCDEF";
	var ichBracket=rgb.indexOf("(");
	if (ichBracket!=-1) {
		var rgstr = rgb.substr(ichBracket+1, rgb.length-ichBracket-2).split(',');
		rgb = "#"+ strHex[parseInt(rgstr[0])>>4]+strHex[parseInt(rgstr[0])%16]+
			   strHex[parseInt(rgstr[1])>>4]+strHex[parseInt(rgstr[1])%16]+
			   strHex[parseInt(rgstr[2])>>4]+strHex[parseInt(rgstr[2])%16];
	}
	return rgb;
}

if (typeof XMLHttpRequest == "undefined")
  XMLHttpRequest = function() {
	try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {};
	try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {};
	try { return new ActiveXObject("Msxml2.XMLHTTP"); }     catch(e) {};
	try { return new ActiveXObject("Microsoft.XMLHTTP"); }  catch(e) {};
 
	throw new Error("This browser does not support XMLHttpRequest or XMLHTTP.");
  };

function getCaptionData( ccFile )
{
	var req = new XMLHttpRequest();
	req.open( "GET", ccFile );
	if (navigator.userAgent.indexOf("Firefox") != -1)
	{
		req.overrideMimeType('text/xml');
	}
	req.setRequestHeader("Content-Type", "application/x-javascript;");
	
	req.onreadystatechange = function()
	{
		if(req.readyState == 4 && req.status == 200)
		{
			if( req.responseXML )
			{
				loadCaptionData( req.responseXML );
			}
		}
	};
	req.send( null );
}

var ccData = null;

function loadCaptionData( xml )
{
	var items = xml.getElementsByTagName( "item" );
	for ( var i = 0; i < items.length; i++)
	{
		var curItem = items[i];
		var time = curItem.getAttribute( "time" );
		var text = curItem.text ? curItem.text : curItem.textContent;
		
		var ccDataObj = new Object();
		ccDataObj.Text = text;
		if (time == "0")
		{
			ccDataObj.Time = time;
		}
		else
		{
			ccDataObj.Time = padTimeValue(Math.floor(time/60/60)) + ":" + padTimeValue(Math.floor(time/60)) + ":" + padTimeValue(Math.floor(time%60));
		}
		
		if (ccData == null)
		{
			ccData = new Array();
		}
		ccData[i] = ccDataObj;
	}
}

function padTimeValue( time )
{
	var timeStr = time.toString();
	if (timeStr.length < 2)
	{
		return "0" + timeStr;
	}
	else
	{
		return timeStr;
	}
}
