
function SfKernel() { }

SfKernel.RequestVariables =
{
    PresentationId: "peid",
    PlaybackTicketId: "playbackTicket"
}

SfKernel.MediaPlayerType =
{
    WM7: "WM7",
    Port25: "Port25",
    SL1: "SL1"
}

SfKernel.CursorType =
{
    Default: 0,
    Hand: 1
}

SfKernel.SlideType =
{
    Normal: 0,
    FullSize: 1,
    ThumbNail: 2,
    Unknown: 3
}

SfKernel.ScriptCmdType =
{
    EndPresentation: "EndPresentation",
    ShowSlide: "ShowSlide",
    Pause: "Pause",
    Resume: "Resume"
}

SfKernel.SliderNotifyType =
{
    NewPosition: "NewPosition",
    DragPosition: "DragPosition",
    BeginDrag: "BeginDrag",
    EndDrag: "EndDrag"
}

SfKernel.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
}


SfKernel.PresentationPlayStatus =
{
    NotAvailable: "NotAvailable",
    ScheduledForLive: "ScheduledForLive",
    OpenForLive: "OpenForLive",
    Live: "Live",
    LiveEnded: "LiveEnded",
    OnDemand: "OnDemand",
    Paused: "Paused"
}

SfKernel.EventType =
{
    Script: "Script",
    LivePlaybackStarted: "LivePlaybackStarted",
    PlayingFromBeginning: "PlayingFromBeginning",
    MediaOpened: "MediaOpened",
    PlayStateChanged: "PlayStateChanged",
    MediaLengthObtained: "MediaLengthObtained",
    PositionChanged: "PositionChanged",
    TimerLoop: "TimerLoop",
    SliderNotify: "SliderNotify",
    VolumeInitialized: "VolumeInitialized",
    MuteToggled: "MuteToggled",
    OptionChanged: "OptionChanged"
}

SfKernel.CommandEventId =
{
    NavigateToSlide: "NavigateToSlide",
    NavigateToTime: "NavigateToTime",
    NavigateToChapter: "NavigateToChapter",
    Play: "Play",
    Pause: "Pause",
    Stop: "Stop",
    SetVolume: "SetVolume",
    Mute: "Mute",
    FullScreen: "FullScreen",
    SkipBack: "SkipBack",
    SkipForward: "SkipForward",
    ChangePlaybackSpeed: "ChangePlaybackSpeed"
}

SfKernel.GetQueryStringValue = function(key) {
    var queryString = document.location.search;

    if (queryString.length > 1) {
        var nvPairs = queryString.substring(1).split('&');
        var queryParams = new Array(nvPairs.length);
        for (var i = 0; i < nvPairs.length; i++) {
            var parts = nvPairs[i].split('=');
            queryParams[parts[0].toLowerCase()] = parts[1];
        }

        return queryParams[key.toLowerCase()];
    }
    return null;
}


SfKernel.EncodeHTML = function(val) {
    if (val == null) {
        return val;
    }
    val = val.toString();
    val = val.replace(/\\r/g, "");
    val = val.replace(/\\n/g, "<br/>");
    val = val.replace(/\&/g, "&amp;");
    return val;
}


SfKernel.EncodeClean = function(val) {
    if (val == null) {
        return val;
    }
    val = val.toString();
    val = val.replace(/\\r/g, "");
    val = val.replace(/\\n/g, " ");
    return val;
}

SfKernel.DurationDisplayToMS = function(durationDisplay) {
    var segments = durationDisplay.split(":");

    for (var i = 0; i < segments.length; i++) {
        segments[i] = parseInt(segments[i]);
        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;
}

SfKernel.GetDisplayDuration = 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 (hours == "00" && !padHours) {
        return (minutes + ":" + seconds);
    }
    return (hours + ":" + minutes + ":" + seconds);
}


SfKernel.SliderArgs = function(notifyType, position) {
    this.NotifyType = notifyType;
    this.Position = position;
}

SfKernel.AudioLanguageEntry = function(index, locale, displayName) {
    this.Index = index;
    this.Locale = locale;
    this.DisplayName = displayName;
}


SfKernel.GetPlayStateName = function(state) {
    switch (state) {
        case SfKernel.MediaState.Undefined:
            return Localization.MediaPlayer.State.Undefined;
        case SfKernel.MediaState.Stopped:
            return Localization.MediaPlayer.State.Stopped;
        case SfKernel.MediaState.Paused:
            return Localization.MediaPlayer.State.Paused;
        case SfKernel.MediaState.Playing:
            return Localization.MediaPlayer.State.Playing;
        case SfKernel.MediaState.ScanForward:
            return Localization.MediaPlayer.State.ScanForward;
        case SfKernel.MediaState.ScanReverse:
            return Localization.MediaPlayer.State.ScanReverse;
        case SfKernel.MediaState.Buffering:
            return Localization.MediaPlayer.State.Buffering;
        case SfKernel.MediaState.Waiting:
            return Localization.MediaPlayer.State.Waiting;
        case SfKernel.MediaState.MediaEnded:
            return Localization.MediaPlayer.State.MediaEnded;
        case SfKernel.MediaState.Transitioning:
            return Localization.MediaPlayer.State.Transitioning;
        case SfKernel.MediaState.Ready:
            return Localization.MediaPlayer.State.Ready;
        case SfKernel.MediaState.Reconnecting:
            return Localization.MediaPlayer.State.Reconnecting;
        case SfKernel.MediaState.Closed:
            return Localization.MediaPlayer.State.Closed;
        case SfKernel.MediaState.Error:
            return Localization.MediaPlayer.State.Error;
        case SfKernel.MediaState.Opening:
            return Localization.MediaPlayer.State.Opening;
        default:
            return Localization.MediaPlayer.State.Unknown;
    }
}


Panel = function(container, containingWindow, id) {
    this.Container = container;
    this.ContainingWindow = containingWindow;
    this.ID = id;
    this.div = null;
    this.originalDisplay = null;
}

Panel.prototype =
{

    GetElement: function(e) {
        return document.getElementById(e);
    },

    GetDiv: function() {
        if (this.div == null) {
            this.div = this.GetElement(this.ID);
        }
        return this.div;
    },

    Hide: function() {
        var divElement = this.GetDiv();

        if (this.originalDisplay == null) {
            this.originalDisplay = divElement.style.display;
        }

        divElement.style.display = 'none';
    },

    Show: function() {
        var divElement = this.GetDiv();

        var currentDisplay = divElement.style.display;
        if (currentDisplay != 'none') {
            this.originalDisplay = currentDisplay;
            return;
        }

        if (this.originalDisplay == null) {
            this.originalDisplay = 'none';
            divElement.style.display = '';
        }
        else {
            if (this.originalDisplay == 'none') {
                divElement.style.display = '';
            }
            else {
                divElement.style.display = this.originalDisplay;
            }
        }
    },

    IsShowing: function() {
        var displayVal = this.GetDiv().style.display;
        if (displayVal == 'none') {
            return false;
        }
        else {
            return true;
        }
    }
}

SfKernel.Util = function() { }

SfKernel.Util.SetCursor = function(element, cursorType) {
    if (cursorType == SfKernel.CursorType.Default) {
        element.style.cursor = 'default';
    }
    else if (cursorType == SfKernel.CursorType.Hand) {
        try {
            element.style.cursor = 'pointer';
        }
        catch (e) {
            element.style.cursor = 'hand';
        }
    }
}

SfKernel.Util.IsNullOrUndefined = function(obj) {
    return (typeof (obj) == 'undefined' || !obj);
}

SfKernel.Util.SetToolTip = function(element, tooltip) {
    element.setAttribute("title", tooltip);
    element.setAttribute("alt", tooltip);
}


SfKernel.Util.SetText = function(element, text) {
    var firstChild = element.childNodes[0];
    var newNode = document.createTextNode(text);
    if (firstChild) {
        element.replaceChild(newNode, firstChild);
    }
    else {
        element.appendChild(newNode);
    }
}



SfKernel.PlayerDetect = function() {
    this._playerType = null;

    this.GetPlayerType = function() {
        if (this._playerType == null) {
            this.DetectPlayerType();
        }
        return this._playerType;
    }

    this.DetectPlayerType = function() {
        if (GlobalOptions.AlwaysUseSilverlight) {
            this._playerType = SfKernel.MediaPlayerType.SL1;
            return;
        }

        var slPref = SfKernel.GetQueryStringValue("UseSilverlight");
        if (slPref && slPref.toLowerCase() == "true") {
            this._playerType = SfKernel.MediaPlayerType.SL1;
            return;
        }

        if (Sys.Browser.agent == Sys.Browser.Firefox && this.IsWindows()) {
            this._SetFirefoxWinPlayerType();
            return;
        }

        if (Sys.Browser.agent == Sys.Browser.InternetExplorer && this.IsWindows()) {
            this._playerType = SfKernel.MediaPlayerType.WM7;
            return;
        }

        this._playerType = SfKernel.MediaPlayerType.SL1;
    }

    this.DisplaySilverlightOption = function() {
        if (this.IsWindows()) {
            if (this.IsInternetExplorer()) {
                return true;
            }

            if (this.IsFirefox() && this.IsPort25Present()) {
                return true;
            }
        }
        return false;
    }

    this._SetFirefoxWinPlayerType = function() {
        this._playerType = SfKernel.MediaPlayerType.SL1;

        if (this.IsPort25Present() == true) {
            this._playerType = SfKernel.MediaPlayerType.Port25;
            return;
        }
    }

    this.IsPort25Present = function() {
        var test
        for (var i = 0; i < navigator.plugins.length; ++i) {
            test += navigator.plugins[i];
            test += "\n";

            var plugin = navigator.plugins[i];
            if (
				(plugin.name && plugin.name.indexOf("np-mswmp") > -1)
				||
				(plugin.description && plugin.description.indexOf("np-mswmp") > -1)
				) {
                return true;
            }
        }
        return false;
    }

    this.IsWindows = function() {
        if (navigator.userAgent) {
            return (navigator.userAgent.toLowerCase().indexOf('windows') > -1);
        }
        return false;
    }

    this.IsMac = function() {
        if (navigator.userAgent) {
            return (navigator.userAgent.toLowerCase().indexOf('macintosh') > -1);
        }
        return false;
    }

    this.IsMacPPC = function() {
        if (navigator.userAgent) {
            return (navigator.userAgent.toLowerCase().indexOf('ppc mac os x') > -1);
        }
        return false;
    }

    this.IsFirefox = function() {
        if (navigator.userAgent) {
            return (navigator.userAgent.toLowerCase().indexOf('firefox') > -1);
        }
        return false;
    }

    this.IsInternetExplorer = function() {
        if (navigator.userAgent) {
            return (navigator.userAgent.toLowerCase().indexOf('msie') > -1);
        }
        return false;
    }

    this.IsInternetExplorer6 = function() {
        if (navigator.userAgent) {
            return (navigator.userAgent.toLowerCase().indexOf('msie 6.') > -1);
        }
        return false;
    }
}


function EventManager() {
    this.Events = new Sys.EventHandlerList();
    this.CommandEvents = new Sys.EventHandlerList();
}

EventManager.prototype =
{
    PostEvent: function(eventId, sender, args) {
        var handler = this.Events.getHandler(eventId);
        if (handler == null) {
            return;
        }
        handler(sender, args);
    },

    PostCommandEvent: function(eventId, sender, args) {
        var handler = this.CommandEvents.getHandler(eventId);
        if (handler == null) {
            return;
        }
        handler(sender, args);
    }
}

////////////////////////////////////////////////////////////////////////////////
// Dialog Box
DialogBox = function DialogBox(container, containingWindow, id) {
    DialogBox.initializeBase(this, [container, containingWindow, id, false]);

    this.Message = null;
    this.Title = null;
    this.Id = id;
    this.okButton = null;
    this.cancelButton = null;
    this.okButtonFunction = null;
    this.okCancelButtonFunction = null;
}
DialogBox.prototype = {
    _container: null,
    _elements: null,
    _title: null,
    _closeButton: null,

    OnLoad: function DialogBox$OnLoad() {
        this._createDialog(this.Id);
    },

    _createDialog: function DialogBox$_createDialog(id) {
        var dialogFrame = this._createDiv(this.Id, 'dialogFrame');

        var dialogWidth;
        var dialogFrameLeft = 20;

        if (LayoutOptions.SlideWidth > 0) {
            dialogFrameLeft += parseInt($('CurrentSlideArea').style.left);
            dialogWidth = LayoutOptions.SlideWidth - 40;
        }
        else {
            if (LayoutOptions.DefaultPosition == 1 || LayoutOptions.DefaultPosition == 4) {
                dialogFrameLeft += LayoutOptions.VideoWidth;
            }
            dialogWidth = (LayoutOptions.PlayerWidth - LayoutOptions.VideoWidth - 40);
        }

        if (dialogWidth > 400) {
            dialogWidth = 400;
        }

        dialogFrame.style.position = 'absolute';
        dialogFrame.style.left = dialogFrameLeft + 'px';
        dialogFrame.style.width = dialogWidth + 'px';


        var dialogHeader = this._createDiv(this.Id + 'Header', 'dialogTitle');
        var dialogIcon = this._createDiv(this.Id + 'HeaderIcon', 'dialogIcon');
        var dialogHeaderText = this._createDiv(this.Id + 'HeaderText', 'dialogTitleText', this.Title);
        this._closeButton = this._createCloseButton(this.Id + 'HeaderCloseButton');

        this._closeButton.observe('mouseover', Function.createDelegate(this, this._closeButtonOnMouseOver));
        this._closeButton.observe('mouseout', Function.createDelegate(this, this._closeButtonOnMouseOut));
        this._closeButton.observe('click', Function.createDelegate(this, this._closeButtonOnClick));

        var dialogMessage = this._createDiv(this.Id + 'Message', 'dialogMessageText', this.Message);
        var dialogButtonContainer = this._createDiv(this.Id + 'MessageButton', 'dialogButtonContainer');
        if (this.okButton) {
            var okButton = this._createButton(this.Id + '_okButton', 'OK', true, 'return true', this._okButtonOnClick);
            okButton.observe('click', Function.createDelegate(this, this._okButtonOnClick));
            dialogButtonContainer.appendChild(okButton);
        }
        if (this.cancelButton) {
            var cancelButton = this._createButton(this.Id + '_cancelButton', 'Cancel', false, 'return false', this.cancelButtonFunction);
            dialogButtonContainer.appendChild(cancelButton);
        }

        dialogHeader.appendChild(dialogIcon);
        dialogHeader.appendChild(dialogHeaderText);
        dialogHeader.appendChild(this._closeButton);

        dialogFrame.appendChild(dialogHeader);
        dialogFrame.appendChild(dialogMessage);
        dialogFrame.appendChild(dialogButtonContainer);

        document.body.appendChild(dialogFrame);
    },

    _createCloseButton: function DialogBox$_createCloseButton(id) {
        var element = $(document.createElement('div'));
        element.setAttribute('id', this.Id + '_closeButton');
        element.className = 'dialogCloseButtonNormal';
        return element;
    },

    _closeButtonOnMouseOver: function DialogBox$_closeButtonOnMouseOver(sender, args) {
        this._closeButton.className = 'dialogCloseButtonOver';
    },

    _closeButtonOnMouseOut: function DialogBox$_closeButtonOnMouseOut(sender, args) {
        this._closeButton.className = 'dialogCloseButtonNormal';
    },

    _closeButtonOnClick: function DialogBox$_closeButtonOnClick(sender, args) {
        this._closeButton.className = 'dialogCloseButtonNormal';
        document.body.removeChild($(this.Id));
    },

    _okButtonOnClick: function DialogBox$_okButtonOnClick(sender, args) {
        document.body.removeChild($(this.Id));
    },

    _addButton: function DialogBox$_createButton(id, text, dismiss, returns, clickevent) {
        var parentElement = document.getElementById(this.Id + 'MessageButton');
        var newButton = this._createButton(id, text, dismiss, returns, clickevent);
        parentElement.appendChild(newButton);
    },

    _createButton: function DialogBox$_createButton(id, text, dismiss, returns, clickevent) {
        var element = $(document.createElement('div'));
        element.setAttribute('id', id);
        element.className = 'dialogButton';
        element.innerHTML = text;
        if (dismiss) {
            clickevent = 'document.body.removeChild($(\'' + this.Id + '\'));' + clickevent + ';';
            //element.setAttribute('onclick', 'document.body.removeChild($(\''+ this.Id +'\'));' + returns +'');
        }
        if (returns) {
            clickevent = clickevent + returns;
        }
        element.setAttribute('onclick', clickevent);
        return element;
    },

    _createDiv: function DialogBox$_createDiv(id, className, html) {
        var element = $(document.createElement('div'));
        element.setAttribute('id', id);
        element.className = className;
        if (html) {
            element.innerHTML = html;
        }
        return element;
    }
}

function PresentationFailedToLoad(id, error) {
    if (GlobalOptions.ErrorPage.length > 0) {
        var errorPage = GlobalOptions.ErrorPage;
        if (errorPage.indexOf('?') > -1) {
            errorPage += '&';
        }
        else {
            errorPage += '?';
        }

        if (window.ErrorStatus) {
            var errorMessage = String.format("Manifest Load Error : {0} - {1}", ErrorStatus.Code, ErrorStatus.Text);
            errorPage = String.format("{0}errorType=ClientLoad&errorDetails={1}", errorPage, encodeURIComponent(errorMessage));
        }
        else {
            errorPage = String.format("{0}errorType=ClientLoad&errorDetails={1}", errorPage, encodeURIComponent(error));
        }

        window.location = errorPage;
    }

    var errorMessage = 'The requested presentation failed to load.<br/><br/>';
    var presentationFailureErrorDialog = new DialogBox(id);
    presentationFailureErrorDialog.Message = errorMessage + error;
    presentationFailureErrorDialog.Title = 'Mediasite Error';
    presentationFailureErrorDialog.Id = id;
    presentationFailureErrorDialog.okButton = true;
    presentationFailureErrorDialog.OnLoad();
    return false;
}


function ReportingCallManager() {
    ReportingCallManager.prototype.OnSuccess = function(result, context) {
    }

    ReportingCallManager.prototype.OnFailure = function(error, context) {
        //need to eat abort errors
    }
}

OptionsManager = function() {
    this._options = {};
    this._Initialize();
}

OptionsManager.prototype =
{
    _Initialize: function() {
    },

    _GetBoolOptionFromCookie: function(optionType, def) {
        return new MediasitePlayerCookie().GetBoolValue(optionType, def);
    },

    _SetBoolOptionToCookie: function(optionType, val) {
        return new MediasitePlayerCookie().SetBoolValue(optionType, val);
    },

    GetOption: function(optionType) {
        var val = this._options[optionType];
        if (typeof (val) != 'undefined') {
            return val;
        }
        return null;
    },

    SetOption: function(optionType, val) {
        this._options[optionType] = val;
        this._FireOptionChanged(optionType, val);
        this._SetBoolOptionToCookie(optionType, val);
    },

    _FireOptionChanged: function(optionType, val) {
        mPlayer.EventManager.PostEvent(SfKernel.EventType.OptionChanged, this, { OptionType: optionType, Value: val });
    }
}



SfKernel.XMLHttpSyncExecutor = function SfKernel$XMLHttpSyncExecutor() {

    SfKernel.XMLHttpSyncExecutor.initializeBase(this);
}

function SfKernel$XMLHttpSyncExecutor$executeRequest() {
    if (arguments.length !== 0) throw Error.parameterCount();
    this._webRequest = this.get_webRequest();

    if (this._started) {
        throw Error.invalidOperation(String.format(Sys.Res.cannotCallOnceStarted, 'executeRequest'));
    }
    if (this._webRequest === null) {
        throw Error.invalidOperation(Sys.Res.nullWebRequest);
    }

    var body = this._webRequest.get_body();
    var headers = this._webRequest.get_headers();
    this._xmlHttpRequest = new XMLHttpRequest();
    this._xmlHttpRequest.onreadystatechange = this._onReadyStateChange;

    var verb = this._webRequest.get_httpVerb();
    this._xmlHttpRequest.open(verb, this._webRequest.getResolvedUrl(), false /*SYNC*/);
    if (headers) {
        for (var header in headers) {
            var val = headers[header];
            if (typeof (val) !== "function")
                this._xmlHttpRequest.setRequestHeader(header, val);
        }
    }

    if (verb.toLowerCase() === "post") {
        // If it's a POST but no Content-Type was specified, default to application/x-www-form-urlencoded
        if ((headers === null) || !headers['Content-Type']) {
            this._xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        }

        // DevDiv 15893: If POST with no body, default to ""(FireFox needs this)
        if (!body) {
            body = "";
        }
    }

    this._xmlHttpRequest.send(body);
    this._started = true;
}

SfKernel.XMLHttpSyncExecutor.prototype = {

    executeRequest: SfKernel$XMLHttpSyncExecutor$executeRequest
}
SfKernel.XMLHttpSyncExecutor.registerClass('SfKernel.XMLHttpSyncExecutor', Sys.Net.XMLHttpExecutor);

