LessonRunModes = {
    TestFromSelection: 0,
    TestFullLesson: 1,
    Publish: 2
};
ScormTypes = {
    NoScorm: -1,
    Scorm12: 0,
    Scorm20043Rd: 1
};


Ext.define('LessonManager', {
    constructor: function () {
        this.AuthorLesson = null;
        this.LessonExitedNormally = false;
        this.InitializedHandler = null;
        this.StateManager = null;
        this.Console = false;

        if (AuthorConsole) {
            this.Console = new AuthorConsole();
        }
        this.VariableWatchWindow = false;
        if (VariableMonitor) {
            this.VariableWatchWindow = new VariableMonitor();
        }
        this.LessonFrame = new LessonFrameClass();
        this.VisitedElementIds = new Ext.util.MixedCollection();
        this.ActionKeyMap = new Ext.util.MixedCollection();
        this.ScormAdapter = null;
    },
    isElementVisited: function (element) {
        return this.VisitedElementIds.containsKey(element.id);
    },
    refreshVariableMonitor: function () {
        if (this.VariableWatchWindow && this.VariableWatchWindow.isVisible()) {
            this.VariableWatchWindow.refreshVariableValues();
        }
    },
    log: function (info) {
        try {
            if (this.RunMode != LessonRunModes.TestFromSelection) {
                return;
            }
        } catch (err) {
        }
        if (window.console) {
            window.console.log(info);
        }
        else if (this.Console) {
            this.Console.log(info);
            if (!this.Console.isVisible()) {
                this.Console.show();
            }
        }
        else {
            alert(info);
        }
    },
    toString: function () {
        return Ext.String.format("LessonManager:\n{0}\nRunMode: {1}\nStartNodeID: {2}\nStartElementID: {3}", this.AuthorLesson, this.RunMode, this.StartNodeID, this.StartElementID);
    },
    initializeLesson: function (onInitializedHandler) {
        this.InitializedHandler = onInitializedHandler;

        var preferences = Author.lessonXMLDoc.getElementsByTagName('lessonPreference')[0];
        var showPlayOnMobile = XmlHelper.getBooleanAttribute(preferences, 'showPlayOnMobile');

        
        this.initializeLesson2();
        
    },
    DisplayPlayButton: function ()
    {
        if (this.Initialized)
        {
            return;
        }
        
        var playdiv = document.getElementById("playDiv");
        var playButton = document.getElementById("playButton")
        playDiv.style.display = "flex";
        playButton.onclick = function(evt, el, o) { 
            
            if (evt)  evt.stopPropagation();//Prevents advance to next page when image clicked
            playdiv.style.display = "none";
            var audio = document.getElementById("html5audio");
            audio.src = "lib/media/silence.mp3";
            audio.onplay = AudioPlayed;
            audio.play();
        }
    },
    Initialized: false,
    initializeLesson2: function ()
    {
        var runModeNode = Author.lessonXMLDoc.getElementsByTagName('runOptions')[0];
        if (runModeNode) {
            this.RunMode = XmlHelper.getIntegerAttribute(runModeNode, 'mode');
            this.StartNodeID = XmlHelper.getStringAttribute(runModeNode, 'startLessonNodeID');
            this.StartElementID = XmlHelper.getStringAttribute(runModeNode, 'startElementID');
        } else {
            this.RunMode = LessonRunModes.Publish;
            this.StartElementID = "-1";
            this.StartNodeID = "-1";
        }
        var scormNode = Author.lessonXMLDoc.getElementsByTagName('scormOptions')[0];
        if (scormNode) {
            this.IsScorm = true;
            this.ScormVersion = XmlHelper.getIntegerAttribute(scormNode, 'scormVersion');
            // Try to connect to scorm api.
            this.ScormAdapter = new AuthorScromAdapter(this.ScormVersion);
            if (this.ScormAdapter.scormInitialize()) {
                var studentFullName = this.ScormAdapter.getStudentName();
                Author.VariableManager.setSystemVariableValue(AuthorSystemVariables.FULLNAME, studentFullName);
                var nameS = studentFullName.split(",");
                Author.VariableManager.setSystemVariableValue(AuthorSystemVariables.FIRSTNAME, nameS[0]);
                Author.VariableManager.setSystemVariableValue(AuthorSystemVariables.LASTNAME, nameS[1]);
                var studentID = this.ScormAdapter.getStudentID();
                Author.VariableManager.setSystemVariableValue(AuthorSystemVariables.USERID, studentID);
                var completionStatus = this.ScormAdapter.getLessonStatus();
                if (completionStatus == "not attempted") {
                    this.ScormAdapter.setLessonStatus('incomplete');
                }
                this.ScormAdapter.isScoreSet = false;
            } else {
                alert("Cannot connect to the LMS SCORM API. \nYou can still view the lesson but no result will be sent back to LMS.");
                this.IsScorm = false;
                this.ScormVersion = ScormTypes.NoScorm;
            }
        } else {

            this.IsScorm = false;
            this.ScormVersion = ScormTypes.NoScorm;
        }


        // preference node

        this.doInitializeLesson();
    },
    setViewPort: function () {

        var viewPort = document.getElementById('viewportmeta');
        var lWidth = this.AuthorLesson.Width;
        var lHeight = this.AuthorLesson.Height;
        var userscalable = 1;
        var wWidth = Ext.Element.getViewportWidth();
        var wHeight = Ext.Element.getViewportHeight();
        var vW2H = lWidth / lHeight;
        var vWidth, vHeight;

		vWidth = lWidth;
		vHeight = lHeight;
		var initScale = wWidth / vWidth;

		

        if (this.IsScorm) {
            if (Ext.is.ios || Ext.is.Android) {				

				var wr= wWidth/lWidth;  // the minimum desire width ratio
				var hr= wHeight/lHeight;  // the minimum desire height ratio
				
				if(hr<wr){
					initScale=hr;
			
					if(hr<1){ // if it is small screen
						vHeight = lHeight;
						vWidth = wWidth/hr;
					}
				}else{
					initScale=wr;
					if(wr<1){
						vWidth = lWidth;
						vHeight = wHeight/wr;
					}
				}	

            }
        }	

        if (this.IsScorm && Author.isIOS()){
            var scormLayout = parent.document.getElementById('scorm_layout');
            scormLayout.style = 'height: '+ (lHeight * 1.12) +'px;';
        }
		
        var viewPortStr = Ext.String.format("width={0}, height={1}, user-scalable={2}, initial-scale={3}", vWidth, vHeight, userscalable, initScale);


        if (this.IsScorm) {
			parent.document.getElementsByName('viewport')[0].setAttribute('content', viewPortStr);
		} else {
			viewPort.setAttribute('content', viewPortStr);
		}
	
    },
    doInitializeLesson: function () {
        var lesson = new LessonClass(Author.lessonXMLDoc.getElementsByTagName('lesson')[0], {
            listeners: {
                lessonInitialized: this.onLessonInitialized,
                lessonTimeout: this.onLessonTimeout,
                scope: this
            }
        });
    },
    initializeStateManager: function () {
        this.StateManager = new StateManager({
            Expires: 90, //, //30 days
            Domain: document.domain
        });
        this.loadLessonState();
    },
    saveLessonState: function () {
        var userid = Author.VariableManager.getSystemVariableValue(AuthorSystemVariables.USERID);
        this.StateManager.set(this.AuthorLesson.NameNoSpace + "[" + userid + "]", this.AuthorLesson.serialize());
    },
    loadLessonState: function () {
        var userid = Author.VariableManager.getSystemVariableValue(AuthorSystemVariables.USERID);
        var savedState = this.StateManager.get(this.AuthorLesson.NameNoSpace + "[" + userid + "]", null);
        if (savedState) {
            this.AuthorLesson.deserialze(savedState);
        }
    },
    clearVeryOldLessonState: function () {
        this.StateManager.clearVeryOldCookies();
    },
    onLessonTimeout: function (lesson) {
        lesson.LessonRoot.ChildNode.onExitLesson(true);
    },
    onLessonInitialized: function (lesson, duration) {
        this.AuthorLesson = lesson;


        this.setupGlobalEventListener();
        this.ReferenceWindow = new ReferenceWindowClass();
        //this.LessonFrame.setLinearGradient('#000000', '#CCD8FF');
        //this.LessonFrame.setImage('wood.jpg');


        if (typeof(this.InitializedHandler) == 'function') {
            this.InitializedHandler.call(this);
        }
    },
    setupGlobalEventListener: function () {
        var bodyEl = Ext.getBody();
        bodyEl.dom.setAttribute('tabindex', -1);
        bodyEl.addListener("click", this.onMouseClicked, this);
        bodyEl.addListener("dblclick", function (e) {
            e.stopEvent();
        });
        bodyEl.addListener("contextmenu", Ext.emptyFn, null, {
            preventDefault: true
        });

        if(this.RunMode!== LessonRunModes.Publish){
            this.addQCButton(bodyEl);
            this.addRefButton(bodyEl);
            this.addVariableButton(bodyEl);
        }
        else if (Author.LessonManager.AuthorLesson.ShowReferenceButton )
        {
            this.addRefButton(bodyEl);
        }

        var keyCodeArray = new Array();
        for (var i = 0; i < 223; i++) {
            keyCodeArray.push(i);
        }
        Author.keyMap = new Ext.util.KeyMap(bodyEl, [
            {
                key: keyCodeArray,
                fn: function (key, e) {
                    this.onKeyDown(e);
                },
                scope: this
            }
        ]);
        Ext.EventManager.onWindowResize(this.onWindowResized, this);
        Ext.EventManager.addListener(window, 'unload', this.onWindowUnload, this);
        window.onerror = this.onError;
        window.onbeforeunload = this.onBeforeWindowUnload;

    },

    addQCButton: function (body) {
        if (this.AuthorLesson.QCUrl != null && this.AuthorLesson.QCUrl.length > 0) {
            this.QCButton = body.createChild({
                tag: 'button',
                tabindex: -1,
                id: 'qcBtn',
                cls: 'qcBtn',
                html: 'QC',
                title: 'Quality Control'
            });
            this.QCButton.addListener('click', this.popUpQCWindow, this);
        }
    },

    addRefButton: function (body) {
        this.RefButton = body.createChild({
            tag: 'button',
            tabindex: -1,
            id: 'refBtn',
            cls: 'qcBtn',
            html: 'R',
            title: 'Reference'
        });
        this.RefButton.addListener('click', this.popUpRefWindow, this);
    },

    addVariableButton: function (body) {
        this.VariableButton = body.createChild({
            tag: 'button',
            tabindex: -1,
            id: 'variableBtn',
            cls: 'qcBtn',
            html: 'V',
            title: 'Variable Watch'
        });
        this.VariableButton.addListener('click', this.popUpVariableWindow, this);
    },

    onError: function (sMsg, sUrl, sLine) {
        Author.log(sMsg + "\n" + sUrl + "\n" + sLine);
        return true;
        if (sLine == 1)
            return true;
        else
            return false;
    },

    sendWebResult: function () {
        var query = Ext.String.format("TraineeID={1}", this.AuthorLesson.WebResultUrl, Author.VariableManager.getSystemVariableValue(AuthorSystemVariables.USERID, "NoID"));
        var netFields = this.AuthorLesson.WebResultFields;
        if (netFields.substring(0, 1) == "1") {
            query += Ext.String.format("&LessonName={0}", this.AuthorLesson.Name);
        }
        if (netFields.substring(1, 2) == "1") {
            query += Ext.String.format("&{0}", Ext.Object.toQueryString({StartTime: new Date(Author.LessonManager.AuthorLesson.StartTime)}));
        }
        if (netFields.substring(2, 3) == "1") {
            query += Ext.String.format("&{0}", Ext.Object.toQueryString({EndTime: new Date()}));
        }
        if (netFields.substring(3, 4) == "1") {
            query += Ext.String.format("&Pass={0}", this.AuthorLesson.PassMark);
        }
        if (netFields.substring(4, 5) == "1") {
            query += Ext.String.format("&Score={0}", Author.VariableManager.getSystemVariableValue(AuthorSystemVariables.LESSONSCORE, Author.VariableManager.getSystemVariableValue(AuthorSystemVariables.SCORE, "0")));
        }
        if (netFields.substring(5, 6) == "1") {
            query += Ext.String.format("&Total={0}", Author.VariableManager.getSystemVariableValue(AuthorSystemVariables.LESSONTOTAL, Author.VariableManager.getSystemVariableValue(AuthorSystemVariables.TOTAL, "0")));
        }
        if (netFields.substring(6, 7) == "1") {
            query += Ext.String.format("{0}", Author.VariableManager.getSystemVariableValue(AuthorSystemVariables.WEBINFO, ""));
        }
        var url = Ext.String.format("{0}?{1}", this.AuthorLesson.WebResultUrl, query);
        var httpIFrame = Ext.getBody().createChild({
            tag: "iframe",
            frameborder: Ext.isIE ? "0" : "1",
            style: "position:absolute;background-color:#fff;width:0px;height:0px;left:0px;top:-9999px"
            //  style:"position:absolute;background-color:#fff;width:400px;height:200px;left:500px;top:50px"
        });

        var infoDiv = Ext.getBody().createChild({
            tag: "div",
            style: "color:white;font-size:12pt;text-align:center;fontfamily:Segoe UI, Tahoma, Trebuchet MS, Arial",
            html: "Sending result ..."
        });
        infoDiv.center();
        httpIFrame.on("load", function (e) {
            infoDiv.setVisible(false);
            Author.LessonManager.closeBrowserWindow();
        });
        httpIFrame.dom.src = url;

    },
    onExitLesson: function () {
        if (this.ReferenceWindow.isVisible()) {
            this.ReferenceWindow.hide();
        }
        Author.DisplayManager.clearScreen(this.AuthorLesson.LessonRoot);
        if (this.AuthorLesson.RepeatLesson) {
            Author.DisplayManager.showLesson(this.AuthorLesson, -1, -1);
        } else {
            this.LessonExitedNormally = true;
            var delayClose = false,
                that = this;
            if (this.IsScorm && this.ScormAdapter) {
                delayClose = true;
                if (!this.ScormAdapter.isScoreSet) {
                    Author.VariableManager.setSystemVariableValue(AuthorSystemVariables.SCORM_SCORE_RAW, Author.VariableManager.getSystemVariableValue(AuthorSystemVariables.SCORE, 0));
                }
                this.ScormAdapter.onLessonExit();
            }

            if (this.AuthorLesson.SendWebResult) {
                this.sendWebResult();
                return;
            }

            if (delayClose) {
                setTimeout(function () {
                    that.closeBrowserWindow();
                }, 500);
                return;
            }
            this.closeBrowserWindow();
        }
    },
    closeBrowserWindow: function () {
        if (Author.isAuthorViewer()) {
            window.location = "author:ExitLesson";
            return;
        }
        window.open('', '_self', '');
        window.close();
        top.window.close();
        setTimeout(function () {
            Ext.MessageBox.show({
                msg: "<p>You have exited the eLearning module. Please close the browser.</p>",
                title: "eLearning module finished",
                width: 380
            });
        }, 1000);
    },
    checkGlobalKeyHandlers: function (e) {
        if (e.shiftKey && e.getKey() == e.F12 && this.ReferenceWindow) {
            this.ReferenceWindow.show();
            return true;
        }
        if (e.shiftKey && e.getKey() == e.F11 && this.VariableWatchWindow) {
            this.VariableWatchWindow.show();
            return true;
        }

        //check QC Key
        if (this.AuthorLesson.QCUrl != null && this.AuthorLesson.QCUrl.length > 0) {
            var showQCWindow = false;
            switch (this.AuthorLesson.QCKey) {
                case QCKeys.F12:
                    showQCWindow = e.getKey() == e.F12 && !e.shiftKey && !e.altKey && !e.ctrlKey;
                    break;
                case QCKeys.CtrlF12:
                    showQCWindow = e.getKey() == e.F12 && !e.shiftKey && !e.altKey && e.ctrlKey;
                    break;
                case QCKeys.AltF12:
                    showQCWindow = e.getKey() == e.F12 && !e.shiftKey && e.altKey && !e.ctrlKey;
                    break;
            }
            if (showQCWindow) {
                this.popUpQCWindow();
                return true;
            }
        }

        return false;
    },
    popUpQCWindow: function () {
        //getElementName
        var eName = "";
        if (Author.CurrentStateManager.CurrentLessonNode) {
            eName = Author.CurrentStateManager.CurrentLessonNode.Name;
        }
        if (Author.CurrentStateManager.CurrentElement) {
            eName = Author.CurrentStateManager.CurrentElement.Name;
        }
        eName += AuthorCommons.getBrowserInfo();
        var qcUrl = this.AuthorLesson.QCUrl + "?" + Ext.Object.toQueryString({eName: eName, pName: this.AuthorLesson.Name});
        window.open(qcUrl);
        // currently not pausing the lesson. and use popup window only.
        //  var QCMessage = "Lesson is paused while you are in bug tracker.<br/>";
        // QCMessage += "Please click OK to continue.";
        //window.clearTimeout(Author.DisplayManager.ActionTimer);
        // Author.DisplayManager.Pause = null;
        /* Ext.MessageBox.alert('QC', QCMessage, function () {
         if (Author.CurrentStateManager.CurrentList) {
         Author.DisplayManager.processListActions();
         }
         });*/

    },
    popUpRefWindow: function () {
        this.ReferenceWindow.show();
    },
    popUpVariableWindow: function () {
        this.VariableWatchWindow.show();
    },
    registerActionKeyMap: function (keyCodeStr, actionId) {
        if (keyCodeStr == null) return;
        if (this.ActionKeyMap.containsKey(keyCodeStr)) {
            var oldActionID = this.ActionKeyMap.getByKey(keyCodeStr);
            if (oldActionID != actionId) {
                // Author.log(Ext.String.format("{0} is mapped to {1}, will map it to {2}", keyCodeStr, oldActionID, actionId));
            }
        }
        this.ActionKeyMap.add(keyCodeStr, actionId);
    },
    checkActionKeyMap: function (keyCodeStr) {
        //check key maps
        if (this.ActionKeyMap.containsKey(keyCodeStr)) {
            var actionID = this.ActionKeyMap.getByKey(keyCodeStr);
            var mappedAction = Author.CurrentStateManager.getActionByID(actionID);
            if (mappedAction == null) return false;
            if (typeof(mappedAction.triggeredByKey) == 'function') {
                mappedAction.triggeredByKey(keyCodeStr);

                return true;
            } else {
                return false;
            }
        }
        return false;
    },

    onKeyDown: function (e) {
        if (!this.isEventValidEventSource(e)) {
            return;
        }
        e.preventDefault();

        if (this.checkGlobalKeyHandlers(e)) {
            return;
        }

        var shift = 0 + (e.shiftKey ? 1 : 0) + (e.ctrlKey ? 2 : 0) + (e.altKey ? 4 : 0);
        if (shift == 0)  shift = 8;
        var keyCodeStr = Ext.String.format("{0},{1}", e.getCharCode(), shift);

        if (this.checkActionKeyMap(keyCodeStr)) {
            return;
        }

        //Author.log("LessonManager.onKeyDown: keyCodeStr: " + keyCodeStr + ", char:" + e.getCharCode() + ", ALT: " + e.altKey + ", CTRL: " + e.ctrlKey + ", SHIFT: " + e.shiftKey);

        if (Author.DisplayManager.Pause != null) {
            Author.DisplayManager.Pause.skipPauseByKeyDown(e);
        }
    },


    isEventValidEventSource: function (e) {

        if (this.Console && e.within(this.Console.LogWindow.getEl())) {
            return false;
        }
        if (this.VariableWatchWindow && e.within(this.VariableWatchWindow.VariableMonitorWindow.getEl())) {
            return false;
        }
        if (this.ReferenceWindow && e.within(this.ReferenceWindow.ReferenceWindow.getEl())) {
            return false;
        }
        if (this.LoginWindow && e.within(this.LoginWindow.LoginWindow.getEl())) {
            return false;
        }

        var eventTarget = Ext.get(e.getTarget());
        var a = eventTarget.parent("a");
        if (a) {
            return false;
        }
        var targetTagName = eventTarget.id;
        var toActionInfo = AuthorCommons.getActionInfoFromElementID(targetTagName);
        if (toActionInfo) {
            // Author.log("isEventValidEventSource:" + print(toActionInfo));
        }

        if (targetTagName.match(/TEXTFIELD.*/)) {
            return false;
        }
        if (targetTagName.match(/FLVPLAYERACTION.*/)) {
            return false;
        }
        if (targetTagName.match(/COMBOBOX.*/)) {
            return false;
        }
        if (targetTagName.match(/HOTSPOT.*/)) {
            return false;
        }

        if (e.getCharCode() == 9) {
            return false;
        }

        return true;
    },
    onMouseClicked: function (e, t, o) {
        //return;
        //  Author.log("LessonManager.onMouseClicked");

        if (!this.isEventValidEventSource(e)) {
            return;
        }
        e.stopEvent();

        if (Author.DisplayManager.Pause != null) {
            // Author.log("LessonManager.onMouseClicked");
            Author.DisplayManager.Pause.skipPauseByMouseClick(e, t, o);

        }
    },
    doLogin: function (onLoginDone) {
        if (this.RunMode == LessonRunModes.TestFromSelection) {
            Author.VariableManager.setSystemVariableValue(AuthorSystemVariables.USERID, 'TestUser');
            onLoginDone.call(this, true);
            return;
        }
        if (this.AuthorLesson.RequireLogin && !this.IsScorm) {
            this.LoginWindow = new AuthorLoginWindow(onLoginDone, this.AuthorLesson.LoginMessage, this.AuthorLesson.LoginPrompt, this.AuthorLesson.LoginLength, this.AuthorLesson.LoginValidationType);
            this.LoginWindow.show();
            //   onLoginDone.call(this, true);
        } else {
            onLoginDone.call(this, true);
        }
    },
    checkScreenSize: function (onCheckScreenSizeDone) {
        var viewSize = Ext.Element.getViewSize();

        var showScreenWarning = true;
        if (showScreenWarning && (viewSize.height < this.AuthorLesson.Height || viewSize.width < this.AuthorLesson.Width)) {
            var messageStr = "Your screen resolution may prevent you seeing the full screen of this eLearning module.<br/><br/>";
            messageStr += "We would recommend you maximise your browser and zoom the page to view this module. ";
            messageStr += "You may zoom the page by holding the Ctrl key and moving the mouse wheel or choose Zoom from the View menu.";
            messageStr += "<br/><br/>";
            messageStr += "Click OK when you are ready to start the eLearning.";
            this.ScreensizeDiv = Ext.getBody().createChild({
                tag: "div",
                style: "position:absolute;width:" + this.AuthorLesson.Width + "px;height:" + this.AuthorLesson.Height + "px;background-color:#ff0000;border:dashed 2px #ff0",
                html: "<p style='text-align:center'>Size of the lesson</p>"

            });
            this.ScreensizeDiv.center();
            this.ScreensizeDiv.setOpacity(0.6);
            this.ScreenWarning = new Ext.Window({
                layout: 'fit',
                title: 'Screen resolution warning',
                modal: true,
                hidden: true,
                closeAction: 'close',
                width: 420,
                height: 250,
                cls: "x-window x-window-plain x-window-dlg",
                resizable: false,
                buttons: [new Ext.Button({
                    text: "OK",
                    handler: function (b) {
                        this.ScreenWarning.close();
                    },
                    scope: this,
                    style: "position:absolute;left:315px;top:200px"
                })]
            });
            this.ScreenWarning.show();
            this.ScreenWarning.center();
            this.ScreenWarning.icon = this.ScreenWarning.body.createChild({
                tag: "img",
                src: "lib/images/icon-warning.gif",
                style: "position:absolute;top:15px;left:15px;"
            });
            this.ScreenWarning.warningText = this.ScreenWarning.body.createChild({
                tag: "div",
                style: "position:absolute;left:60px;top:15px;width:320px;height:380px;font-size:10pt",
                html: messageStr
            });


            this.ScreenWarning.addListener("close", onCheckScreenSizeDone);
        }
        else {
            onCheckScreenSizeDone.apply(this);
        }
    },
    onWindowResized: function (w, h) {
        try {
            if (this.ScreensizeDiv != null) {
                this.ScreensizeDiv.center();
                this.ScreenWarning.center();
                if (h <= this.AuthorLesson.Height || w <= this.AuthorLesson.Width) {
                    this.ScreensizeDiv.setStyle("background-color", "#f00");
                }
                else {
                    this.ScreensizeDiv.setStyle("background-color", "#0f0");
                }
            }
        }
        catch (err) {
        }

        if (Author.DisplayManager.BackgroundObject) {
            Author.DisplayManager.BackgroundObject.center();
        }
        if (this.Console && this.Console.isVisible()) {
            this.Console.moveToRightBottom();
        }
    },
    onBeforeWindowUnload: function (e, t, o) {
        if (!Author.LessonManager.LessonExitedNormally && this.IsScorm) {
            e = e || window.event;
            var msg = "Are you sure you want to exit this module?";
            if (e) {
                e.returnValue = msg;
            }


        if(this.IsScorm && this.ScormAdapter)
        {
            if (!this.ScormAdapter.isScoreSet) {
                Author.VariableManager.setSystemVariableValue(AuthorSystemVariables.SCORM_SCORE_RAW, Author.VariableManager.getSystemVariableValue(AuthorSystemVariables.SCORE, 0));
            }
            this.ScormAdapter.onLessonExit();
        }

        if (this.AuthorLesson.SendWebResult) {
            this.sendWebResult();
        }
            return msg;
        }
    },
    onWindowUnload: function (e, t, o) {
        
        if (!this.LessonExitedNormally) {
            if (this.IsScorm && this.ScormAdapter) {
                if (!this.ScormAdapter.isScoreSet) {
                    Author.VariableManager.setSystemVariableValue(AuthorSystemVariables.SCORM_SCORE_RAW, Author.VariableManager.getSystemVariableValue(AuthorSystemVariables.SCORE, 0));
                }
                this.ScormAdapter.onLessonExit();
            }
            if (this.AuthorLesson.SendWebResult) {
                this.sendWebResult();
            }
        }
        this.clearVeryOldLessonState();
        this.saveLessonState();
    }
})
;
