/**
 * 播放器模块
 * Date: 2014/06/23
 * Author: luxing@iflytek.com
 * @version 1.0
 * @module player
 */
define(function (require, exports) {
    require('./widget/gallery_play');
    require('./widget/history_play');
    require('./widget/flipcard_play');
    require('./widget/ppt_play.js');
    require('./widget/cneval_play.js');
    require('./widget/eneval_play.js');
    require('./widget/situ_play.js');
    require('./widget/video_play');
    require('./widget/audio_play');
    require('./widget/gif_play');
    require('./widget/spot_play');
    require('./widget/exercise_play.js');
    require('./widget/pickcard_play');
    require('./widget/matchcard_play');
    require("jqm");
    var Slide = require('../../../share/assert/js/slide');
    var path = require('../../../share/assert/js/path');
    var AppContext = require('../../../share/assert/js/appcontext').AppContext;
    var IOUtil, paintCanvas;
    if (RunningPlatform === AppContext.RunningPlatform.NodeWebkit) {
        IOUtil = require("../../../share/assert/js/ioutil_desktop.js").IOUtil;
        paintCanvas = require("./toolbarmgr").PaintCanvas;
    }
    if (RunningPlatform === AppContext.RunningPlatform.CEF) {
        IOUtil = require("../../../share/assert/js/ioutil_cef.js").IOUtil;
        paintCanvas = require("./toolbarmgr").PaintCanvas;
    }
    if (RunningPlatform === AppContext.RunningPlatform.Android) {
        IOUtil = require("../../../share/assert/js/ioutil_android.js").IOUtil;
    }
    if (RunningPlatform === AppContext.RunningPlatform.Web) {
        IOUtil = require("../../../share/assert/js/ioutil_web.js").IOUtil;
        paintCanvas = require("./toolbarmgr").PaintCanvas;
    }


    /**
     * 课件播放器
     * @constructor
     * 逐步加载方案进行测试
     * 加载优先级为 fabirc》背景、图片》文字、元素》widget
     */
    function SlidePlayer() {
        var _self = this;
        this._slideNum = 0;
        this._curPackagePath = "";
        this._curPageName = "";
        this._curSlidePageIndex = 0;
        this._originalWidth = 0;
        this._originalHeight = 0;
        this._manifestObj = null;
        this._mainContainerInfo = {position: {left: 0, top: 0, width: 0, height: 0}, innerSlide: null};
        this._isAnimating = false;
        this._isCreatingBlankSlide = false;
        this._pageTransformCSS = {};
        this._newBlankSlideIndex = 0;
        //所有slide的信息
        this._tempIndex = 0;
        this.slidesData = [];
        this.slidesArray = [];
        this._playTotal = 5;
        this._playLocation = [];
        this._isFirstLoad = true;

        /**
         * 初始化播放器，并加载slide------入口
         */
        this.initPlayer = function () {
            var def = $.Deferred();
            _self.getPackagePath().done(function () {
                _self.getPackageInfo().done(function (manifestObj) {
                    _self.initUI(manifestObj);
                    _self.loadSile();
                    _self.updatePageIndexFlag();
                    _self.initStrokeInfo();
                    setTimeout(function(){
                        _self.bindCommands();
                    },1000);
                    def.resolve();
                });
            });
            return def.promise();
        }

        /**
         * 获取package和page地址信息
         */
        this.getPackagePath = function () {
            var def = $.Deferred();
            //NodeWebkit、Cef、WEB环境下，是通过请求参数获取路径
            if (RunningPlatform !== AppContext.RunningPlatform.Android) {
                _self._curPackagePath = _self.getRequestArg("package");
                _self._curPageName = _self.getRequestArg("pname");
                //如果传了widget参数，则认为是单卡片播放模式
                if (_self.getRequestArg("widget")) {
                    _self._curWidgetPath = _self.getRequestArg("widget");
                    if (_self.getRequestArg("route")) {
                        AppContext.singleWidgetRouteAddress = decodeURIComponent(_self.getRequestArg("route"));
                    }
                    $("body").css("overflow", "auto");
                    IOUtil.readFile(_self._curWidgetPath + "/meta.json").done(function (widgetMetaJson) {
                        AppContext.singleWidgetPath = _self._curWidgetPath;
                        AppContext.isSingleWidgetPlayMode = true;
                        var widgetObj;
                        if (typeof widgetMetaJson === "string") {
                            widgetObj = JSON.parse(widgetMetaJson);
                        }
                        AppContext.singleWidgetType = widgetObj.cardtype;
                        def.resolve();
                    });
                } else {
                    def.resolve();
                }
            }

            //Andriod端是调接口获取到路径
            if (RunningPlatform === AppContext.RunningPlatform.Android) {
                androidSink.execute('com.iflytek.teachingMachine.mcv.slide.androidSink.Package', 'getPkgPath', "", false, function (errorInfo, packagePath) {
                    if (errorInfo) {
                        console.error(errorInfo);
                    }
                    _self._curPackagePath = packagePath;
                    def.resolve();
                });
            }

            return def.promise();
        }

        /**
         * 读取package和page信息
         * @returns {_manifestObj} 返回整个package的描述信息对象
         */
        this.getPackageInfo = function () {
            var def = $.Deferred();
            var packagePath = _self._curPackagePath;
            if (AppContext.isSingleWidgetPlayMode) {
                //单卡片播放模式下，构造个假数据返回
                var manifestObj = {"presentfmt": "1280:800", "slides": ["1.sco"]};
                _self._manifestObj = manifestObj;
                def.resolve(manifestObj);
            } else {
                var manifestPath;
                if (!packagePath) {
                    packagePath = AppContext.getCurSlidePackPath();
                }
                manifestPath = path.trimPosix(path.join(packagePath, "manifest.json"));
                AppContext.setCurSlidePackPath(packagePath, false);
                IOUtil.readFile(manifestPath).done(function (manifestJson) {
                    var manifestObj;
                    if (typeof manifestJson === "string") {
                        manifestObj = JSON.parse(manifestJson);
                    }
                    _self._slideNum = manifestObj.slides.length;
                    _self._manifestObj = manifestObj;
                    if (_self._curPageName) {
                        _self._curSlidePageIndex = manifestObj.slides.indexOf(_self._curPageName);
                    }
                    _self.getSlidesInfo(manifestObj.slides).done(function () {
                        def.resolve(manifestObj);
                    })
                });
            }

            return def.promise();
        };

        /**
         * 所有页的信息读到内存中/
         * 此处可能耗时很长
         */
        this.getSlidesInfo = function (slides) {
            var def = $.Deferred();
            var _path = path.join(_self._curPackagePath, 'slides');
            var _pages = slides.length - 1, _slides = slides;

            function readJson() {
                var _callee = arguments.callee;
                if (_pages >= 0) {
                    IOUtil.readFile(path.join(_path, _slides[_pages], 'slide.json')).done(function (manifestJson) {
                        _self.slidesData.splice(0, 0, manifestJson);
                        _pages--;
                        _callee();
                    })
                } else {
                    def.resolve();
                }
            }

            readJson();
            return def.promise();
        }

        /**
         * 加载slide
         */
        this.loadSile = function () {
            _loadSlideIntoContainer();
            function _loadSlideIntoContainer() {
                var callee = arguments.callee;
                if (_self._tempIndex >= _self._slideNum) {
                    _self.displayTurnPageAnimate();
                    return;
                }
                var _tempSlide = new Slide.Slide();
                var _tempCanvas = $("<canvas></canvas>");
                var _tempCanvasDiv = $("<div></div>");
                _tempCanvasDiv.css({'width': _self._mainContainerInfo.position.width, height: _self._mainContainerInfo.position.height});
                _tempCanvasDiv.append(_tempCanvas);
                _tempCanvasDiv.hide();
                _tempCanvas.css(_self._pageTransformCSS);
                $("#mainContainer").append(_tempCanvasDiv);
                _tempSlide.Name = _self._manifestObj.slides[_self._tempIndex];
                _tempCanvasDiv.attr("slideName", _tempSlide.Name);
                _tempSlide.parentContainerId = "mainContainer";
                _tempSlide.widgetArray = [];
                _tempSlide.widgetIsShow = false;
                _tempSlide._canvasJson = _self.slidesData[_self._tempIndex];
                _tempSlide._container = _tempCanvasDiv;
                var _tempPlayCanvas = new fabric.Canvas(_tempCanvas[0], {width: _self._originalWidth, height: _self._originalHeight});
                _tempPlayCanvas.selection = false;
                _tempSlide.init(_tempPlayCanvas, false).done(function () {
                    if (_self._tempIndex == _self._curSlidePageIndex) {
                        _tempSlide.loadWidgets();
                    }
                    _self.slidesArray.push(_tempSlide);
                    _self._playLocation.push(0);
                    _self._tempIndex++;
                    callee();
                });
            }
        };

        /**
         * 翻到下一页
         */
        this.nextPage = function () {
            if(_self._isAnimating){
                return;
            }
            if (_self._curSlidePageIndex < _self._slideNum - 1) {
                _self.stopMedia();
                if (RunningPlatform === AppContext.RunningPlatform.Android) {
                    _self._curSlidePageIndex++;
                    if(!_self._isCreatingBlankSlide){
                        window.commInterface.setCurrentPage(_self._curSlidePageIndex+1, _self._slideNum);
                    }
                } else {
                    _self.saveStrokeCanvas();
                    _self.clearPenCanvas();
                    _self._curSlidePageIndex++;
                    _self.updatePageIndexFlag();
                }
                //_containerClearWidget(_self._curSlidePageIndex, 1)
                var _curSlide = _self.slidesArray[_self._curSlidePageIndex];
                _self._curPageName = _curSlide.Name;
                _self.displayTurnPageAnimate();
            } else {
                if (RunningPlatform === AppContext.RunningPlatform.Android) {
                    window.commInterface.setIsLastPage();
                }
            }
        };

        /**
         * 翻到上一页
         */
        this.prePage = function () {
            if(_self._isAnimating){
                return;
            }
            if (_self._curSlidePageIndex > 0) {
                _self.stopMedia();
                if (RunningPlatform === AppContext.RunningPlatform.Android) {
                    _self._curSlidePageIndex--;
                    window.commInterface.setCurrentPage(_self._curSlidePageIndex+1, _self._slideNum);
                } else {
                    _self.saveStrokeCanvas();
                    _self.clearPenCanvas();
                    _self._curSlidePageIndex--;
                    _self.updatePageIndexFlag();
                }
                //_containerClearWidget(_self._curSlidePageIndex, 0)
                _self._curPageName = _self.slidesArray[_self._curSlidePageIndex].Name;
                _self.displayTurnPageAnimate();
            } else {
                if (RunningPlatform === AppContext.RunningPlatform.Android) {
                    window.commInterface.setIsFirstPage();
                }
            }
        };

        /**
         * 翻到特定某页
         * @param pageIndex
         * @returns {*}
         */
        this.turnToPage = function (pageIndex) {
            if (pageIndex >= 0 && pageIndex < _self._slideNum) {
                _self.stopMedia();
                _self._curSlidePageIndex = pageIndex;
                var _curSlide = _self.slidesArray[pageIndex];
                _self._curPageName = _curSlide.Name;
                _self.displayTurnPageAnimate();
                if (RunningPlatform === AppContext.RunningPlatform.Android) {
                    window.commInterface.setCurrentPage(_self._curSlidePageIndex+1, _self._slideNum);
                }
            }
        }

        /**
         * 执行翻页动画
         * @param {string} direction "next"||"pre"
         */
        this.displayTurnPageAnimate = function (direction) {
            _self._isAnimating = true;
            var _slides = $('#mainContainer>div[slidename]');
            var _left = GlobalStage._curSlidePageIndex * (_self._mainContainerInfo.position.width * -1);
            for (var i = 0; i < _slides.length; i++) {
                _slides[i].style.webkitTransform = 'translate3d(' + _left + 'px, 0, 0)';
            }
            if (_self._isFirstLoad) {
                _slides.show();
                _slides.addClass("animations-n");
                _self.containerMoveEnd();
                _self._isFirstLoad = false;
            }
        }

        /**
         * 初始化界面UI
         * @param {object} manifestObj 整个package的描述信息对象
         */
        this.initUI = function (manifestObj) {
            //根据原始大小进行页面缩放
            var presentfmtStr = manifestObj.presentfmt;
            var originalWidth = parseInt(presentfmtStr.split(":")[0]);
            var originalHeight = parseInt(presentfmtStr.split(":")[1]);
            _self._originalWidth = originalWidth;
            _self._originalHeight = originalHeight;
            _self._containerWidth = 0;
            _self._containerHeight = 0;
            AppContext.containerOffset.width = originalWidth;
            AppContext.containerOffset.height = originalHeight;

            var bodyWidth = $(window).width();
            var bodyHeight = $(window).height();
            console.log(bodyWidth, bodyHeight);
            var screenRate = bodyWidth / bodyHeight;
            var containerHeight = 0, containerWidth = 0, main_containerLeft = 0, main_containerTop = 0;
            //屏幕宽高比例大于16:10，说明高度不足，则自适应高度，否则自适应宽度
            if (screenRate >= 1.6) {
                containerHeight = bodyHeight;
                containerWidth = bodyHeight * 1.6;
                main_containerLeft = (bodyWidth - containerWidth) / 2;
                $("#mainContainer").css("left", main_containerLeft);
                //左右两侧的背景区域
                $("#wrapperLeft").css({"width": main_containerLeft, "height": bodyHeight});
                $("#wrapperRight").css({"left": main_containerLeft + containerWidth, "width": main_containerLeft, "height": bodyHeight});
            } else {
                containerWidth = bodyWidth;
                containerHeight = bodyWidth / 1.6;
                main_containerTop = (bodyHeight - containerHeight) / 2;
                $("#mainContainer").css("top", main_containerTop);
                //上下两侧的背景区域
                $("#wrapperTop").css({"width": bodyWidth, "height": main_containerTop});
                $("#wrapperBottom").css({"top": main_containerTop + containerHeight, "width": bodyWidth, "height": main_containerTop});
            }
            if (RunningPlatform === AppContext.RunningPlatform.Android) {
                containerWidth = bodyWidth;
                containerHeight = bodyHeight;
                main_containerLeft = 0;
            }
            if (AppContext.isSingleWidgetPlayMode === true) {
                containerWidth = "1000";
                containerHeight = "620";
            }
            $("#mainContainer").css("height", containerHeight);
            $("#mainContainer").css("width", containerWidth);
            _self._mainContainerInfo.position = {left: main_containerLeft, top: main_containerTop, width: containerWidth, height: containerHeight};

            if (RunningPlatform === AppContext.RunningPlatform.Android || AppContext.isSingleWidgetPlayMode === true) {
                $("#wrapperLeft").css({"width": "0px", "height": "0px"});
                $("#wrapperRight").css({"width": "0px", "height": "0px"});
                $("#wrapperTop").css({"width": "0px", "height": "0px"});
                $("#wrapperBottom").css({"width": "0px", "height": "0px"});
                $("#mainContainer").css("left", 0);
            }
            else {
                //下方工具栏位置
                if (RunningPlatform === AppContext.RunningPlatform.Web) {
                    $("#toolBar").children().hide();
                    $("#btnPrePage").show();
                    $("#pageDes").show();
                    $("#btnNextPage").show();
                }
                $("#toolBar").css({"right": main_containerLeft, "bottom": main_containerTop, "display": "block"});
            }

            var zoomX = containerWidth / originalWidth;
            var zoomY = containerHeight / originalHeight;
            AppContext.zoomRate.x = AppContext.isSingleWidgetPlayMode ? 1 : zoomX;
            AppContext.zoomRate.y = AppContext.isSingleWidgetPlayMode ? 1 : zoomY;
            var translateX = -originalWidth * (1 - zoomX) / 2;
            var translateY = -originalHeight * (1 - zoomY) / 2;
            _self._pageTransformCSS = {
                'transform': 'matrix(' + zoomX + ',0,0,' + zoomY + ',' + translateX + ' ,' + translateY + ')',
                '-moz-transform': 'matrix(' + zoomX + ',0,0,' + zoomY + ',' + translateX + ' ,' + translateY + ')',
                '-webkit-transform': 'matrix(' + zoomX + ',0,0,' + zoomY + ',' + translateX + ' ,' + translateY + ')'
            };
        }

        /**
         * 初始化底部工具栏
         */
        this.initToolBar = function () {
            paintCanvas.init();
        }

        /**
         * 初始化页面笔迹信息
         */
        this.initStrokeInfo = function () {
            //填充每页的笔迹信息
            for (var i = 0; i < _self._slideNum; i++) {
                AppContext.strokeBase64Arr.push(null);
            }
        }

        /**
         * 清空笔记canvas
         */
        this.clearPenCanvas = function () {
            paintCanvas.clearCanvas();
        }

        /**
         * 保存当前页面笔迹
         */
        this.saveStrokeCanvas = function () {
            var curPageCanvasData = paintCanvas.getStrokeCanvasDataUrl();
            AppContext.strokeBase64Arr[_self._curSlidePageIndex] = curPageCanvasData;
            console.log(AppContext.strokeBase64Arr);
        }

        /**
         * 加载页面笔迹
         */
        this.loadStrokeCanvas = function () {
            var def = $.Deferred();
            var curPageCanvasData = AppContext.strokeBase64Arr[_self._curSlidePageIndex];
            var needChangeToPenMode = _strStartWith(_self._manifestObj.slides[_self._curSlidePageIndex], "newBlank");
            paintCanvas.loadStrokeCanvasFromDataUrl(curPageCanvasData, needChangeToPenMode).done(function(){
                def.resolve();
            });
            function _strStartWith(fullStr, startStr) {
                if (startStr == null || startStr == "" || fullStr.length == 0 || startStr.length > fullStr.length)
                    return false;
                if (fullStr.substr(0, startStr.length) == startStr)
                    return true;
                else
                    return false;
            }
            return def.promise();
        }

        /**
         * 在当前页后面新建一个空白页面
         * @param imgUrl {url} 参数为背景图片地址
         */
        this.createNewBlankSlide = function (imgUrl) {
            if(_self._isCreatingBlankSlide){
                return;
            }
            _self._isCreatingBlankSlide = true;
            AppContext.isCurNewBlankSlide = true;
            var _blankSlide = new Slide.Slide();
            var _blankCanvas = $("<canvas></canvas>");
            var _blankCanvasDiv = $("<div class='animations-n'></div>");
            _blankCanvasDiv.css('width', _self._mainContainerInfo.position.width);
            _blankCanvasDiv.append(_blankCanvas);
            var curSlideDiv = $("#mainContainer").find("div[slideName='" + _self._manifestObj.slides[_self._curSlidePageIndex] + "']");
            _blankCanvasDiv[0].style.WebkitTransform = curSlideDiv[0].style.WebkitTransform;
            curSlideDiv.after(_blankCanvasDiv);
            _blankSlide.Name = "newBlank" + (_self._newBlankSlideIndex + 1) + ".sco";
            _blankCanvasDiv.attr("slideName", _blankSlide.Name);
            _blankSlide.parentContainerId = "mainContainer";
            _blankSlide.widgetArray = [];
            _blankSlide.widgetIsShow = false;
            _self.getVirtualSlideJson(imgUrl).done(function(jsonStr){
                _blankSlide._canvasJson = jsonStr;
                _blankSlide._container = _blankCanvasDiv;
                var _blankPlayCanvas = new fabric.Canvas(_blankCanvas[0], {width: _self._mainContainerInfo.position.width, height: _self._mainContainerInfo.position.height});
                _blankPlayCanvas.selection = false;
                _blankSlide.init(_blankPlayCanvas, false).done(function () {
                    //重新构造页面结构信息
                    _self._slideNum++;
                    _self._newBlankSlideIndex++;
                    AppContext.strokeBase64Arr.splice(_self._curSlidePageIndex + 1, 0,null);
                    _self.slidesArray.splice(_self._curSlidePageIndex + 1, 0,_blankSlide);
                    _self._manifestObj.slides.splice(_self._curSlidePageIndex + 1, 0, "newBlank" + _self._newBlankSlideIndex + ".sco");

                    //向右翻页
                    _self.nextPage();
                });
            });

        }

        /**
         *  新建页时构造假slide的json数据
         * @param imgUrl
         */
        this.getVirtualSlideJson = function(imgUrl){
            var def = $.Deferred();
            if (imgUrl) {
                var tempImg = new Image();
                tempImg.src = imgUrl;
                $("body").append(tempImg);
                tempImg.onload = function(){
                    $(tempImg).css("visibility","hidden");
                    var tempImgWidth = $(tempImg).width();
                    var tempImgHeight = $(tempImg).height();
                    var backImgWidth,backImgHeight;
                    //计算一下图片的宽高比，宽高比大于屏幕的，则自适应宽度
                    var imgRate = tempImgWidth/tempImgHeight;
                    var containerRate = _self._mainContainerInfo.position.width/_self._mainContainerInfo.position.height;
                    if(imgRate>=containerRate){
                        backImgWidth = tempImgWidth < _self._mainContainerInfo.position.width ? tempImgWidth : _self._mainContainerInfo.position.width;
                        backImgHeight = backImgWidth/imgRate;
                    }
                    //宽高比小于屏幕的，则自适应高度
                    if(imgRate<containerRate){
                        backImgHeight = tempImgHeight < _self._mainContainerInfo.position.height ? tempImgHeight : _self._mainContainerInfo.position.height;
                        backImgWidth = backImgHeight*imgRate;
                    }

                    $(tempImg).css({height:backImgHeight,width:backImgWidth});
                    var backImgTop = (_self._mainContainerInfo.position.height-backImgHeight)/2;
                    var backImgLeft = (_self._mainContainerInfo.position.width-backImgWidth)/2;
                    $(tempImg).remove();
                    def.resolve('{"canvas":{"objects":[],"background":null,"backgroundImage":{"type":"image","originX":"left","originY":"top","left":'+backImgLeft+',"top":'+backImgTop+',"width":'+backImgWidth+',"height":'+backImgHeight+',"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","src":"'+imgUrl+'","filters":[],"crossOrigin":""}},"rels":[],"animationInfo":[],"presentfmt":"1280:800"}');
                }
            } else {
                def.resolve('{"canvas":{"objects":[],"background":"white"},"rels":[],"animationInfo":[],"presentfmt":"1280:800"}');
            }
            return def.promise();
        }

        /**
         * 新增带背景的新建页
         * @param imgUrl {url} 背景图片地址
         */
        this.addImage = function (imgUrl) {
            _self.createNewBlankSlide(imgUrl);
        }

        /**
         * 获取页面参数
         * @param arg {string} 页面参数
         */
        this.getRequestArg = function (arg) {
            var uri = decodeURI(window.location.search);
            var reg = new RegExp("" + arg + "=([^&?]*)", "ig");
            return ((uri.match(reg)) ? (uri.match(reg)[0].substr(arg.length + 1)) : null);
        }

        /**
         * 停止页面媒体播放
         */
        this.stopMedia = function () {
            //音频
            var mainAudios = $("#mainContainer").find("audio");
            for (var i = 0; i < mainAudios.length; i++) {
                mainAudios[i].pause();
            }
            //视频
            var mainVideos = $("#mainContainer").find("video");
            for (var i = 0; i < mainVideos.length; i++) {
                mainVideos[i].pause();
            }

            var leftAudios = $("#leftContainer").find("audio");
            for (var i = 0; i < leftAudios.length; i++) {
                leftAudios[i].pause();
            }
            var leftVideos = $("#leftContainer").find("video");
            for (var i = 0; i < leftVideos.length; i++) {
                leftVideos[i].pause();
            }

            var rightAudios = $("#rightContainer").find("audio");
            for (var i = 0; i < rightAudios.length; i++) {
                rightAudios[i].pause();
            }
            var rightVideos = $("#rightContainer").find("video");
            for (var i = 0; i < rightVideos.length; i++) {
                rightVideos[i].pause();
            }
            //Flash
            var mainFlashes = $("#mainContainer").find("embed");
            for (var i = 0; i < mainFlashes.length; i++) {
                $(mainFlashes[i]).hide();
            }

            var leftFlashes = $("#mainContainer").find("embed");
            for (var i = 0; i < leftFlashes.length; i++) {
                $(leftFlashes[i]).hide();
            }

            var rightFlashes = $("#mainContainer").find("embed");
            for (var i = 0; i < rightFlashes.length; i++) {
                $(rightFlashes[i]).hide();
            }

            //评测卡片
            var curPageEvalIframe = $($('#mainContainer>div[slidename]')[_self._curSlidePageIndex]).find("iframe[id*=cardFrm]");
            if (curPageEvalIframe.length > 0) {
                var wordStopBtn = $(curPageEvalIframe[0].contentWindow.document.body).find(".word_stop");
                wordStopBtn.click();
                var situStopBtn = $(curPageEvalIframe[0].contentWindow.document.body).find("#dialogue-read-text");
                if (situStopBtn.text() === "停止朗读") {
                    situStopBtn.click();
                }
            }

            //把热区清除掉
            $("#spot_play_box").remove();
        }

        /**
         * 更新页码显示信息
         */
        this.updatePageIndexFlag = function () {
            var pageIndex = _self._curSlidePageIndex + 1;
            $("#pageDes")[0].innerHTML = pageIndex + " / " + _self._slideNum;
        }

        /**
         * 事件绑定
         */
        this.bindCommands = function () {
            window.CloseGUIWindow = function () {
                var gui = window.require('nw.gui');
                var win = gui.Window.get();
                win.close();
            }
            $('#mainContainer>div[slidename]')[0].addEventListener('webkitTransitionEnd', _self.containerMoveEnd, false);

            window.turnPage = function (direction) {
                if (direction === "pre") {
                    _self.prePage();
                }
                if (direction === "next") {
                    _self.nextPage();
                }
            }

            window.turnToPage = function (pageIndex) {
                _self.turnToPage(pageIndex - 1);
            }

            if (RunningPlatform !== AppContext.RunningPlatform.Android) {
                //新建空白页
                $("#btnNewBlankSlide").click(function () {
                    _self.createNewBlankSlide();
                });

                //添加一页带背景的空白页----在PC端测试Android端效果，真正PC上没有此功能
                //$("#btnNewBlankSlide").click(function(){
                //    _self.addImage("C:/Users/luxing/Pictures/壁纸20141202114026.jpg");
                //});

                //前后翻页按钮
                $("#btnPrePage").bind("vclick", function () {
                    _self.prePage();
                });

                $("#btnNextPage").bind("vclick", function () {
                    _self.nextPage();
                });

                //PC绑定点击事件
                $("#btnClose").bind("vclick", function () {
                    if (RunningPlatform === AppContext.RunningPlatform.NodeWebkit) {
                        CloseGUIWindow();
                    } else {
                        console.error('you need impl close method!');
                    }
                });

                //快捷键支持
                KeyboardJS.on('right', function () {
                    _self.nextPage();
                });
                KeyboardJS.on('down', function () {
                    _self.nextPage();
                });

                KeyboardJS.on('left', function () {
                    _self.prePage();
                });
                KeyboardJS.on('up', function () {
                    _self.prePage();
                });

                KeyboardJS.on('esc', function () {
                    CloseGUIWindow();
                });

                //禁用右键
                $(document).bind("contextmenu", function (e) {
                    return false;
                });
                //禁用flash的右键
                $(document).bind("mousedown", function (e) {
                    if (e.button === 2 && e.target.id === "example_video_1") {
                        e.preventDefault();
                    }
                });

                if (RunningPlatform === AppContext.RunningPlatform.NodeWebkit) {
                    $('html').keyup(function (e) {
                        if (e.keyCode == 123) {
                            var gui = window.require('nw.gui');
                            var win = gui.Window.get();
                            win.showDevTools();
                        }
                    });

                    //捕获全局异常信息
                    process.on('uncaughtException', function (err) {
                        console.error(err.stack);
                        alert('Caught exception: ' + err);
                    });
                }

            }


            if (window.RunningPlatform === AppContext.RunningPlatform.Android) {
                //防止flash在pad端响应两次点击事件，老的Android4.2板子上有此bug，新板子上没有
//            $(document).bind("vclick", function (e) {
//                if (e.target.id === "example_video_1") {
//                    //console.log("you click flash");
//                    e.preventDefault();
//                }
//            });

                window.stopMedia = function () {
                    _self.stopMedia();
                };

                window.createNewSlide = function () {
                    _self.createNewBlankSlide();
                }

                window.addImage = function (imgUrl) {
                    console.log(imgUrl);
                    _self.addImage(imgUrl);
                }
            }
        }

        /**
         * 翻页动画结束回调
         */
        this.containerMoveEnd = function() {
            var _curindex = GlobalStage._curSlidePageIndex
            var _total = Math.floor(GlobalStage._playTotal / 2);
            var _max = (_curindex + _total) > GlobalStage.slidesArray.length - 1 ? GlobalStage.slidesArray.length - 1 : (_curindex + _total);
            var _min = parseInt(_curindex - _total) <= 0 ? 0 : parseInt(_curindex - _total);
            
            for (var i = _min; i <= _max; i++) {
                GlobalStage._playLocation[i] = 1;
                var _curSlide = GlobalStage.slidesArray[i];
                if (!_curSlide.widgetIsShow)
                    _curSlide.loadWidgets();
            }
            var _tarSlide = $('#mainContainer');
            _tarSlide.css('overflow', 'hidden');
            console.log("move end !!!");
            var _slides = $('#mainContainer>div[slidename]');
            if ($(_slides[_curindex]).find("iframe[id*=cardFrm]").length > 0) {
                iframeID = $(_slides[_curindex]).find("iframe[id*=cardFrm]")[0].id;
                console.log(iframeID);
            }
            if (RunningPlatform != AppContext.RunningPlatform.Android) {
				
                //给flash后面加上loading动画
                var mainFlashes = $(_slides[_curindex]).find("embed");
                for (var i = 0; i < mainFlashes.length; i++) {
                    $(mainFlashes[i]).show();
                    $(mainFlashes[i]).parent().addClass("flash-loader");
                }
                setTimeout(function () {
                    $("#mainContainer").find(".flash-loader").removeClass("flash-loader");
                }, 10 * 1000);
                if (!AppContext.isSingleWidgetPlayMode) {
                    paintCanvas.changeToMouseMode();
                    GlobalStage.loadStrokeCanvas().done(function(){
                        GlobalStage._isAnimating = false;
                        GlobalStage._isCreatingBlankSlide = false;
                    });
                }
            }else{
                GlobalStage._isAnimating = false;
                GlobalStage._isCreatingBlankSlide = false;
				window.commInterface.setCurrentPage(_self._curSlidePageIndex+1, _self._slideNum);
            }
        }
    }




    //删除widget
    function _containerClearWidget(_index, _dri) {
        var _curindex = _index;
        var _location = GlobalStage._playLocation;
        var _total = Math.floor(GlobalStage._playTotal / 2);
        var _tarSlide = $('#mainContainer');
        _tarSlide.css('overflow', 'initial');
        if (_dri) {
            for (var i = 0; i < _location.length; i++) {
                if (_location[i] == 1) {
                    if (i < _curindex - _total) {
                        GlobalStage._playLocation[i] = 0;
                        GlobalStage.slidesArray[i].clearWidget();
                    }
                }

            }
        } else {
            for (var i = _location.length - 1; i >= 0; i--) {
                if (_location[i] == 1) {
                    if (i > _curindex + _total) {
                        GlobalStage._playLocation[i] = 0;
                        GlobalStage.slidesArray[i].clearWidget();
                    }
                }
            }
        }


    }


    //播放器入口
    $(function () {
        var player = window.GlobalStage = new SlidePlayer();
        player.initPlayer().done(function () {
            if (RunningPlatform !== AppContext.RunningPlatform.Android) {
                if (!AppContext.isSingleWidgetPlayMode && RunningPlatform != AppContext.RunningPlatform.Android) {
                    player.initToolBar();
                }
            }
        });
    });
});