/// <reference path="Mediasite.Core.js"/>
/// <reference path="Mediasite.Player.Localization.js"/>
/*global Mediasite*/
Mediasite.namespace('Player');

Mediasite.Player.PresentationStatus = {
    NotAvailable: "NotAvailable",
    ScheduledForLive: "ScheduledForLive",
    OpenForLive: "OpenForLive",
    Live: "Live",
    LivePaused: "LivePaused",
    LiveEnded: "LiveEnded",
    OnDemand: "OnDemand"
};

Mediasite.Player.MediaPlayerType = {
    Unknown: 0,
    WindowsMedia: 1,
    Port25: 2,
    Silverlight: 3,
    Flash: 4,
    HTML5: 5,

    GetDisplayName: function (type) {
        switch (type) {
            case this.WindowsMedia:
                return "WindowsMedia";
            case this.Port25:
                return "Port25";
            case this.Silverlight:
                return "Silverlight";
            case this.HTML5:
                return "Html5";
            case this.Flash:
                return "Flash";
            case this.Unknown:
                return "Unknown";
        }
    },

    Parse: function (name) {
        if (typeof (name) === 'undefined') {
            return this.Unknown;
        }
        switch (name.toLowerCase()) {
            case "windowsmedia":
                return this.WindowsMedia;
            case "port25":
                return this.Port25;
            case "html5":
                return this.HTML5;
            case "silverlight":
                return this.Silverlight;
            case "flash":
                return this.Flash;
            default:
                return this.Unknown;
        }
    }
};

Mediasite.Player.TimelineEvent = {
    Unknown: 0,
    Slide: 1,
    PresentationStart: 2,
    PresentationEnd: 3,
    PauseStart: 4,
    PauseEnd: 5
};

Mediasite.Player.MediaEventType = {
    EndPresentation: "E",
    ShowSlide: "S",
    Pause: "P",
    Resume: "R"
};

Mediasite.Player.PlayerServiceFaultType = {
    Unknown: 0,
    InvalidTicket: 1
};

Mediasite.Player.MediaState = {
    Undefined: 0,
    Stopped: 1,
    Paused: 2,
    Playing: 3,
    ScanForward: 4,
    ScanReverse: 5,
    Buffering: 6,
    Waiting: 7,
    MediaEnded: 8,
    Transitioning: 9,
    Ready: 10,
    Reconnecting: 11,
    Closed: 12,
    Error: 13,
    Opening: 14,

    GetDisplayName: function (state) {
        switch (state) {
            case this.Undefined:
                return Mediasite.Player.Localization.MediaPlayer.State.Undefined;
            case this.Stopped:
                return Mediasite.Player.Localization.MediaPlayer.State.Stopped;
            case this.Paused:
                return Mediasite.Player.Localization.MediaPlayer.State.Paused;
            case this.Playing:
                return Mediasite.Player.Localization.MediaPlayer.State.Playing;
            case this.ScanForward:
                return Mediasite.Player.Localization.MediaPlayer.State.ScanForward;
            case this.ScanReverse:
                return Mediasite.Player.Localization.MediaPlayer.State.ScanReverse;
            case this.Buffering:
                return Mediasite.Player.Localization.MediaPlayer.State.Buffering;
            case this.Waiting:
                return Mediasite.Player.Localization.MediaPlayer.State.Waiting;
            case this.MediaEnded:
                return Mediasite.Player.Localization.MediaPlayer.State.MediaEnded;
            case this.Transitioning:
                return Mediasite.Player.Localization.MediaPlayer.State.Transitioning;
            case this.Ready:
                return Mediasite.Player.Localization.MediaPlayer.State.Ready;
            case this.Reconnecting:
                return Mediasite.Player.Localization.MediaPlayer.State.Reconnecting;
            case this.Closed:
                return Mediasite.Player.Localization.MediaPlayer.State.Closed;
            case this.Error:
                return Mediasite.Player.Localization.MediaPlayer.State.Error;
            case this.Opening:
                return Mediasite.Player.Localization.MediaPlayer.State.Opening;
            default:
                return Mediasite.Player.Localization.MediaPlayer.State.Unknown;
        }
    }
};

Mediasite.Player.ClickCommand = {
    AskQuestion: "AskQuestion",
    OpenEmail: "OpenEmail",
    ShowLinks: "ShowLinks",
    ShowPolls: "ShowPolls",
    ShowChapters: "ShowChapters",    
    TogglePlayPause: "PlayPause",
    ToggleSlideShow: "ToggleSlide",
    Mute: "Mute",
    FullScreen: "FullScreen",
    SkipBack: "SkipBack",
    ToggleCaptions: "Captions",
    ToggleCaptionSearch: "CaptionSearch", 
    PlayFaster: "PlayFaster",
    PlaySlower: "PlaySlower",
    PreviousSlide: "PreviousSlide",
    NextSlide: "NextSlide",
    FirstSlide: "FirstSlide",
	LastSlide: "LastSlide",
    ShowSlideList: "ShowSlideList",
    ShowSlideSmallThumbs: "ShowSlideSmallThumbs",
    ShowSlideLargeThumbs: "ShowSlideLargeThumbs",
    ShowHelp: "Help",
    ShowInfo: "ShowInfo",
	PopOut: "PopOut"
};

Mediasite.Player.Options = {
    UserFromName: "UserFromName",
    UserFromEmail: "UserFromEmail",
    Volume: "Volume",
    SlideDisplay: "SlideDisplay",
    ShowSlideDescriptions: "ShowSlideDescriptions",
    UseScreenReader: "UseScreenReader"
};

Mediasite.Player.SlideDisplayPref = {
    List: 0,
    SmallThumbs : 4,
    LargeThumbs: 5,
    Chapters: 9
};

Mediasite.Player.TimingSearcher = function (timings) {

    this.GetCurrentItem = function (time) {
        var low = -1;
        var high = timings.length;
        var mid;

        while (high - low > 1) {
            mid = high + low >> 1;
            if (timings[mid].Time < time) {
                low = mid;
            }
            else if (timings[mid].Time > time) {
                high = mid;
            }
            else {
                return timings[mid];
            }
        }
        return timings[low];
    };
};


Mediasite.Player.BaseView = function () {
    return {
        AddListener: function (listener) { },
        LoadLayout: function () { },
        UpdatePresentationData: function (presentation) { },
        UpdateMediaInfo: function (mediaInfo) { },
        UpdateMediaState: function (state) { },
        UpdateMediaVolume: function (volume) { },
        UpdatePlaybackRate: function (rateInfo) { },
        UpdatePosition: function (position) { },
        UpdateEmailInvite: function (emailData) { },
        UpdateOptions: function (options) { },
        UpdateCurrentSlide: function (slide) { },
        UpdateCurrentCaption: function (caption) { },
        UpdateSlideBrowserView: function (view) { },
        LiveStatusChange: function (status) { },
        InactivityExceeded: function () { },
        SendQuestionComplete: function (success, message) { },
        SendEmailComplete: function (success, message) { },
        ShowErrorMessage: function (title, details) { },
        ShowAskQuestionForm: function () { },
        ShowChapters: function () { },
        ShowLinks: function () { },
        ShowPolls: function () { },
        ShowHelp: function () { },
        ToggleSlideText: function () { },
        ToggleSlideBrowser: function () { },
        ToggleCaptionDisplay: function () { },
        ToggleCaptionSearch: function () { },
        DisplaySearchTextResults: function (searchTerm, results) { },
        ShowInfo: function () { },
        MediaLoadStart: function () { },
        LaunchPopOut: function () { }
    };
};

Mediasite.Player.BaseViewListener = function () {
    return {
        OnLayoutLoaded: function () { },
        OnClickCommand: function (command) { },
        OnKeyCommand: function (keyEvent) { },
        OnSlideChanged: function (slideNumber) { },
        OnChapterChanged: function (chapterNumber) { },
        OnAudioLanguageChanged: function (language) { },
        OnVolumeChanged: function (volume) { },
        OnPlaybackRateChanged: function (speed) { },
        OnPlaybackRateFaster: function (doLoop) { },
        OnPlaybackRateSlower: function (doLoop) { },
        OnPositionChanged: function (position) { },
        OnPreferenceChanged: function (pref, val) { },
        OnSendQuestion: function (question) { },
        OnSendEmail: function (email) { },
        OnSearchPresentationTextOnServer: function (searchTerm, results) { }
    };
};

Mediasite.Player.ViewEventNotifier = function () {
    var listeners = [];

    this.AddListener = function (list) {
        listeners.push(list);
    };

    this.OnLayoutLoaded = function () {
        $.each(listeners, function (i) {
            listeners[i].OnLayoutLoaded();
        });
    };

    this.OnClickCommand = function (command) {
        $.each(listeners, function (i) {
            listeners[i].OnClickCommand(command);
        });
    };

    this.OnKeyCommand = function (keyEvent) {
        $.each(listeners, function (i) {
            listeners[i].OnKeyCommand(keyEvent);
        });
    };

    this.OnSlideChanged = function (slideNumber) {
        $.each(listeners, function (i) {
            listeners[i].OnSlideChanged(slideNumber);
        });
    };

    this.OnChapterChanged = function (chapterNumber) {
        $.each(listeners, function (i) {
            listeners[i].OnChapterChanged(chapterNumber);
        });
    };

    this.OnAudioLanguageChanged = function (language) {
        $.each(listeners, function (i) {
            listeners[i].OnAudioLanguageChanged(language);
        });
    };

    this.OnPlaybackRateChanged = function (speed) {
        $.each(listeners, function (i) {
            listeners[i].OnPlaybackRateChanged(speed);
        });
    };

    this.OnPlaybackRateFaster = function (doLoop) {
        $.each(listeners, function (i) {
            listeners[i].OnPlaybackRateFaster(doLoop);
        });
    };

    this.OnPlaybackRateSlower = function (doLoop) {
        $.each(listeners, function (i) {
            listeners[i].OnPlaybackRateSlower(doLoop);
        });
    };

    this.OnVolumeChanged = function (volume) {
        $.each(listeners, function (i) {
            listeners[i].OnVolumeChanged(volume);
        });
    };

    this.OnPositionChanged = function (position) {
        $.each(listeners, function (i) {
            listeners[i].OnPositionChanged(position);
        });
    };

    this.OnPreferenceChanged = function (pref, val) {
        $.each(listeners, function (i) {
            listeners[i].OnPreferenceChanged(pref, val);
        });
    };

    this.OnSendQuestion = function (question) {
        $.each(listeners, function (i) {
            listeners[i].OnSendQuestion(question);
        });
    };

    this.OnSendEmail = function (email) {
        $.each(listeners, function (i) {
            listeners[i].OnSendEmail(email);
        });
    };

    this.OnSearchPresentationTextOnServer = function (searchTerm) {
        $.each(listeners, function (i) {
            listeners[i].OnSearchPresentationTextOnServer(searchTerm);
        });
    };
};

Mediasite.Player.BaseModel = function () {
    return {
        AddListener: function (listener) { },
        LoadManifest: function () { },
        ReportMediaOpened: function (mediaPlayerType) { },
        ReportMediaView: function (mediaView, synchronous) { },
        HandleMediaEvent: function (event) { },
        HandleMediaError: function (error) { },
        UpdateMediaState: function (state) { },
        UpdateMediaVolume: function (volume) { },
        UpdatePosition: function (position) { },
        SetCurrentSlide: function (slideNumber) { },
        SetCurrentChapter: function (chapterNumber) { },
        SetInactivityTimeout: function (timeout) { },
        SetPreference: function (pref, val) { },
        TogglePreference: function (boolPref) { },
        NextSlide: function () { },
        PreviousSlide: function () { },
        FirstSlide: function () { },
        LastSlide: function () { },
        GetEmailInvite: function () { },
        SendQuestion: function (question) { },
        SendEmail: function (email) { },
        SearchPresentationTextOnServer: function (searchTerm) { },
        EnableLiveJumpBackDetection: function () { },
        EnableLiveStartDelay: function (delayInMs) { }
    };
};

Mediasite.Player.BaseModelListener = function () {
    return {
        OnLoadManifestFailure: function () { },
        OnPresentationLoaded: function (presentation) { },
        OnInactivityExceeded: function () { },
        OnEmailInviteLoaded: function (emailData) { },
        OnOptionsLoaded: function (options) { },
        OnStartMedia: function (mediaUrls) { },
        OnSlideChange: function (slide) { },
        OnAddNewSlide: function (slide) { },
        OnCaptionChange: function (caption) { },
        OnPositionChange: function (position) { },
        OnSendQuestionComplete: function (result, message) { },
        OnSendEmailComplete: function (result, message) { },
        OnLiveStatusChanged: function (status) { },
        OnSetLiveStartTime: function (time) { },
        OnSearchPresentationTextOnServerComplete: function (searchTerm, results) { },
        OnMediaError: function (error) { }
    };
};
        
Mediasite.Player.ModelEventNotifier = function () {
    var listeners = [];
    this.AddListener = function (list) {
        listeners.push(list);
    };

    this.OnLoadManifestFailure = function () {
        $.each(listeners, function (i) {
            listeners[i].OnLoadManifestFailure();
        });
    };

    this.OnPresentationLoaded = function (presentation) {
        $.each(listeners, function (i) {
            listeners[i].OnPresentationLoaded(presentation);
        });
};

    this.OnInactivityExceeded = function () {
        $.each(listeners, function (i) {
            listeners[i].OnInactivityExceeded();
        });
    };

    this.OnOptionsLoaded = function (options) {
        $.each(listeners, function (i) {
            listeners[i].OnOptionsLoaded(options);
        });
    };

    this.OnStartMedia = function (mediaUrls) {
        $.each(listeners, function (i) {
            listeners[i].OnStartMedia(mediaUrls);
        });
    };

    this.OnAddNewSlide = function (slide) {
        $.each(listeners, function (i) {
            listeners[i].OnAddNewSlide(slide);
        });
    };

    this.OnCaptionChange = function (text) {
        $.each(listeners, function (i) {
            listeners[i].OnCaptionChange(text);
        });
    };

    this.OnPositionChange = function (position) {
        $.each(listeners, function (i) {
            listeners[i].OnPositionChange(position);
        });
    };

    this.OnSendQuestionComplete = function (success, message) {
        $.each(listeners, function (i) {
            listeners[i].OnSendQuestionComplete(success, message);
        });
    };

    this.OnSendEmailComplete = function (success, message) {
        $.each(listeners, function (i) {
            listeners[i].OnSendEmailComplete(success, message);
        });
    };

    this.OnSendQuestionComplete = function (searchTerm, results) {
        $.each(listeners, function (i) {
            listeners[i].OnSendQuestionComplete(searchTerm, results);
        });
    };

    this.OnEmailInviteLoaded = function (emailData) {
        $.each(listeners, function (i) {
            listeners[i].OnEmailInviteLoaded(emailData);
        });
    };

    this.OnSlideChange = function (slide) {
        $.each(listeners, function (i) {
            listeners[i].OnSlideChange(slide);
        });
    };

    this.OnLiveStatusChanged = function (status) {
        $.each(listeners, function (i) {
            listeners[i].OnLiveStatusChanged(status);
        });
    };

    this.OnSetLiveStartTime = function (time) {
        $.each(listeners, function (i) {
            listeners[i].OnSetLiveStartTime(time);
        });
    };


    this.OnSearchPresentationTextOnServerComplete = function (searchTerm, results) {
        $.each(listeners, function (i) {
            listeners[i].OnSearchPresentationTextOnServerComplete(searchTerm, results);
        });
    };

    this.OnMediaError = function (error) {
        $.each(listeners, function (i) {
            listeners[i].OnMediaError(error);
        });
    };
};

Mediasite.Player.TimeHelper = {
    getDisplayFromDuration: function (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 (isNaN(hours) || isNaN(minutes) || isNaN(seconds)) {
            if (!padHours) { return "00:00"; }
            return ("00:00:00");
        }
        if (hours === "00" && !padHours) {
            return (minutes + ":" + seconds);
        }
        return (hours + ":" + minutes + ":" + seconds);
    },
    getDurationFromDisplay: function (durationDisplay) {
        var i, segments = durationDisplay.split(":");

        for (i = 0; i < segments.length; i++) {
            if (!this.isNumber(segments[i]) || segments[i].length != 2 || segments[i] < 0) {
                return -1;
            }
        }

        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;
    },
    isNumber: function (n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }
};

Mediasite.namespace("MediaPlayer");

Mediasite.MediaPlayer.BaseModel = function () {
    return {
        AddListener: function (listener) { },
        SetupMediaElement: function (element, sources) { },
        LiveStatusChange: function () { },
        InactivityExceeded: function () { },
        UpdateOptions: function (options) { },
        SetPosition: function (position) { },
        SetAudioLanguage: function (language) { },
        SetVolume: function (volume) { },
        SkipBack: function () { },
        SkipForward: function () { },
        PlayFaster: function () { },
        PlaySlower: function () { },
        TogglePlayPause: function () { },
        ToggleMute: function () { },
        FullScreen: function () { },
        SetLiveStartTime: function (time) { },
        SetIsStandAlone: function (value) { }
    };
};

Mediasite.MediaPlayer.BaseModelListener = function () {
    return {
        OnMediaError: function (message) { },
        OnMediaLoadStart: function () { },
        OnMediaLoaded: function (mediaInfo) { },
        OnMediaStarted: function (mediaPlayerType) { },
        OnMediaEvent: function (event) { },
        OnMediaView: function (mediaView, synchronous) { },
        OnStateChanged: function (state) { },
        OnVolumeChanged: function (volume) { },
        OnPlaybackRateChanged: function (rateInfo) { },
        OnPositionChanged: function (position) { },
        OnEnableLiveJumpBackDetection: function () { },
        OnEnableLiveStartDelay: function (delayInMs) { }
    };
};

Mediasite.MediaPlayer.ModelEventNotifier = function () {

    var listeners = [];
    var mediaStartReported = false;

    this.AddListener = function (list) {
        listeners.push(list);
    };

    this.OnMediaLoadStart = function () {
        $.each(listeners, function (i) {
            listeners[i].OnMediaLoadStart();
        });
    };

    this.OnMediaLoaded = function (mediaInfo) {
        $.each(listeners, function (i) {
            listeners[i].OnMediaLoaded(mediaInfo);
        });
    };

    this.OnPlaybackRateChanged = function (rateInfo) {
        $.each(listeners, function (i) {
            listeners[i].OnPlaybackRateChanged(rateInfo);
        });
    };

    this.OnMediaStarted = function (mediaPlayerType) {
        if (!mediaStartReported) {
            $.each(listeners, function (i) {
                listeners[i].OnMediaStarted(mediaPlayerType);
            });
            mediaStartReported = true;
        }
    };

    this.OnVolumeChanged = function (volume) {
        $.each(listeners, function (i) {
            listeners[i].OnVolumeChanged(volume);
        });
    };

    this.OnPositionChanged = function (position) {
        $.each(listeners, function (i) {
            listeners[i].OnPositionChanged(position);
        });
    };

    this.OnMediaError = function (errorMessage) {
        $.each(listeners, function (i) {
            listeners[i].OnMediaError(errorMessage);
        });
};

    this.OnStateChanged = function (state) {
        $.each(listeners, function (i) {
            listeners[i].OnStateChanged(state);
        });
    };

    this.OnMediaEvent = function (event) {
        $.each(listeners, function (i) {
            listeners[i].OnMediaEvent(event);
        });
    };

    this.OnMediaView = function (mediaView, synchronous) {
        $.each(listeners, function (i) {
            listeners[i].OnMediaView(mediaView, synchronous);
        });
    };

    this.OnEnableLiveJumpBackDetection = function () {
        $.each(listeners, function (i) {
            listeners[i].OnEnableLiveJumpBackDetection();
        });
    };

    this.OnEnableLiveStartDelay = function (delayInMs) {
        $.each(listeners, function (i) {
            listeners[i].OnEnableLiveStartDelay(delayInMs);
        });
    };
};

Mediasite.MediaPlayer.BaseView = function () {
    return {
        AddListener: function (listener) { },
        CreateMediaElement: function () { },
        UpdateMediaInfo: function (mediaInfo) { },
        MediaLoadStart: function () { },
        SetIsStandAlone: function (value) { }
    };
};

Mediasite.MediaPlayer.BaseViewListener = function () {
    return {
        OnClickCommand: function (command) { }
    };
};

Mediasite.MediaPlayer.ViewEventNotifier = function () {

    var listeners = [];

    this.AddListener = function (list) {
        listeners.push(list);
};

    this.OnClickCommand = function (command) {
        $.each(listeners, function (i) {
            listeners[i].OnClickCommand(command);
        });
    };
};
