var SimpleTextImage = {
    // P01692
    jsonData: {},

    currentSection: 0,
    initTemplate: false,
    eventMgr: new EventManager(),

    imgRefArr: [],
    vObj: videoObject,
    isVideo: false,
    activityCompleted: false,

    reset: function() {
        try {
            var _self = TextImageObj;
            _self.currentSection = 0;
            _self.initTemplate = false;
            _self.vObj = videoObject;
            _self.isVideo = false;
            _self.activityCompleted = false;
        } catch (err) {

        }

    },
    init: function(data) {
        // console.clear();
        var _self = TextImageObj;
        _self.reset();
        try {
            _self.jsonData = data;
            _self.addEventForInitialize();
        } catch (err) {
            // console.log(err)
        }
        try {
            _self.updatePageTitle();
        } catch (err) {
            // console.log(err)
        }
        try {
            _self.updateVideoData(data)
            _self.addEventsOnVideo();
        } catch (err) {
            // console.log(err)
        }
    },

    addEventForInitialize: function() {
        var _self = TextImageObj;

        try {

            MainController.initializeTemplateInShell();

            _self.eventMgr.addControlEventListener(document, StaticLibrary.ON_PAGE_UNLOADED, _self.destroy);

            _self.eventMgr.addControlEventListener(document, StaticLibrary.CONTROL_AUDIO_VIDEO_EVENT, _self.handleControl);

        } catch (err) {
            // console.log(err)
        }
    },
    updateData: function(data) {
        var _self = TextImageObj;
        _self.jsonData = data;
    },
    updateLeftVideo: function(sNo, callback) {
        try {
            var _self = TextImageObj;
            _self.isVideo = true;
            var _section = _self.jsonData.sections[sNo];
            var _leftSideVideo = _section.leftSideVideo;
            _leftSideVideo['autoPlay'] = true;
            _self.showLeftVideo(_leftSideVideo, function() {
                callback();
            });
        } catch (err) {
            console.log('updateLeftVideo:	', err)
        }
    },
    updateRightVideo: function(sNo, callback) {
        try {
            var _self = TextImageObj;
            _self.isVideo = true;
            var _section = _self.jsonData.sections[sNo];
            var _rightSideVideo = _section.rightSideVideo;
            _rightSideVideo['autoPlay'] = true;
            _self.showRightVideo(_rightSideVideo, function() {
                callback();
            });

        } catch (err) {
            console.log('updateRightVideo:	', err)
        }
    },
    updateVideoData: function(data) {
        try {
            var _self = TextImageObj;
            _self.jsonData = data;
            if (_self.isVideo) {
                var _vObj = _self.vObj;
                _vObj.updateData(data);
            }
        } catch (err) {
            console.log('updateVideoData:	', err)
        }

    },
    updatePageTitle: function() {
        try {
            var container = $("#textImageContainer #sectionHolder");
            container.find("#contentHolder").prepend("<div class='page_title'></div>");
            var _cData = DataManager.TOCData[currentPageLocationIndex];
            if (_cData.showTitle == "true") {
                $('.page_title').html(_cData.title);
            }
        } catch (err) {

        }
    },
    showRightVideo: function(data, callback) {

        var _self = TextImageObj;

        if (_self.isVideo) {

            data['title'] = _self.jsonData.title;
            data['basePath'] = _self.jsonData.basePath;
            data['isScenarioBasedActivity'] = _self.jsonData.isScenarioBasedActivity;
            data['autoplay'] = true;

            try {
                var _vObj = _self.vObj;
                _vObj.isPopup = _self.jsonData['isPopup'] || false;
                setTimeout(function() {
                    _vObj.updateVideo(data, callback);
                }, 300);

            } catch (err) {
                console.log('showRightVideo:	', err)
            }
            try {
                if (_vObj.isPopup) {
                    var _popupData = {
                        title: data['title'],
                        content: $("#rightVideo-container")
                    }
                    custumPopup.init(_popupData, function() {
                        custumPopup.open();
                        $('#CustomPopupCloseBtn').hide();
                    });
                }

            } catch (err) {
                console.log(err)
            }
        }
    },
    showLeftVideo: function(data, callback) {
        var _self = TextImageObj;
        if (_self.isVideo) {

            data['basePath'] = _self.jsonData.basePath;
            data['isPopup'] = _self.jsonData.isPopup;
            data['isScenarioBasedActivity'] = _self.jsonData.isScenarioBasedActivity;
            data['autoplay'] = true;

            console.log('showLeftVideo:	', data)

            try {
                var _vObj = _self.vObj;
                setTimeout(function() {
                    _vObj.updateVideo(data, callback);
                }, 300)
            } catch (err) {
                console.log('showLeftVideo:	', err)
            }
        }
    },
    showTextSection: function(sNo, data) {
        var _self = TextImageObj;
        var container = $("#textImageContainer #sectionHolder");
        try {
            var _imgs = data.image;
            var contentImage = new ImageMain($("#imageHolder"), _imgs.use_image_tag);
            var contentImage2 = new ImageMain($(".secondImg #imageHolder"), _imgs.use_image_tag)
            contentImage.setObject(_imgs);
            contentImage2.setObject(_imgs);
        } catch (err) {

        }

        try {
            var _imgRefArr = _self.imgRefArr
            _imgRefArr.push(contentImage);
            _imgRefArr.push(contentImage2);
        } catch (err) {

        }
        _self.eventMgr.addControlEventListener(document, StaticLibrary.ORIENTATION_CHANGE, _self.onOrientationChange);
        container.find("#contentHolder").html(data.content);
        NavigatorController.addEventsForDetailLink();
    },
    addEventsOnVideo: function() {

        var _self = TextImageObj;
        var _vObj = _self.vObj;
        var _vData = ''
        var _video = null;
        var _videoHandler = null;

        try {

            $(_vObj).off("videoCanPlay").on('videoCanPlay', function(e, obj) {

                $('#CustomPopupCloseBtn').hide();
                _videoHandler = obj
                _video = _videoHandler['video']
                _vData = _video['vData'];
                //  console.log(':videoCanPlay:	_vData:	', _vData)

                if ((_vData['autoPlay'] == "true") || (_vData['autoPlay'])) {
                    _vObj.videoCompleted = false;
                    _videoHandler.PlayPauseAnimation();
                    _videoHandler['cVideo'] = _vData;
                    _self.showPause();
                }

                if (_videoHandler['cVideo']['id'] == "leftVideo-container") {
                    try {
                        $(_vObj).videosync();
                    } catch (err) {}
                    $("#bottomNav_transcript").removeClass("disabled");
                }

            });

            $(_vObj).off("videoProgress").on('videoProgress', function(e, data) {
                _self.updateProgress(data);
            });

            $(_vObj).off("videoEnded").on('videoEnded', function(e) {
                var _isAutoClose = _vData['isAutoClose'] || "true"
                if (_isAutoClose == "true") {
                    _self.ended();
                } else {
                    var isControls = _vData['isControls'];
                    if (isControls == "false") {
                        $('video').removeAttr('controls')
                    }
                    _video.currentTime = _video.duration - 1;
                    _videoHandler.pause();
                }
            });
        } catch (err) {
            console.log('addEventsOnVideo:	', err)
        }
    },
    updateProgress: function(data) {
        var _self = TextImageObj;
        try {
            data['vObj'] = _self.vObj;
            // // console.log(data.cTime, data.tT);
        } catch (err) {
            // console.log(err)
        }
        try {
            _self.videoSync(data)
        } catch (err) {
            // console.log(err)
        }
    },
    ended: function() {
        var _self = TextImageObj;
        try {
            $('#CustomPopupCloseBtn').show();
            custumPopup.close();
            _self.showPlayPauseDisabled()
        } catch (err) {
            console.log(err)
        }

    },
    handleControl: function(state) {
        var _self = TextImageObj;
        if (state.obj == "popupOpen") {
            popupOpen = true;
        } else {
            popupOpen = false;
        }

    },
    destroy: function() {
        var _self = TextImageObj;
        try {
            custumPopup.close();
        } catch (err) {

        }
        if (_self.isVideo) {
            var _vObj = _self.vObj;
            _vObj.destroy()
        } else {

        }
        _self.eventMgr.removeControlEventListener(document, StaticLibrary.ON_PAGE_UNLOADED, _self.destroy);
        _self.eventMgr.removeControlEventListener(document, StaticLibrary.CONTROL_AUDIO_VIDEO_EVENT, _self.handleControl);
    },
    pageAudioHandler: function(currTime, totTime) {
        try {
            if ((parseInt(currTime) != 0) && (parseInt(totTime) != 0)) {
                if (parseInt(currTime) >= parseInt(totTime)) {

                };
            };
        } catch (err) {
            // console.log(err)
        }
    },
    showPause: function() {
        // console.log("showPause:")
        try {
            $("#navigatorPlayPauseBtn").next('span').html("Pause");
            $("#navigatorPlayPauseBtn").attr("title", "Pause");
            $("#bottomNav_pause").addClass("pause").removeClass("play").removeClass("disabled");
            // $(this).trigger('iconPause')
        } catch (err) {

        }

    },
    showPlay: function() {
        // console.log("showPlay:")
        try {
            $("#navigatorPlayPauseBtn").next('span').html("Play");
            $("#navigatorPlayPauseBtn").attr("title", "Play");
            $("#bottomNav_pause").addClass("play").removeClass("pause").removeClass("disabled");
            // $(this).trigger('iconPlay')
        } catch (err) {

        }

    },
    showPlayPauseDisabled: function() {
        try {
            $("#navigatorPlayPauseBtn").next('span').html("Play");
            $("#navigatorPlayPauseBtn").attr("title", "Play");
            $("#bottomNav_pause").addClass("play").removeClass("pause").addClass("disabled");
            $("#bottomNav_transcript").addClass("disabled")
                // $(this).trigger('iconPlayPauseDisable')
        } catch (err) {

        }
    },
    markPageComplete: function() {
        try {
            var _self = TextImageObj;
            var _vObj = _self.vObj;
            _self.activityCompleted = true;
            _vObj.videoCompleted = true;
            MainController.markCurrentPageComplete();
            MainController.showNextInstruction();
            _self.showPlayPauseDisabled();
            // console.log("TextImageController: markPageComplete:	")
        } catch (err) {
            // console.log(err)
        }
    },
    initTextSection: function(data, initTemplate) {
        var _self = TextImageObj;
        _self.initTemplate = (initTemplate == undefined) ? true : initTemplate;
        if (_self.initTemplate) {
            _self.init(data);
            _self.showSection(0);
        }
    },
    onOrientationChange: function() {
        let _self = TextImageObj
        let _imgRefArr = _self.imgRefArr
        for (let i = 0; i < _imgRefArr.length; i++) {
            if (_imgRefArr[i]) {
                _imgRefArr[i].onOrientaionChange();
            }
        }
    },
    showSection: function(sNo) {
        let _self = TextImageObj
        _self.showTextSection(sNo = 0, _self.jsonData);
        _self.updatePageTitle();
    },
    addAnimation: function(tn) {
        let _self = TextImageObj
        let _content = $("#content_" + tn) || null;
        if (_content.length < 1) {
            _content = $("#sectionHolder #contentHolder .mainCont");
        }
        try {
            _self.getChildrens(_content);
            //_self.getChildrens(_content);
        } catch (err) {

        }

    },
    getChildrens: function(ele) {
        let _self = TextImageObj
        try {
            var _childres = ele.children();
            $.each(_childres, function(i, el) {
                let _el = $(el)
                var _tagName = el.tagName;
                if ((_tagName.toLowerCase() != 'img')) {
                    _el.removeClass('timeLine fadeIn').addClass('timeLine');
                    setTimeout(function() {
                        _el.addClass('fadeIn');
                        _self.getChildrens(_el);
                    }, (i * 600));
                }
            })

        } catch (err) {
            console.error(" getChildrens:   ", err)
        }
    },
    videoSync: function(data) {
        var video = data['vObj'];
        video['cTime'] = data.cTime;
        this.ElementSync(video);
    },
    audioSync: function(data) {
        this.ElementSync(data);
    },
    ElementSync: function(data) {

        let nodes = data.nodes || data || [],
            lastTime = data.lastTime || -1,
            i = 0,
            time = parseFloat(data.cTime);
        if (nodes.length < 1) return;

        if (Math.abs(time - lastTime) < 0.1) {
            return;
        }

        // // console.log('ElementSync:   ', nodes);

        lastTime = time;

        for (i = 0; i < nodes.length; i += 1) {
            let _node = nodes[i];
            let _sTime = _node['sTime'];
            let _eTime = _node['eTime'];
            let _ele = $(_node['element']);
            let classIn = _node['classIn'] || 'fadeIn';
            let classOut = _node['classOut'] || 'fadeOut';

            //   // console.log(i, time, lastTime, _sTime, _eTime)

            if (!_ele.hasClass(classIn)) {
                if ((time >= _sTime) && (_eTime ? time < _eTime : true)) {
                    _ele.addClass(classIn);
                    _ele.removeClass(classOut);
                }
            } else if (_ele.hasClass(classIn)) {
                if ((time < _sTime) || (_eTime ? time >= _eTime : false)) {
                    _ele.removeClass(classIn);
                    _ele.addClass(classOut);
                }
            }
        }
    }
}