/// <reference path="../../ScriptReference/jquery-1.7.1-vsdoc.js"/>
/// <reference path="../../Scripts/Mediasite.Core.js"/>
/// <reference path="../../Scripts/Mediasite.Player.Core.js"/>
/// <reference path="../../Scripts/Mediasite.Player.Localization.js"/>

Mediasite.Player.ScreenReaderView = function (playerContext) {
    var $ = jQuery;

    var presentation;
    var slideStream;
    var streamViewHandlers = [];
    var currentPosition;
    var currentSlide;
    var mediaDuration;
    var volume;
    var liveEnded = false;

    var volumeButtonIncrement = 10;

    var linkRegEx = /\bhttps?:\/\/[-A-Z0-9+&@\/%=~_|!:,.;]+\/Play\/[-A-Z0-9+&@#\/%?=~_|!:,.;]+[-A-Z0-9+&@#\/%=~_|]/ig;
    var emailRegEx = /^[A-Z0-9.'_%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i;

    var _events = new Mediasite.Player.EventBundle();
    var _eventNames = Mediasite.Player.ViewEvent;
    var _jumpNavigationHelper = new Mediasite.Player.Navigation.JumpNavigationHelper();
    var self = this;

    this.SlideStreamType = Mediasite.ContentStreamType.Slide;

    this.AddEventHandler = function (eventName, handler) {
        _events.addHandler(eventName, handler);
    };

    function fireEvent(event) {
        _events.fire(event);
    }

    function validateEmailAddress(address) {
        return emailRegEx.test(address);
    }

    function validateEmailMessage(from, recipients) {
        var errors = 0;

        if (!validateEmailAddress(from)) {
            errors++;
        }

        var valid = 0;
        $.each(recipients, function (i) {
            if (!validateEmailAddress(recipients[i])) {
                errors++;
            }
            else {
                valid++;
            }
        });

        if (errors > 0 || valid < 1) {
            $('#sendEmailSubmitResult').text(Mediasite.Player.Localization.Email.InviteInvalid);
            return false;
        }

        return true;
    }

    function validateQuestion() {

        var errors = "";

        if ($('#questionName').val().length < 1) {
            errors += Mediasite.Player.Localization.AskQuestion.NameRequired + ". ";
        }
        if ($('#questionEmail').val().length > 0 && !validateEmailAddress($('#questionEmail').val())) {
            errors += Mediasite.Player.Localization.AskQuestion.QuestionRequired + ". ";
        }
        if ($('#questionSubject').val().length < 1) {
            errors += Mediasite.Player.Localization.AskQuestion.SubjectRequired + ". ";
        }
        if ($('#questionBody').val().length < 1) {
            errors += Mediasite.Player.Localization.AskQuestion.QuestionRequired + ". ";
        }

        if (errors.length > 0) {
            $('#questionSubmitResult').html(Mediasite.Player.Localization.AskQuestion.ValidationError + " " + errors);

            return false;
        }

        return true;
    }

    function getDisplayFromDuration(durationInMS, padZeros) {
        if (durationInMS < 0) {
            return "";
        }
        var whole = durationInMS;

        var hours = Math.floor(whole / 3600000);
        whole = whole - (hours * 3600000);

        var minutes = Math.floor(whole / 60000);
        whole = whole - (minutes * 60000);
        var seconds = Math.floor(whole / 1000);

        whole = whole - (seconds * 1000);

        var display = "";

        if (hours === 1) {
            display += (hours + " " + Mediasite.Player.Localization.Common.Hour + " ");
        }
        else if (hours > 0 || padZeros) {
            display += (hours + " " + Mediasite.Player.Localization.Common.Hours + " ");
        }

        if (minutes === 1) {
            display += (minutes + " " + Mediasite.Player.Localization.Common.Minute + " ");
        }
        else if (minutes > 0 || padZeros) {
            display += (minutes + " " + Mediasite.Player.Localization.Common.Minutes + " ");
        }

        if (seconds === 1) {
            display += (seconds + " " + Mediasite.Player.Localization.Common.Second);
        }
        else if (seconds > 0 || padZeros) {
            display += (seconds + " " + Mediasite.Player.Localization.Common.Seconds);
        }
        return display;
    }

    function getShortDisplayFromDuration(durationInMS, padHours) {
        if (durationInMS < 0) {
            return "";
        }
        var whole = durationInMS;

        var hours = Math.floor(whole / 3600000);
        whole = whole - (hours * 3600000);
        if (hours < 10) {
            hours = "0" + hours;
        }

        var minutes = Math.floor(whole / 60000);
        whole = whole - (minutes * 60000);
        var seconds = Math.floor(whole / 1000);

        whole = whole - (seconds * 1000);

        if (minutes < 10) {
            minutes = "0" + minutes;
        }
        if (seconds < 10) {
            seconds = "0" + seconds;
        }
        if (hours === "00" && !padHours) {
            return (minutes + ":" + seconds);
        }
        return (hours + ":" + minutes + ":" + seconds);
    }

    function getDurationFromShortDisplay(durationDisplay) {
        var i, segments = durationDisplay.split(":");

        for (i = 0; i < segments.length; i++) {
            segments[i] = parseInt(segments[i], 10);
            if (isNaN(segments[i])) {
                return 0;
            }
        }

        var timeInMS = 0;

        switch (segments.length) {
            case 3:
                timeInMS = segments[0] * 3600000 + segments[1] * 60000 + segments[2] * 1000;
                break;
            case 2:
                timeInMS = segments[0] * 60000 + segments[1] * 1000;
                break;
            case 1:
                timeInMS = segments[0] * 1000;
                break;
        }

        return timeInMS;
    }

    function sendEmail() {

        var recipients = [];
        $.each($('#sendEmailTo').val().split(";"), function (i, val) {
            if ($.trim(val).length > 0) {
                recipients.push($.trim(val));
            }
        });

        var from = $.trim($('#sendEmailFrom').val());

        if (validateEmailMessage(from, recipients)) {
            var invite = {
                ToAddresses: recipients,
                FromAddress: from,
                Subject: $('#sendEmailSubject').val(),
                MessageBody: $('#sendEmailBody').val(),
                Time: getDurationFromShortDisplay($('#sendEmailTime').val())
            };

            _events.fire(_eventNames.SendEmail, invite);
        }
    }


    function sendQuestion() {

        if (validateQuestion()) {
            var timeInPreso = getDurationFromShortDisplay($('#questionTime').val());

            var question = {
                Submitter: $('#questionName').val(),
                SubmitterEmail: $('#questionEmail').val(),
                Subject: $('#questionSubject').val(),
                QuestionText: $('#questionBody').val(),
                TimeInPresentation: timeInPreso
            };

            _events.fire(_eventNames.SendQuestion, question);
        }
    }

    function updateEmailText() {

        var startTimeMS = getDurationFromShortDisplay($('#sendEmailTime').val());
        var messageText = $('#sendEmailBody').val();

        var playLinkMatches = linkRegEx.exec(messageText);
        if (playLinkMatches === null) {
            return;
        }

        var playLink = playLinkMatches[0].replace(/([\?&])?playFrom=\d+&?/ig, '$1').replace(/[\?&]$/, '');
        if (startTimeMS > 0) {
            playLink += (playLink.indexOf('?') > 0 ? '&' : '?') + 'playFrom=' + startTimeMS;
        }

        $('#sendEmailBody').val(messageText.replace(linkRegEx, playLink));
    }


    function setMailToLink() {
        var link = "mailto:" + encodeURIComponent($('#sendEmailTo').val()) + "?subject=" + encodeURIComponent($('#sendEmailSubject').val()) + "&body=" + encodeURIComponent($('#sendEmailBody').val());
        if (link.length > 2000) {
            link = "mailto:" + encodeURIComponent($('#sendEmailTo').val()) + "?subject=" + encodeURIComponent($('#sendEmailSubject').val()) + "&body=" + encodeURIComponent(window.location.href);
        }
        $('#sendEmailUseClientLink').attr('href', link);
    }

    var _layoutFeature = new Mediasite.Player.FeatureAccess();
    _layoutFeature.item = {
        ViewDateTime: 'ViewDateTime'
    };
    (function () {
        _layoutFeature.disable(_layoutFeature.item.ViewDateTime, playerContext.PlayerLayoutOptions.HideDateTime === true || playerContext.PlayerLayoutOptions.ShowDateTime === false);
    })();

    this.LoadLayout = function () {

        $('#standardPlayerPrompt').text(Mediasite.Player.Localization.ScreenReader.StandardPlayerPrompt);
        $('#keyboardShortcutsMessagePrompt').text(Mediasite.Player.Localization.ScreenReader.keyboardShortcutsMessagePrompt);
        $('#shortcutsMessagePanelHeader').text(Mediasite.Player.Localization.ScreenReader.KeyboardShortcutsPanelHeader);

        $('#presentationDescriptionLabel').text(Mediasite.Player.Localization.PresentationCard.Description);
        $('#presentationPresentersLabel').text(Mediasite.Player.Localization.PresentationCard.Presenters);
        $('#presentationAirTimeLabel').text(Mediasite.Player.Localization.PresentationCard.AirTime);
        $('#presentationAirDateLabel').text(Mediasite.Player.Localization.PresentationCard.AirDate);
        $('#presentationDurationLabel').text(Mediasite.Player.Localization.PresentationCard.Duration);

        $('#slideListHeader').text(Mediasite.Player.Localization.Common.SlideList);
        $('#chapterHeader').text(Mediasite.Player.Localization.Buttons.Chapters);
        $('#linkHeader').text(Mediasite.Player.Localization.Buttons.Links);
        $('#btnPlayPause').text(Mediasite.Player.Localization.Buttons.Play).attr("disabled", "disabled");
        $('#btnMute').text(Mediasite.Player.Localization.Buttons.Mute).attr("disabled", "disabled");
        $('#mediaControls').attr("aria-label", Mediasite.Player.Localization.ScreenReader.MediaControls);

        $('#btnJumpBack').text(Mediasite.Player.Localization.Buttons.Jumpback).attr("disabled", "disabled");
        $('#btnJumpBackMore').text(Mediasite.Player.Localization.Buttons.JumpbackMore).attr("disabled", "disabled");
        $('#btnJumpForward').text(Mediasite.Player.Localization.Buttons.JumpForward).attr("disabled", "disabled");
        $('#btnJumpForwardMore').text(Mediasite.Player.Localization.Buttons.JumpForwardMore).attr("disabled", "disabled");

        $('#btnPlayFaster').text(Mediasite.Player.Localization.Buttons.PlayFaster);
        $('#btnPlaySlower').text(Mediasite.Player.Localization.Buttons.PlaySlower);
        $('#currentPlaybackRate').text(Mediasite.Player.Localization.ScreenReader.PlaybackRate + ": 1x");
        $('#btnVolumeIncrease').text(Mediasite.Player.Localization.ScreenReader.VolumeIncrease);
        $('#btnVolumeDecrease').text(Mediasite.Player.Localization.ScreenReader.VolumeDecrease);

        $('#questionHeader').text(Mediasite.Player.Localization.Buttons.Ask);
        $('#questionLabelName').text('* ' + Mediasite.Player.Localization.AskQuestion.Name);
        $('#questionLabelEmail').text(Mediasite.Player.Localization.AskQuestion.Email);
        $('#questionLabelSubject').text('* ' + Mediasite.Player.Localization.AskQuestion.Subject);
        $('#questionLabelBody').text('* ' + Mediasite.Player.Localization.AskQuestion.Question);
        $('#questionLabelTime').text(Mediasite.Player.Localization.AskQuestion.Time);
        $('#questionUseCurrentTime').text(Mediasite.Player.Localization.ScreenReader.UseCurrentTime);
        $('#questionSubmit').text(Mediasite.Player.Localization.ScreenReader.SendQuestion);
        $('.requiredFieldNote').text('* ' + Mediasite.Player.Localization.Common.RequiredField);

        $('#sendEmailHeader').text(Mediasite.Player.Localization.Buttons.Email);
        $('#sendEmailUseClientLink').text(Mediasite.Player.Localization.ScreenReader.ShareUsingEmailClient);
        $('#sendEmailLabelTo').text('* ' + Mediasite.Player.Localization.Email.To);
        $('#sendEmailLabelFrom').text('* ' + Mediasite.Player.Localization.Email.From);
        $('#sendEmailLabelSubject').text(Mediasite.Player.Localization.Email.Subject);
        $('#sendEmailLabelBody').text(Mediasite.Player.Localization.Email.Message);
        $('#sendEmailLabelTime').text(Mediasite.Player.Localization.Email.Time);
        $('#sendEmailUseCurrentTime').text(Mediasite.Player.Localization.ScreenReader.UseCurrentTime);
        $('#sendEmailSubmit').text(Mediasite.Player.Localization.ScreenReader.SendEmail);

        if (_layoutFeature.isDisabled(_layoutFeature.item.ViewDateTime)) {
            $('#presentationAirDateContainer').add('#presentationAirTimeContainer')
                .hide();
        }
    };

    this.GetStreamViewHandler = function (streamViewHandlerOptions) {

        if (streamViewHandlers.length == 2) return undefined;

        var streamViewHandler = undefined;
        if (streamViewHandlerOptions.IsMainStream) {
            streamViewHandler = new Mediasite.Player.StreamViewHandler(
            {
                MediaContainer: $('#mediaElementArea'),
                UpdateCurrentSlide: function () { },
                AddNewSlide: function () { }
            });
            streamViewHandlers.push(streamViewHandler);
        }

        if (streamViewHandlerOptions.StreamType == Mediasite.ContentStreamType.Slide) {
            this.SlideStreamType = streamViewHandlerOptions.StreamType;
            streamViewHandler = new Mediasite.Player.StreamViewHandler(
            {
                MediaContainer: undefined,
                UpdateCurrentSlide: self.UpdateCurrentSlide,
                AddNewSlide: function () { }
            });
            streamViewHandlers.push(streamViewHandler);
        }

        return streamViewHandler;
    };

    function hasSlides() {
        if (!presentation || !slideStream) return false;

        return slideStream.HasSlides();
    }

    function isOnDemand() {
        return presentation.PlayStatus === Mediasite.Player.PresentationStatus.OnDemand;
    }

    this.SendEmailComplete = function (success, message) {
        $('#sendEmailSubmitResult').text(message);

        if (success) {
            $('#sendEmailTo').val("");
        }
    };

    this.SendQuestionComplete = function (success, message) {

        if (success) {
            $('#questionSubmitResult').text(Mediasite.Player.Localization.AskQuestion.SendSuccessDetail);
            $('#questionSubject').val("");
            $('#questionBody').val("");
        }
        else {
            var errorMessage = Mediasite.Player.Localization.AskQuestion.SendFailureDetail;
            if (message.length > 0) {
                errorMessage = errorMessage + ' ' + message;
            }
            $('#questionSubmitResult').text(errorMessage);
        }
    };

    this.ShowErrorMessage = function (message, details) {
        $('#errorMessage').text(message + " " + details);
    };

    this.UpdateCurrentSlide = function (slide) {
        currentSlide = slide;
        if (slide.Number === 0) {
            $('#currentSlideTitle').text("");
            $('#currentSlideDescription').text("");
        }
        else {
            $('#currentSlideTitle').text(Mediasite.Player.Localization.Common.Slide + " " + slide.Number + " - " + slide.Text);
            $('#currentSlideDescription').text(slide.Description);

            if (slide.Text != null && slide.Text != "") {
                $("#screenReaderSlideMessage").text("");
                $("#screenReaderSlideMessage").text(Mediasite.Player.Localization.AriaMessages.SlideHasText);
            } else
                $("#screenReaderSlideMessage").text("");
        }
    };

    function nextSlide() {
        if (currentSlide) {
            if (currentSlide.Number == slideStream.Slides.length) return;
            var slideTime = slideStream.Slides[currentSlide.Number].Time;
            _events.fire(Mediasite.Player.ViewEvent.PositionChanged, slideTime);
        }
    }

    function previousSlide() {
        if (currentSlide) {
            if (currentSlide.Number - 2 < 0) return;
            var slideTime = slideStream.Slides[currentSlide.Number - 2].Time;
            _events.fire(Mediasite.Player.ViewEvent.PositionChanged, slideTime);
        }
    }

    this.UpdateEmailInvite = function (emailData) {
        $('#sendEmailSubject').val(emailData.Subject);
        $('#sendEmailBody').val(emailData.Message);
        $('#sendEmailTo').val("");

        if (!emailData.UseServerForSMTP) {
            $('#sendEmailServerForm').hide();
        }
    };

    this.UpdateMediaInfo = function (mediaInfo) {
        var mainMediaInfo;
        if (mediaInfo instanceof Array) {
            $.each(mediaInfo, function (index, item) {
                if (item.IsMainStream) {
                    mainMediaInfo = item;
                }
            });
        } else {
            mainMediaInfo = mediaInfo;
        }

        mediaDuration = mainMediaInfo.Duration;

        $('#btnVolumeIncrease').click(function () { _events.fire(_eventNames.VolumeChanged, Math.min(volume + volumeButtonIncrement, 100)); });
        $('#btnVolumeDecrease').click(function () { _events.fire(_eventNames.VolumeChanged, Math.max(volume - volumeButtonIncrement, 0)); });

        if (mainMediaInfo.CanChangeSpeed) {
            $('.playbackRateControls').show();
            $('#btnPlaySlower').click(function () { fireEvent(Mediasite.Player.ViewEvent.PlaybackRateSlower); });
            $('#btnPlayFaster').click(function () { fireEvent(Mediasite.Player.ViewEvent.PlaybackRateFaster); });
        }
    };

    this.UpdateMediaState = function (state) {
        var mediaStateText = (state === Mediasite.Player.MediaState.Undefined) ? '' : Mediasite.Player.MediaState.GetDisplayName(state);
        $("#mediaState").text(mediaStateText);

        switch (state) {
            case Mediasite.Player.MediaState.Playing:
                $('#btnPlayPause')
                    .text(Mediasite.Player.Localization.Buttons.Pause).removeAttr("disabled")
                    .unbind()
                    .click(function () { fireEvent(Mediasite.Player.ViewEvent.TogglePlayPause); });
                break;
            case Mediasite.Player.MediaState.Paused:
                $('#btnPlayPause')
                    .text(Mediasite.Player.Localization.Buttons.Play).removeAttr("disabled")
                    .unbind()
                    .click(function () { fireEvent(Mediasite.Player.ViewEvent.TogglePlayPause); });
                break;
            case Mediasite.Player.MediaState.Stopped:
                if (liveEnded) {
                    $('#btnPlayPause')
                    .attr("disabled", "true")
                    .unbind();
                }
                else {
                    $('#btnPlayPause')
                    .text(Mediasite.Player.Localization.Buttons.Play).removeAttr("disabled")
                    .unbind()
                    .click(function () { fireEvent(Mediasite.Player.ViewEvent.TogglePlayPause); });
                }
                break;
            case Mediasite.Player.MediaState.MediaEnded:
                $('#btnPlayPause')
                    .text(Mediasite.Player.Localization.Buttons.Play).removeAttr("disabled")
                    .unbind()
                    .click(function () { fireEvent(Mediasite.Player.ViewEvent.TogglePlayPause); });
                break;
            default:
                break;
        }
    };

    this.UpdateMediaVolume = function (vol) {
        volume = vol;
        if (volume > 0) {
            $("#btnMute")
                .text(Mediasite.Player.Localization.Buttons.Mute).removeAttr("disabled")
                .unbind()
                .click(function () { fireEvent(Mediasite.Player.ViewEvent.Mute); });
        }
        else {
            $("#btnMute")
                .text(Mediasite.Player.Localization.Buttons.UnMute).removeAttr("disabled")
                .unbind()
                .click(function () { fireEvent(Mediasite.Player.ViewEvent.Mute); });
        }

        $('#volumeLevel').text(Mediasite.Player.Localization.Common.Volume + ": " + volume);
    };

    this.UpdatePlaybackRate = function (rateInfo) {
        if (rateInfo.Current <= rateInfo.Min) {
            $("#btnPlaySlower").hide();
        }
        else {
            $("#btnPlaySlower").show();
        }

        if (rateInfo.Current >= rateInfo.Max) {
            $("#btnPlayFaster").hide();
        }
        else {
            $("#btnPlayFaster").show();
        }

        $('#currentPlaybackRate').text(Mediasite.Player.Localization.ScreenReader.PlaybackRate + ": " + rateInfo.Current + "x");

    };

    this.UpdatePosition = function (position) {
        currentPosition = position;

        if (mediaDuration > 0) {
            $('#mediaPosition').text(getDisplayFromDuration(position) + " " + Mediasite.Player.Localization.Common.Of + " " + getDisplayFromDuration(mediaDuration));
        }
        else {
            $('#mediaPosition').text(getDisplayFromDuration(position));
        }
    };

    function shortcutsList() {
        $('#shortcutsMessagePanel').show();
        $('#shortcutsMessageContainer').text("");

        $('#shortcutsMessageContainer').append(Mediasite.Player.Localization.ScreenReader.keyboardShortcutsMessage);

        $("#screenReaderHelpLink").off("click");
        $("#screenReaderHelpLink").on("click", function (e) {
            e.preventDefault();
            self.ShowHelp();
        });
    }

    var helpWindow;
    this.ShowHelp = function () {
        if (!helpWindow || helpWindow.closed) {
            var sep = playerContext.GlobalOptions.AppRoot.length > 0 ? "/" : "";
            var url = playerContext.GlobalOptions.AppRoot + sep + "Help/ScreenReader/OverviewFullVersion.htm";
            helpWindow = Mediasite.Player.CreatePopup(url, "Help", 800, 600, true, true);
        }
    };

    function jumpNavigationButtonClicked(jumpViewEvent) {
        if (!playerContext.CurrentPresentation.IsLivePresentation()) {
            var newPosition = _jumpNavigationHelper.getJumpTime(jumpViewEvent, currentPosition, playerContext.CurrentPresentation.Duration, playerContext.CurrentPresentation.Chapters);
            _events.fire(Mediasite.Player.ViewEvent.PositionChanged, newPosition);
            currentPosition = newPosition;
        }
    }

    function jumpBack() {
        jumpNavigationButtonClicked(Mediasite.Player.ViewEvent.JumpBack)
    }

    function jumpBackMore() {
        jumpNavigationButtonClicked(Mediasite.Player.ViewEvent.JumpBackMore)
    }

    function jumpForward() {
        jumpNavigationButtonClicked(Mediasite.Player.ViewEvent.JumpForward)
    }

    function jumpForwardMore() {
        jumpNavigationButtonClicked(Mediasite.Player.ViewEvent.JumpForwardMore)
    }

    this.UpdatePresentationData = function (modelPresentation) {
        presentation = modelPresentation;

        slideStream = presentation.GetStream(this.SlideStreamType);

        // prevent space and up and down arrows from scroll the page unless the user is focused on an input or textarea.
        window.onkeydown = function (e) {
            var focusedElement = $(":focus");

            if (focusedElement.length > 0 && (focusedElement.prop("tagName").toLowerCase() == "input" || focusedElement.prop("tagName").toLowerCase() == "textarea" || focusedElement.prop("tagName").toLowerCase() == "button")) {
                return !((e.keyCode == 38) || (e.keyCode == 40));
            } else
                return !((e.keyCode == 32) || (e.keyCode == 38) || (e.keyCode == 40));
        };

        $(document).bind("keyup", function (event) {
            var viewEvent = Mediasite.Player.ViewEvent.fromKeyEvent(event);
            if (viewEvent) {
                event.preventDefault();

                var eventData = {};

                if (viewEvent == Mediasite.Player.ViewEvent.NextSlide) {
                    nextSlide();
                    return;
                }

                if (viewEvent == Mediasite.Player.ViewEvent.PreviousSlide) {
                    previousSlide();
                    return;
                }

                if (_jumpNavigationHelper.isJumpViewEvent(viewEvent)) {
                    if (!playerContext.CurrentPresentation.IsLivePresentation()) {
                        var newPosition = _jumpNavigationHelper.getJumpTime(viewEvent, currentPosition, playerContext.CurrentPresentation.Duration, playerContext.CurrentPresentation.Chapters);
                        _events.fire(Mediasite.Player.ViewEvent.PositionChanged, newPosition);
                        currentPosition = newPosition;
                    }
                    return;
                }

                if (viewEvent == Mediasite.Player.ViewEvent.ShortcutsList) {
                    shortcutsList();
                }

                if (presentation.PlayStatus !== Mediasite.Player.PresentationStatus.OnDemand) {
                    if (viewEvent == Mediasite.Player.ViewEvent.SkipBack ||
                        viewEvent == Mediasite.Player.ViewEvent.JumpBackStatic ||
                        viewEvent == Mediasite.Player.ViewEvent.JumpForwardStatic) {

                        return;
                    }
                }

                _events.fire(viewEvent, eventData);
            }
        });

        $('#presentationTitle').text(presentation.Title);
        $('#presentationDescription').html(presentation.Description.replace(/\r/g, "").replace(/\n/g, "<br>").replace(/\&/g, "&amp;"));
        $('#presentationAirDate').text(presentation.Date);
        $('#presentationAirTime').text(presentation.Time);
        $('#presentationDuration').text(getDisplayFromDuration(presentation.Duration, false));

        if (presentation.PlayStatus === Mediasite.Player.PresentationStatus.OnDemand) {
            $("#btnJumpBack").removeAttr("disabled").click(function () { jumpBack(); });
            $('#btnJumpBackMore').removeAttr("disabled").click(function () { jumpBackMore(); });
            $('#btnJumpForward').removeAttr("disabled").click(function () { jumpForward(); });
            $('#btnJumpForwardMore').removeAttr("disabled").click(function () { jumpForwardMore(); });
        }

        $.each(presentation.Presenters, function (i) {
            var item;
            if (presentation.Presenters[i].BioUrl.length > 0) {
                item = $('<li><a href="' + presentation.Presenters[i].BioUrl + '" target="_blank">' + presentation.Presenters[i].Name + '</a></li>');
            }
            else {
                item = $('<li>').text(presentation.Presenters[i].Name);
            }
            $('#presentationPresenters').append(item);
        });

        /////////////////////////////
        // Add Named Slides
        /////////////////////////////

        var hasNamedSlides = false;

        if (hasSlides()) {
            var slidesWithText = [];

            $.each(slideStream.Slides, function (i, slide) {
                if (slide.Text != null && slide.Text != "")
                    slidesWithText.push(slide);
            });

            if (slidesWithText.length > 0)
                hasNamedSlides = true;

            $.each(slidesWithText, function (i, slide) {
                var item = $('<li role="listitem">');
                var divConainer1 = $('<div style="display:inline-block;">');
                var divConainer2 = $('<div style="display:inline-block; margin-left:5px;">');

                var slideButton = $('<button>').text(Mediasite.Player.Localization.Common.Slide + ' ' + (slide.Number)).click(function () { _events.fire(_eventNames.PositionChanged, slide.Time); });
                var time = Mediasite.Player.TimeHelper.Duration(slide.Time);
                var localizeTimeString = Mediasite.Player.Localization.Common.TimeAriaLabel.replaceholders(time.hours, time.minutes, time.seconds);

                var slideText = slide.Text;
                if (slide.Description != "")
                    slideText += ": " + slide.Description;

                var slideButtonAriaLabel = 'Slide' + slide.Number + '.  ' + localizeTimeString + '. ' + slideText;
                slideButton.attr("aria-label", slideButtonAriaLabel);

                divConainer1.append(slideButton);
                divConainer2.append($('<div aria-hidden="true">').text(slideText + ': ' + getDisplayFromDuration(slide.Time)));

                item.append(divConainer1);
                item.append(divConainer2);

                $('#slideList').append(item);
            });
        }

        if (!hasNamedSlides)
            $('#slideListArea').hide();

        /////////////////////////////
        // Add Chapters
        /////////////////////////////

        var hasChapters = false;

        if (presentation.Chapters.length > 0)
            hasChapters = true;

        $.each(presentation.Chapters, function (i, chapter) {

            var item = $('<li role="listitem">');
            var divConainer1 = $('<div style="display:inline-block;">');
            var divConainer2 = $('<div style="display:inline-block; margin-left:5px;">');

            var chapterButton = $('<button>').text(Mediasite.Player.Localization.Common.Chapter + ' ' + (i + 1)).click(function () { _events.fire(_eventNames.PositionChanged, chapter.Time); });
            var time = Mediasite.Player.TimeHelper.Duration(chapter.Time);
            var localizeTimeString = Mediasite.Player.Localization.Common.TimeAriaLabel.replaceholders(time.hours, time.minutes, time.seconds);
            var chapterButtonAriaLabel = Mediasite.Player.Localization.Common.Chapter + ' ' + (i + 1) + '. ' + localizeTimeString + '. ' + chapter.Text;
            chapterButton.attr("aria-label", chapterButtonAriaLabel);

            divConainer1.append(chapterButton);
            divConainer2.append($('<div aria-hidden="true">').text(chapter.Text + ': ' + getDisplayFromDuration(chapter.Time)));

            item.append(divConainer1);
            item.append(divConainer2);

            $('#chapterList').append(item);
        });

        if (!hasChapters)
            $('#chapterArea').hide();

        /////////////////////////////
        // Add Presention Links
        /////////////////////////////

        var hasPresentationLinks = false;

        if (presentation.Links.length > 0)
            hasPresentationLinks = true;

        $.each(presentation.Links, function (i) {
            var item = $('<li role="listitem"><a href="' + presentation.Links[i].Url + '" target="new" title="' + presentation.Links[i].Url + '">' + presentation.Links[i].Description + '</a></li>');
            $('#linkList').append(item);
        });

        if (!hasPresentationLinks)
            $('#linkArea').hide();


        if (!modelPresentation.PollingEnabled || !modelPresentation.PollingLocation) {
            $('#pollArea').hide();
        }
        else {
            var pollUrl = modelPresentation.PollingLocation;
            $('#pollLink').text(Mediasite.Player.Localization.Buttons.Polls).attr("href", pollUrl).attr("target", "_offsite");
        }

        if (!modelPresentation.ForumEnabled) {
            $('#questionForm').hide();
        }
        else {
            $('#questionSubmit').click(function () { sendQuestion(); });
            $('#questionUseCurrentTime').click(function () { $('#questionTime').val(getShortDisplayFromDuration(currentPosition)); });
        }

        if (!modelPresentation.SharingEnabled) {
            $('#sendEmailForm').hide();
        }
        else {
            fireEvent(Mediasite.Player.ViewEvent.OpenEmail);
            $('#sendEmailSubmit').click(function () { sendEmail(); });
            $('#sendEmailUseCurrentTime').click(function () { $('#sendEmailTime').val(getShortDisplayFromDuration(currentPosition)); updateEmailText(); });
            $('#sendEmailUseClientLink').click(function () { setMailToLink(); });
            $('#sendEmailTime').change(function () { updateEmailText(); });
        }

        $('#shortcutsMessagePanel').hide();
    };
};



/******************************************************************************************************************************
This function will register the player view so it can be used by the player engine
*******************************************************************************************************************************/
Mediasite.Player.Register(Mediasite.Player.PlayerType.ScreenReader,
    {
        View: Mediasite.Player.ScreenReaderView,
        LoadFunction: function (callback) {
            if (callback) {
                callback();
            }
        },
        MarkupUrl: 'Javascript/Players/ScreenReader/ScreenReader.html',
        MediaElementOptions:
            {
                backgroundElement: $('#mediaElementArea')
            },
        StyleSheetFiles: [
                'ScreenReader.css'
            ],
        ContentCapability: Mediasite.Player.ContentCapability.MultiVideo


    });