/// <reference path="../ScriptReference/jquery-1.5.2.js"/>
/// <reference path="Mediasite.Core.js"/>
/// <reference path="Mediasite.Player.Core.js"/>
/// <reference path="Mediasite.Player.Localization.js"/>
/*globals Mediasite*/

Mediasite.namespace("Player");

Mediasite.Player.Controller = function () {
    var $ = jQuery;
    var playerView;
    var playerModel;
    var mediaPlayerView;
    var mediaPlayerModel;

    if (typeof Mediasite.GlobalOptions === "undefined" || !Mediasite.GlobalOptions) {
        Mediasite.GlobalOptions = {
            AppRoot: "",
            EnableContextMenuForPlayer: true,
            ErrorPage: "",
            ServiceEndpoint: "",
            SessionTimeout: 20,
            SlideGroupMaxInGroup: 10,
            SlideGroupMinToTrigger: 25,
            SlideGroupThreshold: 2000,
            UseLiveEventPolling: false
        };
    }

    function initialize() {

        playerView = $.extend(new Mediasite.Player.BaseView(), playerView);
        playerModel = $.extend(new Mediasite.Player.BaseModel(), playerModel);
        mediaPlayerView = $.extend(new Mediasite.MediaPlayer.BaseView(), mediaPlayerView);
        mediaPlayerModel = $.extend(new Mediasite.MediaPlayer.BaseModel(), mediaPlayerModel);

        mediaPlayerModel.AddListener($.extend(new Mediasite.MediaPlayer.BaseModelListener(), {
            OnMediaError: function (error) {
                playerModel.HandleMediaError(error);
            },
            OnMediaLoadStart: function () {
                playerView.MediaLoadStart();
                mediaPlayerView.MediaLoadStart();
            },
            OnMediaLoaded: function (mediaInfo) {
                playerView.UpdateMediaInfo(mediaInfo);
                mediaPlayerView.UpdateMediaInfo(mediaInfo);
            },
            OnMediaStarted: function (mediaPlayerType) {
                playerModel.ReportMediaOpened(mediaPlayerType);
            },
            OnMediaEvent: function (event) {
                playerModel.HandleMediaEvent(event);
            },
            OnMediaView: function (mediaView, synchronous) {
                playerModel.ReportMediaView(mediaView, synchronous);
            },
            OnStateChanged: function (state) {
                playerModel.UpdateMediaState(state);
                playerView.UpdateMediaState(state);
            },
            OnVolumeChanged: function (volume) {
                playerModel.UpdateMediaVolume(volume);
                playerView.UpdateMediaVolume(volume);
            },
            OnPlaybackRateChanged: function (rateInfo) {
                playerView.UpdatePlaybackRate(rateInfo);
            },
            OnPositionChanged: function (position) {
                playerModel.UpdatePosition(position);
                playerView.UpdatePosition(position);
            },
            OnEnableLiveJumpBackDetection: function () {
                playerModel.EnableLiveJumpBackDetection();
            },
            OnEnableLiveStartDelay: function (delayInMs) {
                playerModel.EnableLiveStartDelay(delayInMs);
            }
        }));

        mediaPlayerView.AddListener($.extend(new Mediasite.MediaPlayer.BaseViewListener(), {
            OnClickCommand: function (command) {
                switch (command) {
                    case Mediasite.Player.ClickCommand.TogglePlayPause:
                        mediaPlayerModel.TogglePlayPause();
                        break;
                    case Mediasite.Player.ClickCommand.FullScreen:
                        mediaPlayerModel.FullScreen();
                        break;
                }
            }
        }));

        playerModel.AddListener($.extend(new Mediasite.Player.BaseModelListener(), {
            OnLoadManifestFailure: function () {
                playerView.ShowErrorMessage(Mediasite.Player.Localization.Common.ManifestLoadErrorTitle, Mediasite.Player.Localization.Common.ManifestLoadErrorDetail);
            },
            OnPresentationLoaded: function (presentation) {
                playerView.UpdatePresentationData(presentation);
            },
            OnInactivityExceeded: function () {
                playerView.InactivityExceeded();
                mediaPlayerModel.InactivityExceeded();
            },
            OnEmailInviteLoaded: function (emailData) {
                playerView.UpdateEmailInvite(emailData);
            },
            OnOptionsLoaded: function (options) {
                playerView.UpdateOptions(options);
                mediaPlayerModel.UpdateOptions(options);
            },
            OnStartMedia: function (mediaUrls) {
                mediaPlayerModel.SetupMediaElement(mediaPlayerView.CreateMediaElement(), mediaUrls);
            },
            OnSlideChange: function (slide) {
                playerView.UpdateCurrentSlide(slide);
            },
            OnAddNewSlide: function (slide) {
                playerView.AddNewSlide(slide);
            },
            OnCaptionChange: function (caption) {
                playerView.UpdateCurrentCaption(caption);
            },
            OnPositionChange: function (position) {
                mediaPlayerModel.SetPosition(position);
            },
            OnSendQuestionComplete: function (success, message) {
                playerView.SendQuestionComplete(success, message);
            },
            OnSendEmailComplete: function (success, message) {
                playerView.SendEmailComplete(success, message);
            },
            OnSearchPresentationTextOnServerComplete: function (searchTerm, results) {
                playerView.DisplaySearchTextResults(searchTerm, results);
            },
            OnLiveStatusChanged: function (status) {
                playerView.LiveStatusChange(status);
                mediaPlayerModel.LiveStatusChange(status);
            },
            OnSetLiveStartTime: function (time) {
                mediaPlayerModel.SetLiveStartTime(time);
            },
            OnMediaError: function (error) {
                playerView.ShowErrorMessage(Mediasite.Player.Localization.MediaPlayer.ErrorTitle, error);
            }
        }));


        playerView.AddListener($.extend(new Mediasite.Player.BaseViewListener(), {
            OnLayoutLoaded: function () {
                playerModel.LoadManifest();
            },
            OnSlideChanged: function (slideNumber) {
                playerModel.SetCurrentSlide(slideNumber);
            },
            OnChapterChanged: function (chapterNumber) {
                playerModel.SetCurrentChapter(chapterNumber);
            },
            OnAudioLanguageChanged: function (language) {
                mediaPlayerModel.SetAudioLanguage(language);
            },
            OnSendQuestion: function (question) {
                playerModel.SendQuestion(question);
            },
            OnSendEmail: function (email) {
                playerModel.SendEmail(email);
            },
            OnSearchPresentationTextOnServer: function (searchTerm) {
                playerModel.SearchPresentationTextOnServer(searchTerm);
            },
            OnVolumeChanged: function (volume) {
                mediaPlayerModel.SetVolume(volume);
            },
            OnPlaybackRateChanged: function (speed) {
                mediaPlayerModel.SetPlaybackRate(speed);
            },
            OnPlaybackRateFaster: function (doLoop) {
                mediaPlayerModel.PlayFaster(doLoop);
            },
            OnPlaybackRateSlower: function (doLoop) {
                mediaPlayerModel.PlayFaster(doLoop);
            },
            OnPositionChanged: function (position) {
                mediaPlayerModel.SetPosition(position);
            },
            OnPreferenceChanged: function (pref, val) {
                playerModel.SetPreference(pref, val);
            },
            OnClickCommand: function (command) {
                switch (command) {
                    case Mediasite.Player.ClickCommand.TogglePlayPause:
                        mediaPlayerModel.TogglePlayPause();
                        break;
                    case Mediasite.Player.ClickCommand.ToggleSlideShow:
                        playerView.ToggleSlideBrowser();
                        break;
                    case Mediasite.Player.ClickCommand.SkipBack:
                        mediaPlayerModel.SkipBack();
                        break;
                    case Mediasite.Player.ClickCommand.ToggleCaptions:
                        playerView.ToggleCaptionDisplay();
                        break;
                    case Mediasite.Player.ClickCommand.ToggleCaptionSearch:
                        playerView.ToggleCaptionSearch();
                        break;
                    case Mediasite.Player.ClickCommand.PlayFaster:
                        mediaPlayerModel.PlayFaster();
                        break;
                    case Mediasite.Player.ClickCommand.PlaySlower:
                        mediaPlayerModel.PlaySlower();
                        break;
                    case Mediasite.Player.ClickCommand.FullScreen:
                        mediaPlayerModel.FullScreen();
                        break;
                    case Mediasite.Player.ClickCommand.Mute:
                        mediaPlayerModel.ToggleMute();
                        break;
                    case Mediasite.Player.ClickCommand.NextSlide:
                        playerModel.NextSlide();
                        break;
                    case Mediasite.Player.ClickCommand.PreviousSlide:
                        playerModel.PreviousSlide();
                        break;
                    case Mediasite.Player.ClickCommand.FirstSlide:
                        playerModel.FirstSlide();
                        break;
                    case Mediasite.Player.ClickCommand.LastSlide:
                        playerModel.LastSlide();
                        break;
                    case Mediasite.Player.ClickCommand.AskQuestion:
                        playerView.ShowAskQuestionForm();
                        break;
                    case Mediasite.Player.ClickCommand.OpenEmail:
                        playerModel.GetEmailInvite();
                        break;
                    case Mediasite.Player.ClickCommand.ShowPolls:
                        playerView.ShowPolls();
                        break;
                    case Mediasite.Player.ClickCommand.ShowLinks:
                        playerView.ShowLinks();
                        break;
                    case Mediasite.Player.ClickCommand.ShowHelp:
                        playerView.ShowHelp();
                        break;
                    case Mediasite.Player.ClickCommand.ShowChapters:
                        playerView.ShowChapters();
                        break;
                    case Mediasite.Player.ClickCommand.ShowSlideList:
                        playerView.UpdateSlideBrowserView(Mediasite.Player.SlideDisplayPref.List);
                        playerModel.SetPreference(Mediasite.Player.Options.SlideDisplay, Mediasite.Player.SlideDisplayPref.List);
                        break;
                    case Mediasite.Player.ClickCommand.ShowSlideSmallThumbs:
                        playerView.UpdateSlideBrowserView(Mediasite.Player.SlideDisplayPref.SmallThumbs);
                        playerModel.SetPreference(Mediasite.Player.Options.SlideDisplay, Mediasite.Player.SlideDisplayPref.SmallThumbs);
                        break;
                    case Mediasite.Player.ClickCommand.ShowSlideLargeThumbs:
                        playerView.UpdateSlideBrowserView(Mediasite.Player.SlideDisplayPref.LargeThumbs);
                        playerModel.SetPreference(Mediasite.Player.Options.SlideDisplay, Mediasite.Player.SlideDisplayPref.LargeThumbs);
                        break;
                    case Mediasite.Player.ClickCommand.ShowInfo:
                        playerView.ShowInfo();
                        break;
                    case Mediasite.Player.ClickCommand.PopOut:
                        playerView.LaunchPopOut();
                        break;
                }
            },
            OnKeyCommand: function (keyEvent) {
                switch (keyEvent.keyCode) {
                    case 32:  //space
                        mediaPlayerModel.TogglePlayPause();
                        break;
                    case 37: // left arrow
                        if (keyEvent.ctrlKey) {
                            playerModel.PreviousSlide();
                        }
                        else {
                            mediaPlayerModel.SkipBack();
                        }
                        break;
                    case 38:  // up arrow
                        if (keyEvent.ctrlKey) {
                            mediaPlayerModel.StepVolumeUp();
                        }
                        else {
                            mediaPlayerModel.PlayFaster();
                        }
                        break;
                    case 39:  // right arrow
                        if (keyEvent.ctrlKey) {
                            playerModel.NextSlide();
                        }
                        else {
                            mediaPlayerModel.SkipForward();
                        }
                        break;
                    case 40:  // down arrow
                        if (keyEvent.ctrlKey) {
                            mediaPlayerModel.StepVolumeDown();
                        }
                        else {
                            mediaPlayerModel.PlaySlower();
                        }
                        break;
                    case 65:  //A ask
                        playerView.ShowAskQuestionForm();
                        break;
                    case 67:  //C chapters + captions
                        if (keyEvent.shiftKey) {
                            playerView.ToggleCaptionDisplay();
                        }
                        else {
                            playerView.ShowChapters();
                        }
                        break;
                    case 69:  //E email                        
                        playerModel.GetEmailInvite();
                        break;
                    case 70:  //F search (Find)                        
                        playerView.ToggleCaptionSearch();
                        break;
                    case 72: // H help
                        playerView.ShowHelp();
                        break;
                    case 73: // I info panel
                        playerView.ShowInfo();
                        break;
                    case 76:  //L links 
                        playerView.ShowLinks();
                        break;
                    case 77:  //M mute
                        mediaPlayerModel.ToggleMute();
                        break;
                    case 80:  //P polls                        
                        playerView.ShowPolls();
                        break;
                    case 83:  //S slide + slide text
                        if (keyEvent.shiftKey) {
                            playerView.ToggleSlideText();
                        }
                        else {
                            playerView.ToggleSlideBrowser();
                        }
                        break;
                    case 90: //Z
                        if (keyEvent.ctrlKey) {
                            if (typeof window.toggleScreenReaderMode === "function") {
                                // In stand-alone mode, there will exist a function to handle
                                // the transition to/from screen reader mode.
                                window.toggleScreenReaderMode();
                            } else {
                                playerModel.TogglePreference(Mediasite.Player.Options.UseScreenReader);
                                window.location.reload();
                            }
                        }
                        break;
                    case 112: //F1 help 
                        playerView.ShowHelp();
                        break;
                }
            }
        }));
    }

    this.LoadPlayer = function (view, model, mediaView, mediaModel) {
        playerView = view;
        playerModel = model;
        mediaPlayerView = mediaView;
        mediaPlayerModel = mediaModel;

        initialize();

        playerModel.SetInactivityTimeout(Mediasite.GlobalOptions.SessionTimeout);
        playerView.LoadLayout();
    };

    this.DetectMediaPlayer = function () {

        var pluginType = Mediasite.Player.MediaPlayerType.Parse(Mediasite.GlobalOptions.Plugin);

        if (pluginType === Mediasite.Player.MediaPlayerType.Unknown) {
            pluginType = Mediasite.Player.MediaPlayerType.Parse(Mediasite.GetQueryParam("plugin"));
        }

        if (pluginType === Mediasite.Player.MediaPlayerType.WindowsMedia && navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
            pluginType = Mediasite.Player.MediaPlayerType.Port25;
        }

        if (pluginType === Mediasite.Player.MediaPlayerType.Unknown) {
            return Mediasite.Player.MediaPlayerType.Silverlight;
        }

        return pluginType;
    };

};

