var _simple_audio,
    _simple_video,
    childWinRef,
    _global_fname,
    _global_lname,
    _global_player,
    _global_workstation,
    _isLMS = false,
    _timerInstance = null,
    _lmsType = '1.2'
//  local, 1.2, 2004, xAPI

var Shell = function () {

    _isLMS = false;

    let _self = this,
        isFirstTimeLaunch = false,
        _global_wrapper_name = "#global_wrapper",
        _global_wrapper = $(_global_wrapper_name),

        _shellModel = null,
        _LS = null,
        _user_details = null,
        _shellNavigation = null,
        _shellController = null,
        _mediaManager = null;


    let _blankAudio = {
        'url': "./shell/audio/blank.mp3",
        'autoplay': true,
        'timeline': [{}],
        'transcript': ""
    }

    let addEventsOnDocuments = function () {
        try {
            let meta = $('<meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0"/>');
            let t = top.document.getElementsByTagName("head")[0].appendChild(meta.get(0));
        } catch (err) { }


        window.addEventListener('focus', function () {
            let focused = document.hasFocus();
            if (focused) { }
        });



        if (navigator.userAgent.match(/iPhone|iPad|iPod|Mac/i) || navigator.userAgent.match(/Android/i)) {
            $(window).on("pagehide", function (e) {
                if (childWinRef) {
                    childWinRef.closeFromParentWin();
                    childWinRef.close();
                    childWinRef = null;
                }
            });

        } else {
            $(window).on("beforeunload", function (e) {
                SetCourseDetails();
                if (childWinRef) {
                    childWinRef.closeFromParentWin();
                    childWinRef.close();
                    childWinRef = null;
                }
            });
        }

        SetCourseDetails = function () {
            if (window.opener != null && !window.opener.closed) {
                //var getParentData = $.parseJSON(window.opener.$("#courseData").html());
                window.opener.updateCourseDetail();
                // if (window.opener.courseDetails) {
                //     window.opener.courseDetails.Employbridge.status = "inprogress"
                //     window.opener.$("#courseData").html(JSON.stringify(window.opener.courseDetails));
                //     window.opener.$("#Agile.btn").removeClass("disabled")
                // }


            }
        }

        window.addEventListener('blur', function () { });

        if (navigator.userAgent.match(/iPhone|iPad|iPod|Mac/i)) {
            $(window).off('orientationchange').on("orientationchange", function () {
                if (window.orientation == 0 || window.orientation == 180) {
                    alert('This course is best viewed in the landscape orientation.');
                }
            }).trigger('orientationchange');
        }

        try {
            $(document).on("contextmenu cut copy paste", function (e) {
                try {
                    let cDetails = _self.data['shellController'].getCurrentMnoNdPno();
                    if (cDetails.mNo == 3 && cDetails.pNo == 3) {
                        return true;
                    } else {
                        e.preventDefault();
                        return false;
                    }
                } catch (er) {
                    e.preventDefault();
                    return false;
                }
            });
        } catch (err) {

        }

    }


    let loadLaunch = function (callback) {
        console.log('loadLaunch: ')
        
        try {
            MediaManager.stop();
        } catch (err) {
            Utils.error(err)
        }
        try {
            Utils.loadGlobalTemplate(_global_wrapper, 'launch', function () {
                let _launch = new Launch();
                _launch.init();

                Utils.loadTemplate("#simple_audio_holder", "simple_audio", function () {
                    console.log('loadSimpleAudio: ')
                    let _aData = _blankAudio;
                    _aData['callback'] = function () { }
                    _simple_audio = new Simple_Audio();
                    _simple_audio.init(_aData);
                });

                if (callback) {
                    callback();
                }
            })
        } catch (err) {
            Utils.error(err)
        }
    }

    let loadLogin = function (callback) {

        let _imgs = _shellModel.configData['imgs'] || ["../../shell/imgs/background-pattern.png"];

        Utils.preLoadImgs_1(_imgs, function () {
            try {
                MediaManager.stop();
            } catch (err) {
                Utils.error(err)
            }
            try {
                Utils.loadGlobalTemplate(_global_wrapper, 'login', function () {

                    Utils.loadTemplate("#simple_audio_holder", "simple_audio", function () {
                        console.log('loadSimpleAudio: ')
                        let _aData = _blankAudio;
                        _aData['callback'] = function () { }
                        _simple_audio = new Simple_Audio();
                        _simple_audio.init(_aData);
                        let _loadLogin = new Login();
                        _loadLogin.init();
                    });

                    if (callback) {
                        callback();
                    }
                })
            } catch (err) {
                Utils.error(err)
            }
        })

        console.log('loadLogin: ')

    }

    let loadAvatar = function (callback) {
        console.log('loadAvatar: ')
        try {
            MediaManager.stop();
        } catch (err) {
            Utils.error(err)
        }
        try {
            Utils.loadGlobalTemplate(_global_wrapper, 'avatar', function () {
                let _loadAvatar = new Avatar();
                _loadAvatar.init();
                if (callback) {
                    callback();
                }
            })
        } catch (err) {
            Utils.error(err)
        }
    }


    let loadTheme = function (callback) {
        console.log('loadTheme: ')
        try {
            MediaManager.stop();
        } catch (err) {
            Utils.error(err)
        }
        try {
            Utils.loadGlobalTemplate(_global_wrapper, 'theme', function () {
                let _loadTheme = new Theme();
                _loadTheme.init();
                if (callback) {
                    callback();
                }
            })
        } catch (err) {
            Utils.error(err)
        }
    }

    let loadIntro = function (callback) {
        console.log('loadIntro: ')
        try {
            MediaManager.stop();
        } catch (err) {
            Utils.error(err)
        }
        try {
            Utils.loadGlobalTemplate(_global_wrapper, 'intro', function () {
                let _intro = new Intro();
                _intro.init();
                if (callback) {
                    callback();
                }
            })
        } catch (err) {
            Utils.error(err)
        }
    }

    let loadObjective = function (callback) {
        console.log('loadObjective : ')
        try {
            MediaManager.stop();
        } catch (err) {
            Utils.error(err)
        }
        try {
            Utils.loadGlobalTemplate(_global_wrapper, 'objective', function () {
                let _objective = new Objective();
                _objective.init();
                if (callback) {
                    callback();
                }
            })

        } catch (err) {
            Utils.error(err)
        }
    }


    let loadShellWrapper = function (callback) {
        console.log('loadShellWrapper : ')
        try {
            MediaManager.stop();
        } catch (err) {
            Utils.error(err)
        }
        console.log('loadShellWrapper : ')

        let _global_wrapper_loaded = false
        try {
            Utils.loadGlobalTemplate(_global_wrapper, 'shellWrapper', function () {

                if (!_global_wrapper_loaded) {
                    loadShellModel();
                    if (callback) {
                        callback();
                    }
                }
                _global_wrapper_loaded = true;

            })

        } catch (err) {
            Utils.error(err)
        }
    }

    let addEventsOnGlobalWrapper = function () {

        _global_wrapper.off('loadLaunch').on('loadLaunch', function () {
            loadLaunch();
        })

        _global_wrapper.off('loadLogin').on('loadLogin', function () {
            loadLogin();
        })

        _global_wrapper.off('loadAvatar').on('loadAvatar', function () {
            loadAvatar();
        })

        _global_wrapper.off('loadTheme').on('loadTheme', function () {
            loadTheme();
        })

        _global_wrapper.off('loadIntro').on('loadIntro', function () {
            loadIntro();
        })

        _global_wrapper.off('loadObjective').on('loadObjective', function () {
            loadObjective();
        })

        _global_wrapper.off('loadShellWrapper').on('loadShellWrapper', function () {

            loadShellWrapper(function () {

            });
        })

        _global_wrapper.off('setFirstTimeLaunchData').on('setFirstTimeLaunchData', function (e, _isFirstTimeLaunch) {
            isFirstTimeLaunch = _isFirstTimeLaunch;
        });

        _global_wrapper.off('getFirstTimeLaunchData').on('getFirstTimeLaunchData', function () {
            _global_wrapper.trigger("takeFirstTimeLaunchData", isFirstTimeLaunch);
        });


    }

    let checkONLineOffline = function () {
        try {
            var status = navigator.onLine ? true : false,
                _msg = (status == true) ? "'You are online!" : 'You are offline!'
            console.log('checkONLineOffline:    ', _msg)
            return status

        } catch (err) {
            console.error("checkONLineOffline:	", err.toString())
        }
    }


    let startCourse = function () {

        _shellModel = new ShellModel();

        let _CLS = new customLocalStorage();
        _LS = _CLS;

        _user_details = _shellModel.user_details;

        loadConfig(function () {

            let _isOnLine = checkONLineOffline();

             if (window_opener) {
                 let _cDetails = window_opener.courseDetail;
                 if (_cDetails && _cDetails.userName != null) {
                     _user_details['userName'] = _cDetails.userName
                 }
                 if (_cDetails._lmsType == 'xAPI') {
                     _lmsType = _cDetails._lmsType
                     _LS = _cDetails.xapi_manager;
                 }
             }

            var nextStep = function () {

               if (window_opener) {
                    let _cDetails = window_opener.courseDetail;
                    if (_cDetails && _cDetails.userName != null) {
                        _user_details['userName'] = _cDetails.userName
                    }
                }
                

                console.log("_lmsType:    ", _lmsType)
                console.log("_isLMS:    ", _isLMS)

                _self.data = {
                    'shellModel': _shellModel,
                    'mediaManager': MediaManager,
                    'LS': _LS
                }

                window['course'] = _self;

                try {
                    MediaManager.stop();
                } catch (err) {
                    Utils.error(err)
                }


                Utils.updateUtilsData(_self.data);

                if (window_opener) {
                    let _cDetails = window_opener.courseDetail;
                    if (_cDetails && _cDetails.userName != null) {
                        let _aData = _blankAudio;
                        _aData['callback'] = function () { }
                        Utils.loadSimpleAudio(_aData, function () {
                            _global_wrapper.trigger('loadShellWrapper')
                        })
                        return
                    }
                }
               
                _global_wrapper.trigger('loadLaunch');
            }

            if (_lmsType == '1.2' || _lmsType == '2004') {
                
                _LS = new SCORM_Manager();
               
                let timeout = setTimeout(function () {
                    if (!_isLMS) {
                        _lmsType = 'local'
                        _LS = _CLS;
                        nextStep();
                    }
                }, 5000);

                _LS.init(_lmsType, function () {
                    _isLMS = true;
                    clearTimeout(timeout);
                    _user_details['userName'] = _LS.getUserDetail(); 
                    nextStep();
                });

               
                
            } else if (_lmsType == 'xAPI') {
                _LS = new XAPI_Manager();
                nextStep();
            } else {
                _lmsType = 'local'
                _LS = _CLS;
                nextStep();
            }

        })


    }



    let loadConfig = function (callback) {

        _global_wrapper.off("configLoaded").on("configLoaded", function () {
            if (callback) {
                callback()
            }
        })

        let _config = getParameterByName('cm') || 'shell_config'
        _shellModel.init(_config);

    }

    let getParameterByName = function (name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        let regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }



    let loadShellModel = function () {
        _global_wrapper = $("#global_wrapper")
        _global_wrapper.off('loadLaunch');
        _global_wrapper.off('loadIntro');
        _global_wrapper.off('loadLogin');
        _global_wrapper.off('loadAvatar');


        _shellNavigation = new ShellNavigation();
        _shellController = new ShellController();
        _mediaManager = MediaManager;

        //var _mediaManager = new MediaManager();
        _self.data['shellNavigation'] = _shellNavigation
        _self.data['shellController'] = _shellController
        _self.data['mediaManager'] = _mediaManager


        _shellController.init(_self.data);
        window['course'] = _self;
        _shellModel.updateTitle();


    }


    var init = function () {

        console.log('Shell:   init');

        let _libsJsArr = ["./libs/jquery/jquery.plugin.js", "./libs/jquery/jquery-ui.js", "./libs/jquery/jquery.ui.touch-punch.min.js", "./libs/jquery/jquery.draggableTouch.js", "./libs/jquery/jquery.browser.min.js", "./libs/jquery/jquery.mask.min.js", "./libs/bootstrap/js/bootstrap.min.js", "./libs/videojs/video.min.js", "./libs/xapi/xapiwrapper.min.js", "./libs/scorm/SCORM_API_wrapper.js"]

        let _shellJsArr = ["./shell/js/xapiHandler.js", "./shell/js/mediaManager.js", "./shell/js/xapiManager.js", "./shell/js/scormManager.js", "./shell/js/shellModel.js", "./shell/js/shellNavigation.js", "./shell/js/shellController.js"]

        // console.log(window.opener.courseDetails)
        // _libsJsArr = _libsJsArr.join(".libs/")

        Utils.jsLoader(_libsJsArr, function () {
            //   _shellJsArr = _shellJsArr.join("./shell/js/")
            Utils.jsLoader(_shellJsArr, function () {
                addEventsOnDocuments();
                addEventsOnGlobalWrapper();
                startCourse();
            })
        });

    }

    var resizable = function () {

        var scale = {
            x: 1,
            y: 1
        },
            zoomFactor = 1,
            stageLeft = 0,
            config = {
                stageWidth: 1366,
                stageHeight: 768
            };

        var scaleStage = function () {

            var rootElem = document.getElementById("fixFrame");

            scale.x = window.innerWidth / config["stageWidth"];
            scale.y = window.innerHeight / config["stageHeight"];
            let newScale = scale.x + ", " + scale.y;

            if (scale.x < scale.y) {
                zoomFactor = scale.x;
                newScale = scale.x + ", " + scale.x;
            } else {
                zoomFactor = scale.y;
                newScale = scale.y + ", " + scale.y;
            }

            let newWidth = Number(newScale.split(",")[0]) * config["stageWidth"];
            let leftPos = (window.innerWidth - newWidth) / 2;

            let newHeight = Number(newScale.split(",")[0]) * config["stageHeight"];
            let topPos = (window.innerHeight - newHeight) / 2;

            stageLeft = leftPos;
            window.rootLeftElmPos = stageLeft;
            var styleObj = {};

            styleObj = {
                "-webkit-transform": "scale(" + newScale + ")",
                "-moz-transform": "scale(" + newScale + ")",
                "-ms-transform": "scale(" + newScale + ")",
                "-o-transform": "scale(" + newScale + ")",
                transform: "scale(" + newScale + ")",
                "-webkit-transform-origin": "left top",
                "-moz-transform-origin": "left top",
                "-ms-transform-origin": "left top",
                "-o-transform-origin": "left top",
                "transform-origin": "left top",
                position: "absolute",
                top: topPos + "px",
                left: leftPos + "px",
                overflow: "hidden",
                width: config["stageWidth"] + "px",
                height: config["stageHeight"] + "px",
            };

            for (var key in styleObj) {
                if (styleObj.hasOwnProperty(key)) {
                    rootElem.style[key] = styleObj[key];
                }
            }

            window.zoomFactor = zoomFactor;
        }

        scaleStage();

        window.addEventListener("resize", scaleStage);

    }

    init();

    resizable();

}

    (function () {
        let _shell = new Shell();
    })