define(function (require, exports) {

    var S = require('../../../share/assert/js/slide');
    var AppContext = require('../../../share/assert/js/appcontext').AppContext;
    var P = require('editor/assert/js/pagethumb').PagesThumb;
    var idgen = require('../../../share/assert/js/idgen');
    var commands = require('editor/assert/js/utils/commands').commands;
    window.commands = commands;
    var IO = require('share/assert/js/ioutil_desktop').IOUtil;
    var paths = require('../../../share/assert/js/path');
    var userSvc = require('../../../share/assert/js/usersvc').userSvc;
    var userLogin = require('editor/assert/js/plugins/table/dialogs/userlogin/userlogindlg').userLoginDlg;
    var upload = require('editor/assert/js/plugins/table/dialogs/upload/uploaddlg').uploadDlg;
    var pptConverter = window.require('documentconverter/AddonDocumentConverter');
    var updateCheck = require('editor/assert/js/addon/updateCheck');
    var urlCheck = require('editor/assert/js/addon/urlCheck');
    var appUtil = require('editor/assert/js/addon/appUtil');
    var FS = window.require('fs');
    var LM = require('editor/assert/js/addon/logManager').LogManager;
    var gui = window.require('nw.gui');


//    var exec = window.require('child_process').exec;

//    var WdtType = require('../../../share/assert/js/widgettype');
    var myScroll = null;


    function init() {
        //重置一些设置
        Global.saveToPath = null;
        Global.isEditing = false;
        Global.isVariety = false;
        Global.isVarietyType = 0;
        Global.DefaultBackground = {src: null, color: null, repeat: false, use: false};
//        $('#background_use_all')[0].checked = false;
        //---------换页
        EventBase.addListener('ClickThumb', function (e,opts) {
            Global.curSelStatus = "slides";
            Global.CurrentSlide.t.content.removeClass('current2');
            if(Global.CurrentSlide.t == arguments[1].e && opts.type == 'sel' && Global.selSlides.length <= 1) return;
            if (Global.CurrentSlide.t == arguments[1].e && Global.KeyLists[0] != 17 && (opts ? false : Global.selSlides.length <= 1)) return;
            if (Global.AppState.init.value || Global.AppState.inputPPT.value) return;
            if (opts.e.content[0].id === Global.CurrentSlide.t.content[0].id && (opts ? false : Global.selSlides.length <= 1)) return;
            //saveSlide();
            if (Global.KeyLists[0] == 17 && !arguments[2]) {
                commands.addSelSlides(arguments[1].e) || updateSelectPage(arguments[1].e, true);
            } else {
                Global.selSlides = [];
                if (!arguments[2]) {
                    commands.saveCtrlPath('selPage');
                }
                Global.isVarietyType = Global.isVariety;
                updateStage(arguments[1].e, 2, arguments[3]);
            }
//            Global.CurrentSlide.t.content.removeClass('current2');
            showThumbScroll();
        });
        EventBase.addListener('winClose', function () {
            var win = gui.Window.get();
            win.maximize();
            if (!Global.isEditing && !Global.isVariety && !Global.isAdded) {
                commands.showSelectorPop(commands.getErrorMsg(2008), function (isext) {
                    commands.hidePop();
                    if (isext && isext != 'close') {
                        setTimeout(commands.closeWindow, 200);
                        IO.rmdir(AppContext.getCurSlidePackPath());
                    }
                }, 30000, this);
            } else {
                commands.showSelectorPop(commands.getErrorMsg(2003), null, null, this, [
                    {
                        label: '保存',
                        cssClass: 'btn-primary',
                        action: function () {
                            selectSaveFile(true)
                            //BootstrapDialog && BootstrapDialog.closeAll();
                        }
                    },
                    {
                        label: '不保存',
                        action: function () {
                            selectSaveFile(false);
                            commands.hidePop();
                            //BootstrapDialog && BootstrapDialog.closeAll();
                        }
                    },
                    {
                        label: '取消',
                        action: function () {
                            commands.hidePop();
                        }
                    }
                ]);
            }

            function selectSaveFile(isSave) {
                commands.hidePop();
                if (!isSave) {
                    setTimeout(commands.closeWindow, 500);
                    //IO.rmdir(AppContext.getCurSlidePackPath());
                } else {
                    commands.setAppState('close', [true, true]);
                    $('#btn_save')[0].click();
                }
            }
        });
        eventlisters();
        commands.usePropertyCtrlArea(null);
        //------------修改一下自适应
//        scaleStage();
        commands.resetUndoBtn();

        // -------------------- 课件崩溃 自恢复
        if (paths.extname(gui.App.argv[1]) == '.dat') {//自恢复的启动参数.自动保存的配置文件以.dat为后缀
            // 读取autosave.dat 配置文件
            var asfObj = JSON.parse(FS.readFileSync(gui.App.argv[1]));
            var packageDir = paths.dirname(gui.App.argv[1]);
            var manifestPath = AppContext.joinPath(packageDir, 'manifest.json');

            Global.PackagePath = AppContext.setCurSlidePackPath(packageDir);
            $('#saveAsPackage').attr('nwsaveas', asfObj.packageName.split('.')[0]);
            $('#fileName_title').text(asfObj.packageName.split('.')[0] + ' - 畅言课件制作工具');
            getFileData(manifestPath);
        } else { // 正常启动
            // 读取所有的autosave.dat配置信息
            var autoSaveinfo = commands.getAutoSaveInfo();
            console.log(autoSaveinfo);


            // 有可恢复课件 并且是第一次启动 -- 处理自动恢复
//            if (autoSaveinfo.length > 0 && gui.App.argv[0] === 'true') {
//                dealWithBackup(autoSaveinfo); // 处理自恢复
//            }

            // 没有可恢复课件 并且为第一次启动 -- 清空缓存
            if (autoSaveinfo.length == 0 && gui.App.argv[0] === 'true') {
                IO.rmdir(AppContext.getTmpPackPath());
            }

            // 处理启动参数
            dealWithArgs();
        }

        /*myScroll && myScroll.destroy();
         myScroll = null;
         myScroll = new IScroll('#page_thumb_list', {
         scrollbars: true,
         mouseWheel: false,
         interactiveScrollbars: true,
         shrinkScrollbars: 'scale',
         fadeScrollbars: false
         });*/
    }

    function dealWithBackup(info) {
        if ($('#modal_content_backup')) {
            $('#modal_content_backup').remove();
        }

        var dlg = $('<div id="modal_content_backup" class="modal fade in" tabindex="-1" role="dialog"' +
            'style="padding-top: 15%; overflow-x: hidden; display: block;" aria-hidden="false">' +
            '<div class="pop_warp pop_tips">' +
            '<div class="pop_tit"><span class="fl">课件恢复</span>' +
            '<div class="w_func fr" id="btnBackUpClose"><a href="javascript:;" title="关闭" class="w_func_close" data-dismiss="modal"></a>' +
            '</div>' +
            '</div>' +
            '<div class="pop_con"><p class="pop_tips_con" >' + '是否恢复上次异常关闭的课件？' + '</p></div>' +
            '<div class="pop_btn_box t_center" id="pop_btns_box">' +
            '<a href="javascript:void(0)" class="pop_btn" id="btnBackUpConfirm"><span>恢复</span></a>' +
            '<a href="javascript:void(0)" class="pop_btn" id="btnBackUpCancel"><span>取消</span></a>' +
            '</div>' +
            '</div>' +
            '</div>'
        );

        $('body').append(dlg);

        dlg.find('#btnBackUpClose').bind('click', function () {
            dlg.remove();
        });

        dlg.find('#btnBackUpConfirm').bind('click', function () {
            dlg.remove();
            appUtil.executeAppWithArgs("..\\..\\iFlySlide.exe", info[0].autoSaveFile);
        });

        dlg.find('#btnBackUpCancel').bind('click', function () {
            dlg.remove();
            IO.rmdir(AppContext.joinPath(AppContext.getTmpPackPath(), info[0].packageName)).done(function () {
            });
        });
    }

    function dealWithArgs() {

        var _psrc = QueryUrlString('package');

        if (gui.App.argv.length > 1) {
            var _name = commands.getFileNameToUrl(gui.App.argv[1]);
            var _path = AppContext.joinPath(AppContext.getTmpPackPath(), _name);
            IO.exists(_path).done(function (_is) {
                if (_is) {
                    IO.rmdir(_path).done(function () {
                        openPackage(gui.App.argv[1])
                    });
                } else {
                    openPackage(gui.App.argv[1])
                }
            });
        } else if (_psrc) {
            openPackage(AppContext.joinPath(AppContext.getDefaultTemplate(), decodeURI(_psrc)));
            Global.saveToPath = null;
        } else {
            //创建一个新的文件夹/包
            var _dir = AppContext.joinPath(AppContext.getTmpPackPath(), commands.randomString(5));
            IO.mkdirp(_dir).done(function (bol) {
                if (bol) {
                    AppContext.setCurSlidePackPath(_dir);
                    resizeStage();
                    createPages();
                } else {
                    commands.showPop(commands.getErrorMsg(2001), 2000);
                }
            });
        }
        $("#pageArea_list").dragsort({dragStartCall:function(_tar){
            if(!_tar) return;
            Global.selSlides = [];
//            console.log(_tar);
//            console.log(_tar.id);
//            console.log(_tar.nodeName);
            if(_tar.nodeName === "SPAN" || _tar.nodeName === "A"){
                _tar = _tar.parentElement;
            }
            var thumeb = _tar.id.split('_')[0];
            thumeb = commands.searchSlideById(thumeb);
            thumeb && updateSelectPage(thumeb.t)
            try{
                updateStage(thumeb.t,2)
            }catch (err)
            {
                throw  err;
            }

        }, dragSelector: "li", dragBetween: true, dragEnd: pageSortEnd, placeHolderTemplate: "<li></li>" });
    }

    //舞台区域缩放。
    function resizeStage(opt) {
        if (!opt) opt = {};
        $('#edit_wrapper').css('height', window.outerHeight<500?window.screen.availHeight:window.outerHeight);
        var _tar = $('#stageArea');
        var _w = _tar[0].clientWidth, _h = _tar[0].clientHeight;
        //22为滚动条的宽
        //1.6是为是控制为16:10

        //todo 固定分辨率

       /* DEFAULT_STAGE.cheight = (_h - 22);
        DEFAULT_STAGE.cwidth = (Math.floor(DEFAULT_STAGE.cheight * 1.6));
        DEFAULT_STAGE.height = opt.height || DEFAULT_STAGE.cheight;
        DEFAULT_STAGE.width = opt.width || DEFAULT_STAGE.cwidth;
        Global.PackageJson.presentfmt = DEFAULT_STAGE.width + ":" + DEFAULT_STAGE.height;
        //计算出当前屏幕较合适的尺寸
        if (DEFAULT_STAGE.width > _w) {
            *//*setTimeout(function(){
             DEFAULT_STAGE.scale = ($('#stageArea')[0].clientWidth/DEFAULT_STAGE.width-0.1).toFixed(1);
             DEFAULT_STAGE.scale = (DEFAULT_STAGE.scale * 10 - 1) / 10;
             $('#scale_ctrl_bar')[0].value = Math.floor(DEFAULT_STAGE.scale * 10);
             scaleStage();
             },3000);*//*
//            DEFAULT_STAGE.width = Math.floor(_w / 10) * 10;
//            DEFAULT_STAGE.height = DEFAULT_STAGE.width / 1.6;
        }*/
        if(DEFAULT_STAGE.width>_w*0.9 || DEFAULT_STAGE.height>_h*0.9)
        {
            var _xx = 1-(((DEFAULT_STAGE.width-_w)+DEFAULT_STAGE.width*0.1)/DEFAULT_STAGE.width).toFixed(1);
            var _yy = 1-(((DEFAULT_STAGE.height-_h)+DEFAULT_STAGE.height*0.1)/DEFAULT_STAGE.height).toFixed(1);
            DEFAULT_STAGE.scale = Math.min(_xx,_yy)
//            DEFAULT_STAGE.scale = Number(1-(DEFAULT_STAGE.scale/DEFAULT_STAGE.width).toFixed(1));
        }else
        {
            DEFAULT_STAGE.scale = 0.9;
        }
//        DEFAULT_STAGE.left = Math.floor((_w - DEFAULT_STAGE.width) * 0.5);
//        _tar.css('padding-top', Math.floor((_h - DEFAULT_STAGE.height) * 0.5))
    }

    /**
     * 舞台区域缩放
     */
    function scaleStage() {
        var _stage = $('#stage_m_c');
        $('#stageArea').css('overflow','hidden')
        var _w = _stage.width();
        var _h = _stage.height();
        var _maxw = $('#stageArea')[0].clientWidth;
        var _maxy = $('#stageArea')[0].clientHeight;

        _stage.css('-webkit-transform', 'scale(' + DEFAULT_STAGE.scale + ')');
        var _bingrect = _stage[0].getBoundingClientRect();

        var _left = (_maxw - _bingrect.width);
        var _top = (_maxy - _bingrect.height);

        //if (DEFAULT_STAGE.scale < 1) {
//            _stage.css('position', 'relative');
           // _stage.css('left', 0)
            //_stage.css('top', 0)


            if(_left>0){
                DEFAULT_STAGE.left = Math.abs(_left) * 0.5;
                _stage.css('left', Math.abs(_left) * 0.5);
            }else
            {
                DEFAULT_STAGE.left = 0;
                _stage.css('left', 0)
            }
            if(_top>0){
                DEFAULT_STAGE.top = Math.abs(_top) * 0.5;
                _stage.css('top', Math.abs(_top) * 0.5);
            }else
            {
                DEFAULT_STAGE.top = 0;
                _stage.css('top', 0)
            }
            if(_maxw>_bingrect.width)
            {
                $('#stageArea').scrollLeft(0);
            }else
            {
                $('#stageArea').scrollLeft(Math.abs(_left) * 0.5);
            }
            if(_maxy>_bingrect.height)
            {
                $('#stageArea').scrollTop(0);
            }else
            {
                $('#stageArea').scrollTop(Math.abs(_top) * 0.5);
            }


        /*} else {
            _stage.css('left', (_maxw - _w)*0.5);
            _stage.css('top', (_maxy - _h)*0.5);
        }*/
        $('#scale_value_text').text(Math.floor(DEFAULT_STAGE.scale * 100) + "%");

        if(_bingrect.width<_maxw && _bingrect.height<_maxy)
        {
            $('#stageArea').css('overflow','hidden')
        }else
        {
            $('#stageArea').css('overflow','scroll')
        }
        $('#scale_ctrl_bar')[0].value = Math.floor(DEFAULT_STAGE.scale * 10);
    }

    /**
     * 创建已经有的页
     */
    function createPages() {
        $('#canvas_object_style_toolbar').show();

        Global.PackageJson.ver = AppCfg.ICWVersion;
        if (Global.PackageJson.slides.length > 0) {
            for (var i = 0; i < Global.PackageJson.slides.length; i++) {
                addPages(Global.PackageJson.slides[i]);
            }
        } else {
            addPages(null);
            updateStage(0, 1);
            setTimeout(function(){
                $('#page_waiting').hide();
            },3000);
        }
        showThumbScroll();
    }

    /**
     * 添加对象到slide中
     */
    function addElement() {

        for (var i in arguments[0]) {
            if (i == 'src') {
                var _img = new Image();
                _img.src = arguments[0][i];
                this.setElement(_img);
            }
        }
        Global.isVariety = true;
        Global.CurrentSlide.c.add(this, arguments[0]);
        /*setTimeout(function () {

            IO.writeFile(Global.CurrentSlide.c.getCurJsonPath(), Global.CurrentSlide.c.toJSON());
        }, 50)*/
        setTimeout(function () {
            commands.showThumbImg(Global.CurrentSlide.c._canvas);
            Global.CurrentSlide.c.renderAll();
            commands.saveCtrlPath('object');
        }, 150)
    }

    /**
     * 更新当前stage
     * @param tar
     * @param type 1创建，2选择，3跳转,5排序更新
     */
    function updateStage(tar, type, ppt) {
        var def = jQuery.Deferred();
        //清空回撤键队列
        Global.KeyLists = [];

        //显示状态创建中
        if(!ppt){
            commands.setAppState('init', true);
        }
//        DEFAULT_STAGE.scale = 1;
        $('#scale_ctrl_bar')[0].value = 10;
        $('#scale_value_text').text((DEFAULT_STAGE.scale * 100) + '%');
        updateSortNumber();
        if((type == 1 || type == 3) && (!Global.CurrentSlide || Global.CurrentSlide.t.content.attr("class") != "current")){
            updateSelectPage(tar, false, true);
        }
        else{
            updateSelectPage(tar);
        }
        if (Global.CurrentSlide && !ppt) {
            var a = Global.CurrentSlide.c.getActiveObject();
            a && a.hideEditButton();
        }
        commands.usePropertyCtrlArea(null, false);

        if (Global.CurrentSlide && !ppt && Global.isVariety) {
            saveSlide(function(){
                //Global.isVariety = false;
                Global.CurrentSlide.c._canvas.dispose();
                Global.CurrentSlide = null;
                updateAction()
            });
        }else
        {
            updateAction()
        }
        function updateAction()
        {
            $('#stageArea').html('');
            clearGlobalDefind();
            for (var i = 0; i < Global.SlideArray.length; i++) {
                if (i == tar || Global.SlideArray[i].t == tar) {

                    Global.CurrentSlide = Global.SlideArray[i];
                    Global.CurrentSlide.c.createStage($('#stageArea'), commands.randomString(10), function (e) {
                        scaleStage();
                        if(type==2){
							Global.isVariety = false;
						}
                        if (ppt && type!=2) {
                            var _t = null;
                            var _img = new Image();
                            _img.src = ppt;
                            _img.onload = function () {
                                var _scale = commands.setObjSizeForStage(this);
                                _t = new fabric.Img(_img, {left: 0, top: 0, width: DEFAULT_STAGE.width, height: DEFAULT_STAGE.height});
                                _t.id = commands.randomString(10);
                                setTimeout(function () {
                                    _t.showEditDialog(AppContext.joinPath(Global.CurrentSlide.c.getCurMediaPath(), _t.id), addElement);
                                }, 150)
                            }
                        }
                        if (Global.DefaultBackground.use && !ppt && (type == 1 || type == 4)) {
                            if (Global.DefaultBackground.src) {
                                Global.isVariety = true;
                                IO.exists(Global.DefaultBackground.src).done(function (_is) {
                                    if (_is) {
                                        copyImgToFolder(Global.DefaultBackground.src, function (_to) {
                                            Global.CurrentSlide.c.setBackgroundImage(_to, Global.DefaultBackground.repeat);
                                            setTimeout(function () {
                                                commands.showThumbImg(Global.CurrentSlide.c._canvas).done(function () {
                                                    commands.resetAppState();
                                                    Global.CurrentSlide.c.renderAll();
                                                    def.resolve();
                                                });
                                            }, 200)
                                        })
                                    } else {
                                        Global.DefaultBackground.use = false;
                                        Global.DefaultBackground.src = null;
//                                    $('#background_use_all')[0].checked = false;
                                        setTimeout(function () {
                                            commands.showThumbImg(Global.CurrentSlide.c._canvas).done(function () {
                                                commands.resetAppState();
                                                def.resolve();
                                            });
                                        }, 50)
                                    }
                                })
                            } else if (Global.DefaultBackground.color) {
                                Global.isVariety = true;
                                if (typeof(Global.DefaultBackground.color) === 'string') {
                                    Global.CurrentSlide.c._canvas.backgroundImage = null;
                                    Global.CurrentSlide.c._canvas.setBackgroundColor(Global.DefaultBackground.color);
                                    Global.CurrentSlide.c.renderAll();
                                } else {
                                    Global.DefaultBackground.use = false;
                                    Global.DefaultBackground.src = null;
//                                    $('#background_use_all')[0].checked = false;
                                    setTimeout(function () {
                                        commands.showThumbImg(Global.CurrentSlide.c._canvas).done(function () {
                                            commands.resetAppState();
                                            def.resolve();
                                        });
                                    }, 50)
                                }
                            }
                        }
                        if (type == 1) {
                            //创建文件夹
                            //setTimeout(function () {
                                 //IO.mkdirp(Global.CurrentSlide.c.getCurMediaPath()).done(function (bol) {
                                 IO.writeFile(Global.CurrentSlide.c.getCurJsonPath(), Global.CurrentSlide.c.toJSON());
                                 //});
                                // IO.writeFile(AppContext.getPackageJsonPath(), JSON.stringify(Global.PackageJson));
                             //}, 50)
                        } else if (type == 5) {
                            Global.isVariety = true;
                        }
                        if ((!ppt && !Global.DefaultBackground.src)  || !Global.DefaultBackground.use || type != 1) {
                            /*commands.resetAppState();
                            def.resolve();
                            return;*/
                            setTimeout(function () {
                                commands.showThumbImg(Global.CurrentSlide.c._canvas).done(function () {
                                    commands.resetAppState();
                                    def.resolve();
                                });
                            }, 50)
                        }
                        Global.curStageJson = Global.CurrentSlide.c.toJSON();
                    });
                    break;
                }
            }
        }

        return def.promise();
    }

    /**
     * 添加一页
     */
    function addPages(_id, callback) {
        if (Global.AppState.init.value) return;
        commands.closeToolsPop();
        var _name = !_id ? idgen.SlideIdGen.newId() : _id;
        var slide = new S.Slide();
        slide.Name = _name;
        //slide.background = _bg;
        slide.setFmt(Global.PackageJson.presentfmt);
        slide.isFile = _id ? true : false;
        if (_id) slide.LoadId(_id);
        var _pt = new P();
        _pt.create(_name + '_Thumb');
        var _index = 0;
        if (!_id) {
            if (Global.CurrentSlide) {
                _pt.add(Global.CurrentSlide.t.content, 2);
                updateSortNumber();
                _index = commands.getCurSlideIndex(Global.PackageJson.slides);
            } else {
                _pt.add($('#pageArea_list'), 1);
            }
            _index=_index + 1;
            Global.SlideArray.splice(_index, 0, {c: slide, t: _pt});
            if (Global.PackageJson.slides.length<=0){
                if(!_id) Global.PackageJson.slides.splice(_index, 0, _name);
            }
            var _plist = $('#page_thumb_list');
            _plist.scrollTop(_plist.scrollTop() + 151);
            commands.saveCtrlPath('addPage',{Name:slide.Name});
        } else {
            _pt.add($('#pageArea_list'), 1);

            Global.SlideArray.push({c: slide, t: _pt});
            if (!_id) Global.PackageJson.slides.push(_name);
        }

        if (!_id) IO.writeFileSync(AppContext.getPackageJsonPath(), JSON.stringify(Global.PackageJson));
//        var _slidePath = AppContext.joinPath(AppContext.getPackageJsonPath(),slides,slide.Name,'slide.json');
        if (_id) commands.showThumbImg(null, slide.getCurThumbPath(), _pt);
        //检查media目录是否存在
        IO.exists(slide.getCurMediaPath()).done(function (_is) {
            if (!_is) {
                IO.mkdirp(slide.getCurMediaPath()).done(function (e) {
                    if (!e) {
                        commands.showPop(commands.getErrorMsg(2001), 2000);
                    } else {
                        callback && callback(_index,1);
                    }
                })
            }
        });
        return _name;
    }

    Global.addPages = addPages;

    /**
     * 重新排序缩略图
     */
    function updateSortNumber() {
        var _thmlist = $('#pageArea_list>li');
        if (_thmlist.length < 1) return;
        Global.PackageJson.slides = [];
        for (var i = 0, d = _thmlist.length; i < d; i++) {
            var _thm = $($('#pageArea_list>li')[i]).find('span');
            _thm.text(i + 1);
            Global.PackageJson.slides.push($('#pageArea_list>li')[i].id.split('_')[0]);
        }

        updateSlideArray()
    }

    /**
     * 重排后更新slideArray的排序
     */
    function updateSlideArray() {
        var _cl = [];

        for (var t = 0; t < Global.PackageJson.slides.length; t++) {
            for (var c = 0; c < Global.SlideArray.length; c++) {
                if (Global.SlideArray[c].c.Name === Global.PackageJson.slides[t]) {
                    _cl.push(Global.SlideArray[c]);
                    Global.SlideArray.splice(c, 1);
                    break;
                }
            }
        }
        Global.SlideArray = _cl;
        _cl = null;
    }

    function uploadPackage(callback) {
        var _upload = new upload();
        //if (userSvc.uuid == "") {
            var _t = new userLogin();
            _t.showDialog(function () {
                _upload.showDialog(callback);
            });
        //}
        //else {
        //    _upload.showDialog(callback);
        //}
    }

    //添加事件
    function eventlisters() {
        var _that = this;
        $('body').on('keyup', function (e) {
            if (Global.CurrentSlide || !Global.isEditing) {
                if (Global.AppState.init.value || Global.AppState.inputPPT.value) return;
                commands.pushKeyCode(e.keyCode, 2);
                if ((e.keyCode == 46 || e.keyCode == 90 ) && (e.target.nodeName == 'TEXTAREA' || e.target.type == 'text')) {
                    //return false;
                }
                else if(e.keyCode == 46 && Global.curSelStatus == "slides"){
                        deleteSelectedSlides();
                }
                else{
                    commands.fireKeyEvent(e.keyCode);
                }
            }
        });

        $('#btnWindowHelp').on('click', function (e) {
            IO.shellexecute('"' + AppContext.joinPath(process.env.SystemRoot, 'hh.exe') + '" "' + AppContext.joinPath(AppContext.getBinPath(), 'help.chm') + '"')
        });

        document.body.addEventListener("mousedown",function(e){
            if(e.which === 3 && !((e.target.nodeName == "LI" && e.target.parentElement.parentElement.id == "contextMenu")
                ||(e.target.nodeName == "A" && e.target.parentElement.parentElement.parentElement.id == "contextMenu")
                ||(e.target.nodeName == "I" && e.target.parentElement.parentElement.parentElement.parentElement.id == "contextMenu"))){
                $("#contextMenu").hide();
            }
            if((e.target.nodeName == "LI" && e.target.parentElement.id == "pageArea_list")
                ||(e.target.nodeName == "A" && e.target.parentElement.parentElement.id == "pageArea_list")
                ||(e.target.nodeName == "IMG" && e.target.parentElement.parentElement.parentElement.id == "pageArea_list")){
                commands.resetDeleteBtn(true);
                Global.curSelStatus = "slides";
            }
            else if((e.target.nodeName == "UL" && e.target.id == "pageArea_list")
                || (e.target.nodeName == "DIV" && e.target.id == "page_thumb_list" && $('#page_thumb_list').css('overflow-y') === 'hidden')
                || (e.target.nodeName == "DIV" && e.target.id == "page_thumb_items")
                || (e.target.nodeName == "DIV" && e.target.id == "stage_m_r")
                || (e.target.nodeName == "DIV" && e.target.id == "stage_m_l")
                || (e.target.nodeName == "DIV" && e.target.id == "stageArea")
                || (e.target.nodeName == "CANVAS")){
                commands.resetDeleteBtn(false);
                commands.resetExportBtn(false);
                if(Global.CurrentSlide){
                    $('#pageArea_list>li').removeClass("current current2");
                    Global.CurrentSlide.t.content.addClass("current current2");
                }
                Global.curSelStatus = null;
                Global.selSlides = [];
            }
            else if(e.target.nodeName == "A" && e.target.parentElement.nodeName == "BODY"){   //点击编辑按钮时选中状态取消
                commands.resetDeleteBtn(false);
                commands.resetExportBtn(false);
                Global.curSelStatus = null;
            }
        },true);

        $('body').on('keydown', function (e) {
            //console.log(e.target.nodeName);
            if (e.keyCode === 8 && e.target.nodeName != 'TEXTAREA' && e.target.type != 'text' && e.target.type != 'password') {
                e.returnValue = false;
                return false;
            }
            if (Global.AppState.init.value || Global.AppState.inputPPT.value) {
                e.returnValue = false;
                return false;
            }
            commands.pushKeyCode(e.keyCode, 1);

//            console.log(e.keyCode,e.ctrlKey);
            if (e.ctrlKey) {
                switch (e.keyCode) {
                    case 88:    //剪切，如果当前是多选，则不响应剪切
                        var activeGroup = Global.CurrentSlide.c._canvas.getActiveGroup();
                        if (!activeGroup && e.target.type != "textarea" && e.target.type != "text") {
                            if (Global.curSelStatus === "widget") {
                                var newObj={};
                                newObj = fabric.util.object.extend(newObj, Global.CurrentSlide.c.activeObject);
                                AppContext.rightClicked = {type: "widget", slideName: Global.CurrentSlide.c.Name, obj: newObj};
                                AppContext.pasteTimes=0;
                            }
                            $("#rightBtnCut").click();
                        }
//                        else{
//                            var curSelectedText = window.getSelection().toString();
//                            if(curSelectedText.length>0){
//                                AppContext.rightClicked = {type: "text", slideName: Global.CurrentSlide.c.Name, obj: {text: curSelectedText}};
//                            }
//                        }
                        break;
                    case 67:    //复制，如果当前是多选，则不响应复制
                        var activeGroup = Global.CurrentSlide.c._canvas.getActiveGroup();
                        if (!activeGroup && e.target.type != "textarea" && e.target.type != "text") {
                            if (Global.curSelStatus === "widget") {
                                var newObj = Global.CurrentSlide.c.activeObject;
                                AppContext.rightClicked = {type: "widget", slideName: Global.CurrentSlide.c.Name, obj: newObj};
                            }
                            if (Global.curSelStatus === "slides") {
                                AppContext.rightClicked = {type: "slide", slideName: Global.CurrentSlide.c.Name, obj: {slideName: Global.CurrentSlide.Name}};
                            }
                            AppContext.oldAnimationInfo = Global.CurrentSlide.c.getAnimationInfo(AppContext.rightClicked.obj.id);
                            AppContext.selectedCopyTarget = AppContext.rightClicked;
                            AppContext.pasteTimes=0;
                        }
//                        else{
//                            var curSelectedText = window.getSelection().toString();
//                            if(curSelectedText.length>0){
//                                AppContext.rightClicked = {type: "text", slideName: Global.CurrentSlide.c.Name, obj: {text: curSelectedText}};
//                            }
//                        }
//                        AppContext.selectedCopyTarget = AppContext.rightClicked;
//                        AppContext.pasteTimes=0;
                        break;
                    case 86:    //粘贴，如果当前是多选，则不响应粘贴，否则会出bug
                        var activeGroup = Global.CurrentSlide.c._canvas.getActiveGroup();
                        if (!activeGroup) {
//                            console.log("paste");
                            if (e.target.type != "textarea" && e.target.type != "text") {
                                $("#rightBtnPaste").click();
                            }
                        }
                        break;
                }
            }
            else if(e.keyCode === 33 || e.keyCode === 38){  //上一页
                var _index = commands.getCurSlideIndex(Global.PackageJson.slides, Global.CurrentSlide.c.Name);
                if(_index == 0) return;
                Global.selSlides = [];
                commands.saveCtrlPath('selPage');
                Global.isVarietyType = Global.isVariety;
                updateStage(_index - 1, 3);
            }
            else if(e.keyCode === 34 || e.keyCode === 40){  //下一页
                var _index = commands.getCurSlideIndex(Global.PackageJson.slides, Global.CurrentSlide.c.Name);
                if(_index == Global.PackageJson.slides.length - 1)  return;
                Global.selSlides = [];
                commands.saveCtrlPath('selPage');
                Global.isVarietyType = Global.isVariety;
                updateStage(_index + 1, 3);
            }
        });

        $('body').click(function (e) {
            $("#contextMenu").hide();
        });

        $("#rightBtnCopy").click(function () {
            console.log("copy");
            if (AppContext.rightClicked.obj) {
                AppContext.selectedCopyTarget = AppContext.rightClicked;
                AppContext.oldAnimationInfo = Global.CurrentSlide.c.getAnimationInfo(AppContext.rightClicked.obj.id);
                AppContext.pasteTimes=0;
            }
        });

        $("#rightBtnCut").click(function () {
            console.log("cut");
            if (AppContext.rightClicked.obj) {
                Global.isVariety = true;
                AppContext.selectedCopyTarget = AppContext.rightClicked;
                AppContext.oldAnimationInfo = Global.CurrentSlide.c.getAnimationInfo(AppContext.rightClicked.obj.id);
                Global.CurrentSlide.c.getActiveObject().remove();
                Global.CurrentSlide.c.renderAll();
                AppContext.pasteTimes=0;
            }
        });

        $("#rightBtnPaste").click(function () {
            console.log("paste");
            Global.isVariety = true;
            if (AppContext.selectedCopyTarget && AppContext.selectedCopyTarget.type === "widget") {
                var oldObj = AppContext.selectedCopyTarget.obj;
                var newObj = {};
                if (oldObj.type === "TextField") {
                    newObj = new fabric.TextField(oldObj.text,JSON.parse(JSON.stringify(oldObj)));
                }else{
                    newObj = fabric.util.object.extend(newObj, oldObj);
                }
                //console.log(oldObj, newObj);

                newObj.left += 20*(AppContext.pasteTimes+1);
                newObj.top += 20*(AppContext.pasteTimes+1);
                //换id
                newObj.id = Global.CurrentSlide.c._WIdGen.newId(newObj.type);
                //重新定向relInfo和拷贝文件
                if (oldObj.rinfo) {
                    //widget复制
                    var oldObjRinfoSrc = AppContext.getCurSlidePackPath() + "/slides/" + AppContext.selectedCopyTarget.slideName + "/"
                        + oldObj.rinfo.src.replace(/.*?sco\//ig, '');
                    newObj.rinfo = {des: "", id: "", src: "", title: "", type: "dir"};
                    var newRid = Global.CurrentSlide.c.NewRId();
                    newObj.rid = newRid;
                    newObj.rinfo.id = newRid;
                    var curSlidePath = Global.CurrentSlide.c.getCurSlidePath();

                    if(oldObj.type==="Audio" || oldObj.type ==="Video"){
                        //先拷贝缩略图
                        var oldObjFullThumbSrc = oldObj._element.src.replace("file:///","").replace(/(.+?)\?(.*)/g, "$1");
                        oldObjFullThumbSrc = decodeURI(oldObjFullThumbSrc);
                        var newObjRelatedThumbSrc = oldObjFullThumbSrc.replace(/.*?sco\//ig, '');
                        var newObjFullThumbSrc= curSlidePath +"/" + newObjRelatedThumbSrc;
                        //再拷贝资源
                        var oldObjRinfoRelatedSrc = oldObj.rinfo.src;
                        var newRinfoRelatedSrc = commands.changeFileName(oldObjRinfoRelatedSrc);
                        var oldObjRinfoSrc = oldObjFullThumbSrc.replace(/(.+?)media(.*)/g, "$1")+oldObjRinfoRelatedSrc;
                        var newRinfoSrc= curSlidePath + "/" + newRinfoRelatedSrc;
                        newObj.rinfo.src = newRinfoRelatedSrc;
                        IO.copyFileSync(oldObjFullThumbSrc, newObjFullThumbSrc);
                        IO.copyFileSync(oldObjRinfoSrc, newRinfoSrc);
                        Global.CurrentSlide.c.addRelationInfo(newObj.rinfo);
                        Global.CurrentSlide.c._canvas.add(newObj);
                        newObj.src =newObjRelatedThumbSrc;
                    }
                    else{
                        var newRinfoSrc,newObjRelatedThumbSrc,oldObjFullThumbSrc,newObjFullThumbSrc;
                        newRinfoSrc= curSlidePath + "/media/" + newObj.id;
                        oldObjFullThumbSrc = oldObj._element.src.replace("file:///","").replace(/(.+?)\?(.*)/g, "$1");
                        if(oldObj.type ==="Spot"){
                            //因为热区的缩略图不在资源文件夹内，所以还得单独拷贝缩略图
                            oldObjFullThumbSrc = decodeURI(oldObjFullThumbSrc);
                            newObjRelatedThumbSrc = oldObjFullThumbSrc.replace(/.*?sco\//ig, '');
                            newObjFullThumbSrc= curSlidePath +"/" + newObjRelatedThumbSrc;
                            IO.copyFileSync(oldObjFullThumbSrc, newObjFullThumbSrc);
                        }else{
                            newObjRelatedThumbSrc= "media/" + newObj.id + "/thumbnail.png";
                            newObjFullThumbSrc= curSlidePath +"/" + newObjRelatedThumbSrc;
                        }
                        newObj.rinfo.src = newRinfoSrc;
                        newObj.src = newObjFullThumbSrc;
                        IO.mkdir(newRinfoSrc).done(function () {
                            var fileList = IO.readFileList(oldObjRinfoSrc);
                            for (var i = 0; i < fileList.length; i++) {
                                var oldFilePath = oldObjRinfoSrc + "/" + fileList[i];
                                var newFilePath = newRinfoSrc + "/" + fileList[i];
                                IO.copyFileSync(oldFilePath, newFilePath);
                            }
                            var newImg = new Image();
                            newImg.src = newObjFullThumbSrc;
                            newObj._originalElement = newImg;
                            newObj._element = newImg;
                            Global.CurrentSlide.c.addRelationInfo(newObj.rinfo);
                            Global.CurrentSlide.c._canvas.add(newObj);
                            setTimeout(function(){
                                Global.CurrentSlide.c._canvas.renderAll();
                            },10);
                        });
                    }
                } else {
                    //非widget复制
                    //如果是图片或者文本，则需要把动画也同时复制
                    if(oldObj.type ==="Img" || oldObj.type ==="TextField" || oldObj.type ==="Graphica"){
                        if(oldObj.type ==="Img"){
                            var oldImgSrc = oldObj._element.src.replace("file:///","").replace(/(.+?)\?(.*)/g, "$1");
                            oldImgSrc = decodeURI(oldImgSrc);
                            var newImgRelatedSrc = oldImgSrc.replace(/.*?sco\//ig, '');
                            var curSlidePath = Global.CurrentSlide.c.getCurSlidePath();
                            var newImgFullSrc= curSlidePath +"/" + newImgRelatedSrc;
                            IO.copyFileSync(oldImgSrc, newImgFullSrc);
                        }
                        var oldAnimationInfo = AppContext.oldAnimationInfo;
                        if(oldAnimationInfo){
                            var newAnimationInfo=AppContext.clone(oldAnimationInfo);
                            newAnimationInfo.id=newObj.id;
                            Global.CurrentSlide.c.addAnimationInfo(newAnimationInfo);
                        }
                    }
                    Global.CurrentSlide.c._canvas.add(newObj);
                }
                setTimeout(function () {
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                }, 100);
                AppContext.pasteTimes++;
            }
            if (AppContext.selectedCopyTarget && AppContext.selectedCopyTarget.type === "slide") {
                //先创建一个空白页面
                var _curName = addPages();
                var _index = commands.getCurSlideIndex(Global.PackageJson.slides, _curName);
                updateStage(_index, 1).done(function () {
                    showThumbScroll();
                    Global.isVariety = true;
                    //然后拷贝页面内容
                    var oldSlidePath = AppContext.getCurSlidePackPath() + "/slides/" + AppContext.selectedCopyTarget.slideName;
                    var newSlidePath = AppContext.getCurSlidePackPath() + "/slides/" + Global.CurrentSlide.c.Name;
                    //console.log(oldSlidePath,newSlidePath);
                    IO.copyDir(oldSlidePath, newSlidePath).done(function(){
                        //根据json加载页面
                        var newSlideJsonPath = newSlidePath + "/slide.json";
                        var newSlideJsonStr = IO.readFileSync(newSlideJsonPath);
                        Global.CurrentSlide.c.loadFromJSON(newSlideJsonStr, function () {
                            setTimeout(function () {
                                commands.showThumbImg(Global.CurrentSlide.c._canvas);
                            }, 100);
                        });
                    });
                });
            }
//            if (AppContext.selectedCopyTarget && AppContext.selectedCopyTarget.type === "text") {
//                var iText = new fabric.TextField(AppContext.selectedCopyTarget.obj.text);
//                iText.left += 20*(AppContext.pasteTimes+1);
//                iText.top += 20*(AppContext.pasteTimes+1);
//                iText.id = Global.CurrentSlide.c._WIdGen.newId(iText.type);
//                Global.CurrentSlide.c._canvas.add(iText);
//                AppContext.pasteTimes++;
//            }
        });

        $("#rightBtnDelete").click(function () {
            doDelete();
        });

        function doDelete(){
            if (!Global.curSelStatus) {
                commands.resetDeleteBtn(false);
                commands.resetExportBtn(false);
                return;
            }
            else if (Global.curSelStatus == "slides") {
                deleteSelectedSlides();
            }
            else if (Global.curSelStatus == "widget") {
                if (Global.SlideArray.length < 1)return;
                if (Global.CurrentSlide.c.getActiveObject() || Global.CurrentSlide.c._canvas.getActiveGroup()) {
                    commands.fireKeyEvent(46);
                }
            }
        }

        //----------------head----------------
        //------------打开包
        EventBase.addListener('openFile', function () {
            commands.closeToolsPop();
            var _that = this;
            var url = arguments[1].value;
            commands.setAppState('open', url);
            if (Global.isVariety) {
                commands.showSelectorPop('是否保存正在编辑的课件！', function (_is) {
                    commands.hidePop();

                }, 30000, _that, [
                    {
                        label: '保存',
                        cssClass: 'btn-primary',
                        action: function () {

                            $('#btn_save').click();
                            //selectSaveFile(true)
                            //BootstrapDialog && BootstrapDialog.closeAll();
                        }
                    },
                    {
                        label: '不保存',
                        action: function () {
                            openPackage(url);
                            commands.hidePop();
                            //selectSaveFile(false)
                            //BootstrapDialog && BootstrapDialog.closeAll();
                        }
                    },
                    {
                        label: '取消',
                        action: function () {
                            commands.hidePop();
                        }
                    }
                ])
            } else {
                openPackage(url);
            }

            arguments[1].value = null;
            //这里要解压到一个目录
        });
        //-----------------更新slide
        EventBase.addListener('updateSlide',function(type,opt){
            updateStage(opt.index,5)
        })
        // 打开widget模板
        EventBase.addListener('openWidget', function () {
            var filePath = arguments[1].value;
            openWidget(filePath);
            arguments[1].value = null;
        });

        //保存课件
        $('#btn_save').on('click', function (e) {
            if (Global.SlideArray.length < 1)return;
            commands.closeToolsPop();
            saveSlide(function () {
                //保存到zip
                if (Global.saveToPath) {
                    copyPakcageThumb(function () {
                        commands.savePackage(AppContext.getCurSlidePackPath(), Global.saveToPath).done(function (o) {
                            commands.resetUndoBtn();
                            if (o == 0) {
                                commands.showPop('保存' + commands.getErrorMsg(o), 1000);
                            } else {
                                commands.showPop(commands.getErrorMsg(o), 1000);
                                return;
                            }
                            Global.isVariety = false;
                            if (Global.AppState.upload.value == true) {
                                Global.AppState.upload.value = false;
                                uploadPackage(function (httpCode) {
                                    commands.resetAppState();
                                });
                            }
                            if (Global.AppState.open.value) {

                                openPackage(Global.AppState.open.value);
                            }
                        });
                    });
                } else {
                    $('#saveAsPackage')[0].click();
                }
            });
        });
        //另存
        EventBase.addListener('saveAsPackage', function () {
            var url = arguments[1].files[0];
            if (!url || url.path.length < 5) return;
//            arguments[1].nwsaveas+='.icw';
            var _filename = url.path;

            copyPakcageThumb(function () {
                saveSlide(function () {
                    _filename && commands.savePackage(AppContext.getCurSlidePackPath(), _filename).done(function (o) {
                        //console.log('SaveEnd',o);
                        commands.resetUndoBtn();
                        if (o == 0) {
                            commands.showPop('保存' + commands.getErrorMsg(o), 1000);
                        } else {
                            commands.showPop(commands.getErrorMsg(o), 1000);
                            return;
                        }

                        Global.isVariety = false;
                        if (Global.AppState.upload.value == true) {
                            Global.AppState.upload.value = false;
                            uploadPackage(function (httpCode) {
                                commands.resetAppState();
                            });
                        }
                        if (Global.AppState.open.value) {
                            openPackage(Global.AppState.open.value);
                            return;
                        }
                        var _name = _filename.split('\\');
                        _name = _name[_name.length - 1];
                        $('#fileName_title').text(_name + ' - 畅言课件制作工具');
                    });
                })

            });
            arguments[1].value = null;
        });

        //删除一个对象
        $('#btn_delete').on('click', function (e) {
            if (!commands.checkDeleteBtn()) {
                return;
            }
            doDelete();
        });

        //撤销
        $('#btn_undo').on('click', function (e) {
            //if (Global.CurrentSlide.c.getActiveObject() || Global.CurrentSlide.c._canvas.getActiveGroup()) {
            Global.KeyLists = [17];
            commands.fireKeyEvent(90, true);

            //}
        });
        //----------------------function
        $('#btn_hdmb').on('click', function (e) {
            if (Global.SlideArray.length < 1)return;
            commands.closeToolsPop('hdmb_list_box');
        });

        //导出
        $('#rightBtnExport,#btn_export').on('click', function () {
            if($('#btn_export> img').attr('src').indexOf('_disable') > -1){
                return;
            }

            if (!Global.CurrentSlide.c._canvas.getActiveObject()) {
                commands.showPop(commands.getErrorMsg(3005), 2000);
                return;
            }

            var cardType = Global.CurrentSlide.c._canvas.getActiveObject().type.toLocaleLowerCase();
            var cardTypeWgtArr = ['history', 'flipcard', 'pickcard', 'matchcard', 'gallery', 'exercise', 'cneval', 'eneval', 'situdlg', 'ppt']; // 导出互动模板的对象
            var mediaTypeArr = ['audio', 'video']; // 导出媒体文件的对象
            var otherTypeArr = ['img', 'textfield', 'mathgraph', 'mathequation', 'graphica', 'gif']; // 导出为图片的对象
            var cardTypeName = {history: '时间轴', flipcard: '翻翻卡', pickcard: '分类题', matchcard: '连线题', gallery: '画廊',exercise: '测验', cneval: '中文字词评测卡片', eneval: '英文单词评测卡片', situdlg: '英文情景对话评测卡片', ppt: 'ppt画廊' };

            if (cardTypeWgtArr.indexOf(cardType) >= 0) {
                var activeObjectPath = commands.getCurrentActiveObjectPath();
                var options = {nwsaveas: cardTypeName[cardType] + "_" + (new Date()).Format("yyyyMMddhhmmssS") +".ict"};
                DialogUtil.saveFileDialog(options).done(function (url) {
                    if (!url || url.length < 5) return;
                    saveAsWgt(activeObjectPath, url);
                });
            } else if(mediaTypeArr.indexOf(cardType) >= 0){
                var activeObjectPath = commands.getCurrentActiveObjectPath();
                var newName = paths.extname(activeObjectPath);
                if (cardType === 'audio'){
                    newName = '音频_' + (new Date()).Format("yyyyMMddhhmmssS") + newName;
                } else {
                    newName = '视频_' + (new Date()).Format("yyyyMMddhhmmssS") + newName;
                }
                var options = {nwsaveas: newName};
                DialogUtil.saveFileDialog(options).done(function (url) {
                    if (!url || url.length < 5) return;
                    saveMediaFile (activeObjectPath, url);
                });
            } else if (otherTypeArr.indexOf(cardType) >= 0) {
                    if(cardType === 'img'){
                        var activeObjectPath = Global.CurrentSlide.c.getActiveObject()._element.src;
                        activeObjectPath = decodeURI(paths.trimPosix(activeObjectPath));
                        activeObjectPath = activeObjectPath.replace(/(.+?)\?(.*)/g, "$1");

                        var newName = paths.extname(activeObjectPath);
                        newName = '图片_' + (new Date()).Format("yyyyMMddhhmmssS") + newName;

                        var options = {nwsaveas: newName};
                        DialogUtil.saveFileDialog(options).done(function (url) {
                            if (!url || url.length < 5) return;
                            saveMediaFile (activeObjectPath, url);
                        });
                    }else if(cardType === 'gif'){
                        commands.getCurrentActiveGifPath().done(function (activeObjectPath) {
                            var newName = paths.extname(activeObjectPath);
                            newName = '图片_' + (new Date()).Format("yyyyMMddhhmmssS") + newName;
                            var options = {nwsaveas: newName};
                            DialogUtil.saveFileDialog(options).done(function (url) {
                                if (!url || url.length < 5) return;
                                saveMediaFile (activeObjectPath, url);
                            });
                        });
                    }else if (cardType === 'mathgraph' || cardType === 'mathequation') {
                        var activeObjectPath = commands.getCurrentActiveObjectPath();
                        var newName = '图片_' + (new Date()).Format("yyyyMMddhhmmssS") + '.png';
                        activeObjectPath = paths.join(activeObjectPath, 'thumbnail.png');
                        var options = {nwsaveas: newName};
                        DialogUtil.saveFileDialog(options).done(function (url) {
                            if (!url || url.length < 5) return;
                            saveMediaFile (activeObjectPath, url);
                        });
                    } else {
                        var newName = '图片_' + (new Date()).Format("yyyyMMddhhmmssS") + '.png';;
                        var options = {nwsaveas: newName};
                        DialogUtil.saveFileDialog(options).done(function (url) {
                            if (!url || url.length < 5) return;
                            IO.writeIMG(url, Global.CurrentSlide.c._canvas._activeObject.toDataURL('image/png')).done(function(err){
                                commands.showPop('导出' + commands.getErrorMsg(0), 1000);
                            });
                        });
                    }
            }else{
                commands.showPop(commands.getErrorMsg(3004), 2000);
            }
        });
        // 保存媒体文件
        function saveMediaFile (fromUrl, toUrl) {
            commands.showPop(commands.getErrorMsg(2));
            IO.copyFile(fromUrl, toUrl).done(function(rlt){
                if(rlt){
                    commands.hidePop();
                    commands.showPop('导出' + commands.getErrorMsg(0), 1000);
                }else{
                    commands.hidePop();
                    commands.showPop('导出失败，请重试！');
                }
            });
        }

        // 保存widget交互模板
        function saveAsWgt (fromUrl, toUrl) {
            commands.saveWidget(fromUrl, toUrl).done(function (o) {
                if (o == 0) {
                    commands.showPop('导出' + commands.getErrorMsg(o), 1000);
                    LM.statisticsMoudleTime('4105','trigger','widget_export_count');
                } else {
                    commands.showPop(commands.getErrorMsg(o), 1000);
                    return;
                }
            });
        };

        $('#btn_bubble').on('click', function (e) {
            if (Global.SlideArray.length < 1)return;
            commands.closeToolsPop('spot_list_box');
        });
        $('#spot_list_def_box').on('click', function (e) {
            if (Global.SlideArray.length < 1)return;
            var _id = $(e.target).attr('icon');
            if (!_id) return;
            commands.closeToolsPop('spot_list_box');
            commands.showPop(commands.getErrorMsg(2002));

            copyImgToFolder(AppContext.joinPath(AppContext.getDefaultImagePath(), _id + '.png'), function (o) {
                commands.hidePop();
                var _t = null;
                var _img = new Image();
                _img.src = o;
                _img.onload = function () {
                    var _scale = commands.setObjSizeForStage(this);
                    _t = new fabric.Spot(_img, {left: _img.width * 0.5, top: 100, width: this.width * 0.5, height: this.height * 0.5});
                    _t.id = Global.CurrentSlide.c.NewWId(_t.type);
                    _t.icon = (_id === 'pin4' ? 'pin4_a.png' : _id + '.gif');
                    Global.CurrentSlide.c.add(_t, {});
                    setTimeout(function () {
                        Global.CurrentSlide.c.renderAll();
                        IO.writeFile(Global.CurrentSlide.c.getCurJsonPath(), Global.CurrentSlide.c.toJSON());
                        _t.showEditDialog(null, null, true);
                        commands.showThumbImg(Global.CurrentSlide.c._canvas).done(function(){
                            commands.saveCtrlPath('object');
                        });
                        Global.isVariety = true;
                    }, 50)

                }
            });
        });
        /**
         * 导入PPT
         */
        EventBase.addListener('openPPT', function (e) {
            commands.closeToolsPop();
            var url = AppContext.joinPath(arguments[1].value);
            if (!commands.changeFilePathIsSpeailCharts(url)) {
                arguments[1].value = null;
                return;
            }
            if (!url || url.length < 5) return;
            var _ext = commands.getExtName(url)[0];
            var _type = commands.changeFileExtType(_ext);
            if (_type != 'ppt') {
                commands.showPop(commands.getErrorMsg(3003), 1000);
                arguments[1].value = null;
                return;
            }

            var appPath = process.cwd();
            var modulePath = paths.join(appPath, "node_modules", "documentconverter");

            commands.setAppState('inputPPT', true);
            Global.CurrentSlide.c && Global.CurrentSlide.c._canvas.discardActiveObject();
            saveSlide(function () {
                console.log(url, AppContext.getTmpPackPath());

                var isCancel = false;
                var popContent = "<div id='pptConverting' style='text-align: center; width:100%; height: 50px; font-family: microsoft yahei; font-size: 16px; color: #898989'>" +
                    "<img src='editor/assert/images/page-loader.gif' style='margin-left: auto; margin-right: auto; margin-top: -10px; height: 30px; width:30px;'/><p>" +
                    commands.getErrorMsg(2011) + "</p></div>";
                commands.showSelectorPop(popContent, null, null, _that, [
                    {
                        label: '取消',
                        cssClass: 'btn-primary',
                        action: function () {
                            isCancel = true;
                            commands.resetAppState();
                            commands.hidePop();
                        }
                    }
                ], true)

                pptConverter.document2Image(url, AppContext.getTmpPackPath(), 'slide_bg_', modulePath, function (errMsg, errCode, num) {
                    //todo 先用定时器
                    if (errCode != 0) {
                        commands.resetAppState();
                        commands.hidePop();
                        commands.showPop(commands.getErrorMsg(errCode));
                        if (errCode == 10) {
                            $('#pptNetLink').find("a").click(function () {
                                gui.Shell.openExternal("http://www.microsoft.com/zh-cn/download/details.aspx?id=17718");
                            });
                        }
                        return;
                    }
                    var _cn = 1;
                    setTimeout(function () {
                        if (isCancel) {
                            return;
                        }
                        var _url = 'slide_bg_' + _cn + '.png';
                        _url = AppContext.joinPath(AppContext.getTmpPackPath(), _url);
                        var _callee = arguments.callee;
                        var _curName = addPages(null, function () {
                            var _index = commands.getCurSlideIndex(Global.PackageJson.slides, _curName);
                            var _tosrc = commands.changeFolderToMedia(_url, Global.SlideArray[_index].c.getCurMediaPath());
                            IO.copyFile(_url, _tosrc).done(function () {
                                commands.showThumbImg(null, _tosrc, Global.SlideArray[_index].t);
                                updateStage(_index, 1, _tosrc);
                                saveSlide(function () {
                                    if (++_cn <= num) {
                                        setTimeout(_callee, 800);
                                    } else {
                                        commands.hidePop();
                                        upzipres();
                                        commands.resetAppState();
                                    }
                                }, true)
                            })

                        });
                        showThumbScroll();
                    }, 500);

                    function upzipres() {
                        if (_ext === '.pptx') {
                            var _dir = url.split('/');
                            var _fname = _dir[_dir.length - 1];
                            _fname = _fname.split('.')[0];
                            var _desktop2 = AppContext.joinPath('桌面', _fname)
                            var _desktop = AppContext.joinPath(appUtil.getDesktopDir(), _fname)
                            IO.unZipPPT(AppContext.joinPath(url), _desktop).done(function (e) {
                                if (e) {
                                    setTimeout(function () {
                                        commands.showSelectorPop(commands.getErrorMsg(2012) + _desktop2 + '  查看！', null, null, null, [
                                            {
                                                label: '确定',
                                                cssClass: 'btn-primary',
                                                action: function () {
                                                    commands.hidePop();
                                                }
                                            }
                                        ])
                                        //commands.showPop(commands.getErrorMsg(2012)+AppContext.getBinPath(),1000);
                                    }, 200)
                                }
                            });
                        } else {
                            commands.showSelectorPop(commands.getErrorMsg(2013), null, null, null, [
                                {
                                    label: '确定',
                                    cssClass: 'btn-primary',
                                    action: function () {
                                        commands.hidePop();
                                    }
                                }
                            ]);
                        }
                    }
                })
            }, true)

            arguments[1].value = null;
        });
        /**
         * 添加图片
         */
        EventBase.addListener('openImage', function (e) {
            commands.closeToolsPop();
            var url = arguments[1].files;

            if (!url || url.length < 1) return;

            var _errFileNum = 0;
            for (var i = 0; i < url.length; i++) {
                var _curPath = url[i].path;
                var _ext = commands.getExtName(_curPath)[0];
                if (commands.changeFileExtType(_ext) != 'image') {
                    _errFileNum++;
                    continue;
                }
                if (commands.getFileExtType(_ext) != 'image') {
                    _errFileNum++;
                    continue;
                }
                if (!commands.changeFilePathIsSpeailCharts(_curPath, true)) {
                    _errFileNum++;
                    continue
                }
                if(_ext == ".gif"){
                    copyGifToFolder(_curPath, function (o, _opt) {
                        var _gifSrc = o.gifSrc;
                        var _img = new Image();
                        _img.loadTimes = 0;
                        _img.src = encodeURI(_gifSrc);
                        _img.idx = _opt.idx;
                        _img.onload = function () {
                            if(_img.loadTimes > 0) return false;    //防止因更新src造成的多次触发
                            _img.loadTimes++;
                            var _scale = commands.setObjSizeForStage(this);
                            var _l = (DEFAULT_STAGE.width - _img.width * (_scale || 1)) * 0.5;
                            var _t = (DEFAULT_STAGE.height - _img.height * (_scale || 1)) * 0.5;
                            _t = new fabric.Gif(_img, {left: _l + (_img.idx * 10), top: _t + (_img.idx * 10), width: this.width * (_scale || 1), height: this.height * (_scale || 1)});
                            _t.id = o.widgetId;
                            var _gifDir = AppContext.joinPath(Global.CurrentSlide.c.getCurMediaPath(),_t.id);
                            _t.showEditDialog({imgSrc: _gifSrc.replace(_gifDir+'/', '')}, addElement);
                        }
                    }, {idx: i, _en: true});
                }
                else{
                    copyImgToFolder(_curPath, function (o, _opt) {
                        //commands.hidePop();
                        var _t = null;
                        var _img = new Image();
                        _img.src = encodeURI(o);
                        _img.idx = _opt.idx;
                        _img.onload = function () {
                            var _scale = commands.setObjSizeForStage(this);
                            var _l = (DEFAULT_STAGE.width - _img.width * (_scale || 1)) * 0.5;
                            var _t = (DEFAULT_STAGE.height - _img.height * (_scale || 1)) * 0.5;
                            _t = new fabric.Img(_img, {left: _l + (_img.idx * 10), top: _t + (_img.idx * 10), width: this.width * (_scale || 1), height: this.height * (_scale || 1)});
                            _t.id = commands.randomString(10);
                            _t.showEditDialog(AppContext.joinPath(Global.CurrentSlide.c.getCurMediaPath(), _t.id), addElement);
                        };
                    }, {idx: i, _en: true});
                }
            }
            if (_errFileNum > 0) {
                commands.showSelectorPop(commands.getErrorMsg(2021), null, null, this, [
                    {
                        label: '确定',
                        cssClass: 'btn-primary',
                        action: function () {
                            commands.hidePop();
                            //commands.closeWindow();
                        }}
                ]
                );
            }
            arguments[1].value = null;
        });
        /**
         * 添加媒体
         */
        EventBase.addListener('openMedia', function (type, target) {
            commands.closeToolsPop();
            var url = arguments[1].value;
            var _that = this;
            if (!url || url.length < 5) return;
            var _e = commands.getExtName(url)[0];
            var _extt = commands.changeFileExtType(_e);
            if (_extt != 'video' && _extt != 'audio') {
                commands.showPop(commands.getErrorMsg(3001), 1000);
                arguments[1].value = null;
                return;
            }

            if (!commands.changeFilePathIsSpeailCharts(url)) {
                arguments[1].value = null;
                return;
            }
            var _thumb = null, _res = null, _enPath = null;
            var _type = commands.changeFileExtType(_e);
            if (_e === '.swf' || _type == 'audio') {
                copyImgToFolder(url, function (o) {
                    addObject(o, _type);
                }, {_en: true});
                arguments[1].value = null;
                return;
            }
            _enPath = commands.changeFolderToMedia(url, null, true)
            _thumb = commands.getExtName(_enPath, 'jpg');
            _res = commands.getExtName(_enPath, 'mp4');
            var _isH264 = false;
            commands.showPop(commands.getErrorMsg(2016));
            IO.getMediaThemb(AppContext.joinPath(url)).done(function (e) {

                var _video = e.match(/Stream #.*Video:.*/g);
                var _size = _video[0].match(/\d{2,4}x\d{1,4}/g);
                if (!_video) {
                    commands.showPop(commands.getErrorMsg(2017), 2000);
                    return
                } else {
                    _video = _video[0];
                }
                if (_video.indexOf('h264') >= 0) {
                    _isH264 = true;
                }
                IO.getMediaThemb(AppContext.joinPath(url),_thumb,_size).done(function (e) {
                    commands.hidePop();
                    if (!_isH264 || (_type === 'video' && _e != '.mp4')) {
                        //todo 中文pad播放有问题,全换成英文路径
                        commands.showSelectorPop(commands.getErrorMsg(2009), function (_is) {
                            if (_is) {
                                commands.setAppState('videoConvert', true);
                                Global.AppState.init.value = true;
                                commands.hidePop();
                                //var _desurl =  commands.getExtName(commands.changeFolderToMedia(url),'mp4');
                                IO.ffmpeg(AppContext.joinPath(url), _res).done(function (e) {
                                    commands.resetAppState();
                                    commands.hidePop();
                                    Global.AppState.init.value = false;
                                    if (e) {
                                        addObject(_res, 'video', _size[0]);
                                    } else {
                                        commands.showPop(commands.getErrorMsg(3011), 1000);
                                    }
                                });
                                setTimeout(function () {
                                    //commands.showPop(commands.getErrorMsg(2007));
                                    var popContent = "<div id='pptConverting' style='text-align: center; width:100%; height: 50px; font-family: microsoft yahei; font-size: 16px; color: #898989;'>" +
                                        "<img src='editor/assert/images/loading.gif' style='margin-left: auto; margin-right: auto; margin-top: -10px; height: 30px; width:30px;'/><p>" +
                                        commands.getErrorMsg(2007) + "</p></div>";
                                    commands.showSelectorPop(popContent, null, null, _that, [
                                        {
                                            label: '取消',
                                            cssClass: 'btn-primary',
                                            action: function () {
                                                cancelMediaChange.call(_that, true);
                                            }
                                        }
                                    ], true)
                                }, 500);
                            } else {
                                commands.hidePop();
                                _thumb && IO.removeFile(_thumb).done(function (e) {

                                })
                            }
                        }, null, this, null, 'close');
                        return;
                    } else {
                        commands.showPop(commands.getErrorMsg(2002));

                        IO.copyFile(url, _res).done(function () {
                            addObject(_res, _type, _size[0]);
                        })
                    }
                })
            });
            function cancelMediaChange(_is) {
                commands.hidePop();
                IO.shellexecute("taskkill /F /IM ffmpeg.exe /T");
                IO.removeFile(_res).done(function (e) {
                    commands.resetAppState();
                })
                IO.removeFile(_thumb).done(function (e) {

                })
            }

            //添加文件
            function addObject(_desurl, _type, _size) {

                if (_type == 'video') {
                    if (_thumb) {
                        e(_thumb, 1, _size);
                    } else {
                        copyImgToFolder(AppContext.joinPath(AppContext.getDefaultImagePath(), 'movie.png'), function (o) {
                            e(o, 1, _size);
                        }, {_en: true})
                    }
                } else {
                    copyImgToFolder(AppContext.joinPath(AppContext.getDefaultImagePath(), 'audio.png'), function (o) {
                        e(o, 2, _size);
                    }, {_en: true})
                }

                function e(_src, type, _size) {
                    commands.hidePop();
                    var _t = null;
                    var _img = new Image();
                    _img.src = _src;
                    _img.onload = function () {
                        var _s = [320, 240]; //因为播放器最小宽是320
                        if (_size) {
                            _s = _size.split('x');
                        }
                        var _bl = _s[0]/_s[1];
                        var _w = _s[0], _h = _s[1];
                        if(_w<=320)
                        {
                          _w = 320;
                          _h =  320/_bl;
                        }
                        _t = type == 1 ? new fabric.Video(_img, {left: (DEFAULT_STAGE.width - _w) * 0.5, top: (DEFAULT_STAGE.height - _h) * 0.5, width: parseInt(_w), height: parseInt(_h)}) : new fabric.Audio(_img, {left: 50, top: 100, width: 397, height: 30});
                        _t.id = commands.randomString(10);
                        _t.showEditDialog({source: _desurl.replace(Global.CurrentSlide.c.getCurSlidePath(), '')}, addElement);
                    }
                }

            }

            arguments[1].value = null;
        });
        /**
         * 添加文字
         */
        $('#btn_text').on('click', function (e) {
            if (Global.SlideArray.length < 1)return;
            commands.closeToolsPop();
            var _t = null;
            try {
                _t = new fabric.TextField(commands.getErrorMsg(4001), {left: 50, top: 100});
            } catch (error) {
                commands.showPop(commands.getErrorMsg(50), 1000);
                throw('没有找到对象');
            }
            _t.id = commands.randomString(10);
            _t.showEditDialog(AppContext.joinPath(Global.CurrentSlide.c.getCurMediaPath(), _t.id), addElement);
        });
        $('#btn_bg').on('click', function (e) {
            if (Global.SlideArray.length < 1)return;
            commands.closeToolsPop('bg_list_box');
            var _bg = Global.CurrentSlide.c._canvas.backgroundImage || Global.CurrentSlide.c._canvas.backgroundColor.source;
            if (_bg) {
                $('#set_slide_bg>img').attr('src', _bg.src);
            } else {
                $('#set_slide_bg>img').attr('src', "editor/assert/images/customer_img.jpg");
            }
        });
        /**
         * 添加背景图片
         */
        EventBase.addListener('openBackGround', function (e) {
            commands.closeToolsPop();
            var url = arguments[1].value;

            if (!url || url.length < 5) return;

            if (commands.changeFileExtType(commands.getExtName(url)[0]) != 'image') {
                commands.showPop(commands.getErrorMsg(3002), 1000);
                arguments[1].value = null;
                return;
            }

            var _type = commands.getFileExtType(commands.getExtName(url)[0]);
            if (_type != 'image') {
                commands.showPop(commands.getErrorMsg(3002), 1000);
                arguments[1].value = null;
                return;
            }

            if (!commands.changeFilePathIsSpeailCharts(url)) {
                arguments[1].value = null;
                return;
            }
            if (Global.selSlides.length > 0) {
                var _check = $('#background_is_full')[0].checked;
                setAllSlideBackground(Global.selSlides, url, null, _check ? 'repeat' : false, true);
                Global.selSlides = [];
            } else {
                commands.showPop(commands.getErrorMsg(2002));
                commands.saveCtrlPath('background');
                copyImgToFolder(url, function (o) {
                    Global.isVariety = true;
                    var _check = $('#background_is_full')[0].checked;
                    Global.CurrentSlide.c.setBackgroundImage(o, _check ? 'repeat' : false);
                    //if(Global.DefaultBackground.use )
                    //{
//                    Global.DefaultBackground.src = decodeURI(url.replace('file:///', ''));
//                    Global.DefaultBackground.color = null;
//                    Global.DefaultBackground.repeat = _check ? 'repeat' : false;
                    //}
                    $('#set_slide_bg>img').attr('src', url);
                    var sid = setTimeout(function () {
                        commands.hidePop();
                        commands.showThumbImg(Global.CurrentSlide.c._canvas);
                        clearTimeout(sid);
                    }, 200)
                }, {_en: true})
            }
            arguments[1].value = null;
        });

        //默认设置背景
        $('#background_use_all').on('click', function (e) {
            if (Global.SlideArray.length < 1)return;
            var _bg = null, _bc = '', _repeat = false;
            if (Global.CurrentSlide.c._canvas.backgroundImage) {
                _bg = Global.CurrentSlide.c._canvas.backgroundImage._element.src.replace('file:///', '');
            } else {
                if (typeof Global.CurrentSlide.c._canvas.backgroundColor === "string") {
                    _bc = Global.CurrentSlide.c._canvas.backgroundColor;
                } else {
                    _bg = Global.CurrentSlide.c._canvas.backgroundColor.source.src.replace('file:///', '');
                    _repeat = 'repeat';
                }
            }
            setAllSlideBackground(Global.SlideArray, _bg, _bc, _repeat, false);
        })

        $('#bg_list_def_box>ul>li').on('click', function (e) {
            var _dom = $(this).find('a').attr('bg-style');
            if (!_dom) return;
            Global.isVariety = true;
            var _style = _dom.split(';')[0];
            if (_style.indexOf('background-color') >= 0) {
                _style = _style.match(/\#.+/)[0];
                if (Global.selSlides.length > 0) {
                    setAllSlideBackground(Global.selSlides, null, _style, false, true);
                    Global.selSlides = [];
                } else {
                    commands.saveCtrlPath('background');
                    Global.CurrentSlide.c._canvas.backgroundImage = null;
                    Global.CurrentSlide.c._canvas.setBackgroundColor(_style);
                    Global.CurrentSlide.c.renderAll();
                    //if(Global.DefaultBackground.use)
                    //{

                    //}
                    commands.writeSlideJson();

                }

            } else {
                _style = _style.match(/\(.+\)/g)[0];
                _style = _style.replace(/(\(|\))/g, '');
                if (Global.selSlides.length > 0) {
                    setAllSlideBackground(Global.selSlides, AppContext.joinPath(_style), null, false, true);
                    Global.selSlides = [];
                } else {
                    commands.saveCtrlPath('background');
                    copyImgToFolder(AppContext.joinPath(_style), function (src) {
                        Global.CurrentSlide.c.setBackgroundImage(src);
                        //if(Global.DefaultBackground.use)
                        //{

                        //}
                        setTimeout(function () {
                            commands.writeSlideJson();
                        }, 100)
                    })
                }

            }

        })
        $("#bg_list_def").on('click', function (e) {
            $('#bg_list_def_box').toggle();
            $('#bg_list_use_box').toggle();
        });
        $("#bg_list_use").on('click', function (e) {
            $('#bg_list_use_box').toggle();
            $('#bg_list_def_box').toggle();
        });
        //图形
        $("#path_btn").on('click', function (e) {
            if (Global.SlideArray.length < 1)return;
            commands.closeToolsPop('path_list_box');
            //$('#path_list_box').toggle();
        })
        $('#path_list_box li').on('click', function (e) {
            commands.closeToolsPop();
            var _idx = $(e.currentTarget).attr('idx');
            var _t = null;
            try {
                fabric.loadSVGFromURL(AppContext.joinPath(AppContext.getSVGPath(), _idx + '.svg'), function (objects, options) {
//                    commands.saveCtrlPath('object');
                    _t = new fabric.Graphica(objects, options);
                    _t.set({left: 200, top: 100})
                    _t.id = commands.randomString(10);
//                    Global.CurrentSlide.c.add(_t);
                    _t.showEditDialog(null, addElement);
                    setTimeout(function () {
                        commands.showThumbImg(Global.CurrentSlide.c._canvas).done(function(){
                            commands.saveCtrlPath('object');
                        });
                    }, 150)
                })

            } catch (error) {
                commands.showPop(commands.getErrorMsg(50), 1000);
                throw('没有找到对象');
            }
        })
        //-------------------------play
        var btn_play_part1=document.getElementById("btn_play_part1") ;
        var btn_play_part2=document.getElementById("btn_play_part2") ;
        btn_play_part2.onmouseover=function(){
            btn_play_part1.className="btn_play_part1 add_btn_play_part";
        }
        btn_play_part2.onmouseout=function(){
            btn_play_part1.className="btn_play_part1";
        }
        /**
         * 播放当前
         */
        $('#btn_play_part1').on('click', function (e) {
            if (Global.SlideArray.length < 1)return;
            var _clle = arguments.callee;
            $('#btn_play_part1').off();
            setTimeout(function () {
                $('#btn_play_part1').on('click', _clle)
            }, 1000)
            saveSlide(function () {
//                window.open("player.html?package=" + AppContext.getCurSlidePackPath());         //直接打开新窗口

                gui.Window.open("player.html?package=" + AppContext.getCurSlidePackPath(),{
                        'new-instance':true,
                        "position": 'center',
                        "frame": false,
                        "icon":"share/assert/images/icon.png",
                        "transparent": true,
                        "toolbar": false,
                        "show":true,
                        "kiosk":true,
                        "focus":true
                    });    //使用Window.open方法，设置new-instance为true，启动新窗口

//                var cmd = '\"' + AppContext.getLauncherPath() + '\" \"' + AppContext.getCurSlidePackPath() + '\" player';       //使用启动器启动
//                var cmd = '\"' + AppContext.getNWPath() + '\" \"'+AppContext.getBinPath() + '\" true \"' + AppContext.getCurSlidePackPath() + '\" player';       //直接启动NW.exe
//                console.log(cmd);
//                var last = exec(cmd, function(err, stdout , stderr ) {
//                    if(err)   console.err(err);
//                });
            })
        });
        $('#btn_play_part2').on('click', function (e) {
            if (Global.SlideArray.length < 1)return;
            commands.closeToolsPop('btn_play_list');
        });
        $('#btn_play_list_first').on('click', function (e) {
            if (Global.SlideArray.length < 1)return;
            saveSlide(function () {
//                window.open("player.html?package=" + AppContext.getCurSlidePackPath());          //直接打开新窗口

                gui.Window.open("player.html?package=" + AppContext.getCurSlidePackPath(),{
                    'new-instance':true,
                    "position": 'center',
                    "frame": false,
                    "icon":"share/assert/images/icon.png",
                    "transparent": true,
                    "toolbar": false,
                    "show":true,
                    "kiosk":true,
                    "focus":true
                });    //使用Window.open方法，设置new-instance为true，启动新窗口

//                var cmd = '\"' + AppContext.getLauncherPath() + '\" \"' + AppContext.getCurSlidePackPath() + '\" player';      //使用启动器启动
//                var cmd = '\"' + AppContext.getNWPath() + '\" \"'+AppContext.getBinPath() + '\" true \"' + AppContext.getCurSlidePackPath() + '\" player';        //直接启动NW.exe
//                console.log(cmd);
//                var last = exec(cmd, function(err, stdout , stderr ) {
//                    if(err)   console.err(err);
//                });
            })
        });
        $('#btn_play_list_current').on('click', function (e) {
            if (Global.SlideArray.length < 1)return;
            saveSlide(function () {
//                window.open("player.html?package=" + AppContext.getCurSlidePackPath() + "&pname=" + Global.CurrentSlide.c.Name);        //直接打开新窗口

                gui.Window.open("player.html?package=" + AppContext.getCurSlidePackPath() + "&pname=" + Global.CurrentSlide.c.Name,{
                    'new-instance':true,
                    "position": 'center',
                    "frame": false,
                    "icon":"share/assert/images/icon.png",
                    "transparent": true,
                    "toolbar": false,
                    "show":true,
                    "kiosk":true,
                    "focus":true
                });    //使用Window.open方法，设置new-instance为true，启动新窗口

//                var cmd = '\"' + AppContext.getLauncherPath() + '\" \"' + AppContext.getCurSlidePackPath() + '&pname=' + Global.CurrentSlide.c.Name + '\" player';      //使用启动器启动
//                var cmd = '\"' + AppContext.getNWPath() + '\" \"'+AppContext.getBinPath() + '\" true \"' + AppContext.getCurSlidePackPath() + '&pname=' + Global.CurrentSlide.c.Name + '\" player';    //直接启动NW.exe
//                console.log(cmd);
//                var last = exec(cmd, function(err, stdout , stderr ) {
//                    if(err)   console.err(err);
//                });
            })
        });

        $('#scale_btn_play').on('click', function (e) {
            var _clle = arguments.callee;
            $('#scale_btn_play').off();
            setTimeout(function () {
                $('#scale_btn_play').on('click', _clle)
            }, 1000)
            if (Global.SlideArray.length < 1)return;
            saveSlide(function () {
//                window.open("player.html?package=" + AppContext.getCurSlidePackPath() + "&pname=" + Global.CurrentSlide.c.Name);          //直接打开新窗口

                gui.Window.open("player.html?package=" + AppContext.getCurSlidePackPath() + "&pname=" + Global.CurrentSlide.c.Name,{
                    'new-instance':true,
                    "position": 'center',
                    "frame": false,
                    "icon":"share/assert/images/icon.png",
                    "transparent": true,
                    "toolbar": false,
                    "show":true,
                    "kiosk":true,
                    "focus":true
                });    //使用Window.open方法，设置new-instance为true，启动新窗口

//                var cmd = '\"' + AppContext.getLauncherPath() + '\" \"' + AppContext.getCurSlidePackPath() + '&pname=' + Global.CurrentSlide.c.Name + '\" player';      //使用启动器启动
//                var cmd = '\"' + AppContext.getNWPath() + '\" \"'+AppContext.getBinPath() + '\" true \"' + AppContext.getCurSlidePackPath() + '&pname=' + Global.CurrentSlide.c.Name + '\" player';    //直接启动NW.exe
//                console.log(cmd);
//                var last = exec(cmd, function(err, stdout , stderr ) {
//                    if(err)   console.err(err);
//                });
            })
        })
        /**
         * 缩小
         */
        $('#scale_decrease').on('click', function (e) {
            if (DEFAULT_STAGE.scale > 0.5) {
                DEFAULT_STAGE.scale = ((DEFAULT_STAGE.scale * 10 - 1) / 10).toFixed(1);
                $('#scale_ctrl_bar')[0].value = Math.floor(DEFAULT_STAGE.scale * 10);
                scaleStage();
            }
        })
        /**
         * 放大
         */
        $('#scale_increase').on('click', function (e) {
            if (DEFAULT_STAGE.scale < 2) {
                DEFAULT_STAGE.scale = (Number(DEFAULT_STAGE.scale) + 0.1).toFixed(1);

                scaleStage();
            }
        })

        EventBase.addListener('stageScaleCtrl', function (e, target) {
            if (!target.value)return;

            DEFAULT_STAGE.scale = Number(((target.value) / 10).toFixed(1));
            scaleStage();
        })
        //---------------------slide ctrl
        /**
         * 添加一页
         */
        $('#btn_add').on('click', function (e) {
            commands.resetExportBtn(false);
            if (Global.SlideArray.length <= 0) {
                commands.toggerCmdBtns(true)
            }
            if (Global.AppState.init.value || Global.AppState.inputPPT.value) return;
            Global.isVariety = true;
            Global.selSlides = [];
            addPages(null,function(_idx,_type){
                updateStage(Global.SlideArray.length>1? _idx:0,_type);
                showThumbScroll();
            });
        });
        /**
         * 清空后新加一页
         */
        EventBase.addListener('elementPageAdd', function (e, target) {
            commands.resetExportBtn(false);
            if (Global.SlideArray.length <= 0) {
                commands.toggerCmdBtns(true)
            }
            if (Global.AppState.init.value || Global.AppState.inputPPT.value) return;
            Global.isVariety = true;
            Global.selSlides = [];
            addPages(null,function(_idx,_type){
                updateStage(0,_type);
                showThumbScroll();
            });
        })
        /**
         * 删除页
         */
        function deleteSelectedSlides() {
            if (Global.SlideArray.length <= 0) return;
            if (Global.AppState.init.value || Global.AppState.inputPPT.value) return;
            Global.isVariety = true;
            var list = $('#pageArea_list>li');
            var cur = $('#pageArea_list>.current').attr('id');
            var _idx = 0;
            //是否包括当前的slide
            var _haveCurt = false;
            if (Global.selSlides.length > 0) {
                commands.saveCtrlPath('delPage', {slide: Global.SlideArray, package: Global.PackageJson.slides});
                for (var m = Global.selSlides.length - 1; m >= 0; m--) {
                    if (Global.selSlides[m].content.attr('id') === Global.CurrentSlide.t.content.attr('id')) {
                        Global.CurrentSlide.c.clear();
                        Global.CurrentSlide = null;
                        $('#stageArea').html('');
                    }
                    delSlides(Global.selSlides[m]);
                }
                Global.selSlides = [];
                IO.writeFile(AppContext.getPackageJsonPath(), JSON.stringify(Global.PackageJson));
                if (Global.SlideArray.length > 0)updateStage(Math.floor(Global.SlideArray.length / 2), 3);
            } else {
                for (var i = 0; i < list.length; i++) {
                    if (list[i].id === cur) {
                        _idx = i;
                        var _dpath = Global.SlideArray[i].c.getCurSlidePath();
                        $('#pageArea_list>.current').remove();
                        $('#stageArea').html('');
                        commands.saveCtrlPath('delPage', {slide: Global.SlideArray, package: Global.PackageJson.slides});
                        Global.SlideArray[i].c.clear();
                        delete  Global.SlideArray[i];
                        Global.KeyLists = [];
                        Global.CurrentSlide = null;
                        Global.SlideArray.splice(i, 1);
                        Global.PackageJson.slides.splice(i, 1);
                        i == 0 ? 0 : i--;
                        //删除文件
                        IO.writeFile(AppContext.getPackageJsonPath(), JSON.stringify(Global.PackageJson));
                        /*IO.exists(_dpath).done(function (e) {
                         e && IO.rmdir(_dpath);
                         });*/
                        //----------加载剩余的slide
                        if (Global.SlideArray.length <= 0) {
                            //$('#btn_add')[0].click();
                        } else {
                            updateStage(i, 5);
                        }
                        break;
                    }
                }
            }
            function delSlides(_slide) {
                for (var i = 0; i < Global.SlideArray.length; i++) {
                    if (Global.SlideArray[i].t.content.attr('id') == _slide.content.attr('id')) {
                        var _dpath = Global.SlideArray[i].c.getCurSlidePath();
                        delete  Global.SlideArray[i];
                        Global.SlideArray.splice(i, 1);
                        Global.PackageJson.slides.splice(i, 1);
                        _slide.content.remove();
                        //IO.rmdir(_dpath);
                        return;
                    }
                }
            }

            showThumbScroll();
            commands.addNotSlideMask();
        }

        /**
         * 属性功能
         */
            //与对象左对齐
        $('#global_group>a:nth-of-type(1)').on('click', function (e) {

            Global.isVariety = true;
            var _obj = Global.CurrentSlide.c._canvas.getActiveGroup();
            if (!_obj) return;
            _obj = _obj._objects;
            commands.setGroupAlign(_obj, 'left');
        });
        //与对象右对齐
        $('#global_group>a:nth-of-type(2)').on('click', function (e) {
            Global.isVariety = true;
            var _obj = Global.CurrentSlide.c._canvas.getActiveGroup();
            if (!_obj) return;
            _obj = _obj._objects;
            commands.setGroupAlign(_obj, 'right');
        });
        //与对象顶对齐
        $('#global_group>a:nth-of-type(3)').on('click', function (e) {
            Global.isVariety = true;
            var _obj = Global.CurrentSlide.c._canvas.getActiveGroup();
            if (!_obj) return;
            _obj = _obj._objects;
            commands.setGroupAlign(_obj, 'top');
        });
        //与对象中对齐
        $('#global_group>a:nth-of-type(4)').on('click', function (e) {
            Global.isVariety = true;
            var _obj = Global.CurrentSlide.c._canvas.getActiveGroup();
            if (!_obj) return;
            _obj = _obj._objects;
            commands.setGroupAlign(_obj, 'center');
        });
        //与对象底对齐
        $('#global_group>a:nth-of-type(5)').on('click', function (e) {
            Global.isVariety = true;
            var _obj = Global.CurrentSlide.c._canvas.getActiveGroup();
            if (!_obj) return;
            _obj = _obj._objects;
            commands.setGroupAlign(_obj, 'buttom');
        });

        //顶层
        $('#sort_group>a:nth-of-type(1)').on('click', function (e) {

            Global.isVariety = true;
            var _obj = Global.CurrentSlide.c.getActiveObject();
            if (!_obj) return;
            _obj.bringToFront();
            setTimeout(function(){
                commands.saveCtrlPath('object');
            },100)
        });
        //底层
        $('#sort_group>a:nth-of-type(2)').on('click', function (e) {
            Global.isVariety = true;
            var _obj = Global.CurrentSlide.c.getActiveObject();
            if (!_obj) return;
            _obj.sendToBack();
            setTimeout(function(){
                commands.saveCtrlPath('object');
            },100)
        });
        //上移一层
        $('#sort_group>a:nth-of-type(3)').on('click', function (e) {
            Global.isVariety = true;
            var _obj = Global.CurrentSlide.c.getActiveObject();
            if (!_obj) return;
            _obj.bringForward();
            setTimeout(function(){
                commands.saveCtrlPath('object');
            },100)
        });
        //下移一层
        $('#sort_group>a:nth-of-type(4)').on('click', function (e) {
            Global.isVariety = true;
            var _obj = Global.CurrentSlide.c.getActiveObject();
            if (!_obj) return;
            _obj.sendBackwards();
            setTimeout(function(){
                commands.saveCtrlPath('object');
            },100)
        });

        EventBase.off('addElment');
        EventBase.on('addElment',function(type,opts){
            console.log(opts)
            if(opts)
            {
                commands.writeSlideJson();
            }
        })

        /*----------------------动画*/
        EventBase.off('animation');
        EventBase.on('animation',function(type,opts){
            var _opt = arguments[1];
            //找到父对象
            var _fdiv = $(arguments[1][0]).closest('div').find('button:nth-child(1)');
            var _value = _opt[0].text || _fdiv.text;
            _fdiv.text(_value);
            switch (_opt[1])
            {
                case "animation-none":
                    var _obj = Global.CurrentSlide.c.getActiveObject();
                    var _slide = Global.CurrentSlide.c;
                    Global.isVariety = true;
                    _slide.delAnimationInfo(_obj.id);
                    break;
                case "animation-in":
                    Global.isVariety = true;
                    var _obj = Global.CurrentSlide.c.getActiveObject();
                    var _slide = Global.CurrentSlide.c;
                    var aniInfo = {"id": _obj.id, type: "fadeIn", "trigger": "mousedown", "attr": "opacity", "start": 0, "end": 1, "duration": 1000, "delay": 0};
                    _slide.addAnimationInfo(aniInfo);
                    break;
            }
        })
        //----------------------------------widget
        //时间轴
        $('#widget_timeLine').on('click', function (e) {
            $('#hdmb_list_box').hide();
            var _t = null;
            try {
                _t = new fabric.History();
            } catch (error) {
                commands.showPop(commands.getErrorMsg(2211), 1000);
                throw(commands.getErrorMsg(2211));
            }
            _t.showEditDialog(null);
        });
        //翻翻卡
        $('#widget_turnCard').on('click', function (e) {
            $('#hdmb_list_box').hide();
            var _t = null;
            try {
                _t = new fabric.Flipcard();
            } catch (error) {
                commands.showPop(commands.getErrorMsg(2221), 1000);
                throw(commands.getErrorMsg(2221));
            }
            _t.showEditDialog(null);
        });
        //画廊
        $('#widget_gallery').on('click', function (e) {
            $('#hdmb_list_box').hide();
            var _t = null;
            try {
                _t = new fabric.Gallery();
            } catch (error) {
                commands.showPop(commands.getErrorMsg(2231), 1000);
                throw(commands.getErrorMsg(2231));
            }
            _t.showEditDialog(null);
        });
        //函数图像
        $('#widget_mathGraph').on('click', function (e) {
            $('#hdmb_list_box').hide();
            var _t = null;
            try {
                _t = new fabric.MathGraph();
            } catch (error) {
                commands.showPop(commands.getErrorMsg(2241), 1000);
                throw(commands.getErrorMsg(2241));
            }
            _t.showEditDialog(null);
        });
        //数学公式
        $('#widget_mathEquation').on('click', function (e) {
            $('#hdmb_list_box').hide();
            var _t = null;
            try {
                _t = new fabric.MathEquation();
            } catch (error) {
                commands.showPop(commands.getErrorMsg(2251), 1000);
                throw(commands.getErrorMsg(2251));
            }
            _t.showEditDialog(null);
        });


        $('#widget_speechApp').on('click', function (e) {
            $('#hdmb_list_box').hide();

            if ($('#modal-content')) {
                $('#modal-content').remove();
            }

            var dlg = $('<div id="modal-content" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog">' +
                '<div class="modal-dialog">' +
                '<div class="test_temp" style="width: 640px;height: 470px;">' +

                '<div class="pop_tit">' +
                '<span class="fl">语音应用' +
                '</span>' +
                '<div class="w_func fr"><a href="javascript:;" title="关闭" data-dismiss="modal" class="w_func_close"></a></div>' +
                '</div>' +

                '<div class="tst_temp_step tst_temp_step_voice">' +

                '<div class="test_temp_voice_box clearfix" style="margin-left: 20px;">' +
                '<a class="btn-speechapp-cneval speechapp_tpl" href="javascript:;"  data-toggle="modal" data-keyboard="false" data-backdrop="false" title="中文字词评测卡片" data-target="123123">' +
                '<img alt="中文字词评测卡片" src="editor/assert/images/pop/voice_img.png">' +
                commands.getErrorMsg(2263) +
                '</a>' +
                '<a class="btn-speechapp-eneval speechapp_tpl" href="javascript:;" title="英文单词评测卡片" data-dismiss="modal" style="margin-left: 90px;">' +
                '<img alt="英文单词评测卡片" src="editor/assert/images/pop/voice_img2.png">' +
                commands.getErrorMsg(2264) +
                '</a>' +
                '<a class="btn-speechapp-situdlg speechapp_tpl" href="javascript:;" title="英文情景对话评测卡片" data-dismiss="modal">' +
                '<img alt="英文情景对话评测卡片" src="editor/assert/images/pop/voice_img3.jpg">' +
                commands.getErrorMsg(2265) +
                '</a>' +
                '</div>' +

                '</div>' +

                '</div>' +
                '</div>' +
                '</div>');

            var top = (window.innerHeight - 470) / 2;

            dlg.css("paddingTop", top);

            $('body').append(dlg);

            dlg.modal({show: true, backdrop: "static", keyboard: false});

            dlg.find(".btn-speechapp-cneval").bind('click', function () {
                dlg.modal('hide');
                dlg.on('hidden.bs.modal', function (e) {
                    dlg.remove();
                    var _t = null;
                    try {
                        _t = new fabric.CnEval();

                    } catch (error) {
                        commands.showPop(commands.getErrorMsg(2261), 1000);
                        throw(commands.getErrorMsg(2261));
                    }
                    _t.showEditDialog(null);
                });
            });

            dlg.find(".btn-speechapp-eneval").bind('click', function () {
                dlg.modal('hide');
                dlg.on('hidden.bs.modal', function (e) {
                    dlg.remove();
                    var _t = null;
                    try {
                        _t = new fabric.EnEval();

                    } catch (error) {
                        commands.showPop(commands.getErrorMsg(2261), 1000);
                        throw(commands.getErrorMsg(2261));
                    }
                    _t.showEditDialog(null);
                });
            });

            dlg.find(".btn-speechapp-situdlg").bind('click', function () {
                dlg.modal('hide');
                dlg.on('hidden.bs.modal', function (e) {
                    dlg.remove();
                    var _t = null;
                    try {
                        _t = new fabric.Situdlg();

                    } catch (error) {
                        commands.showPop(commands.getErrorMsg(2261), 1000);
                        throw(commands.getErrorMsg(2261));
                    }
                    _t.showEditDialog(null);
                });
            });


        });

        //测验
        $("#widget_test").on('click', function () {
            $('#hdmb_list_box').hide();
            var _t = null;
            try {
                _t = new fabric.Exercise();

            } catch (error) {
                throw('没有找到测验对象');
            }
            _t.showEditDialog(null);
            event.stopPropagation();
        });


        //PPT
        $('#widget_PPT').on('click', function (e) {
            $('#hdmb_list_box').hide();
            var dlg = $('<div id="modal-content" class="modal fade" tabindex="-1" role="dialog">'+
                '<div class="modal-dialog test_temp" style="width: 500px;height: 340px;">' +
                '<div class="pop_tit">' +
                '<span class="fl">PPT</span>' +
                '<div class="w_func fr">' +
                '<a href="javascript:;" title="关闭" class="w_func_close" data-dismiss="modal"></a>' +
                '</div>' +
                '</div>' +
                '<div id="test_temp_container" style="background-color: rgb(255, 255, 255); height: 276px;" class="tst_temp_step tst_temp_step1">'+
                '<div class="tst_temp_step_box clearfix test_selectType" style="padding: 80px 56px">'+
                '<a href="javascript:void(0);" title="PPT画廊" class="ppt_gallery"><img alt="PPT画廊" src="editor/assert/images/pop/type_img06.jpg">PPT画廊</a>'+
                '<a href="javascript:void(0);" title="导入PPT" class="ppt_insert"><img alt="导入PPT" src="editor/assert/images/pop/type_img05.jpg">导入PPT' +
                '<input type="file" accept=".ppt,.pptx"  style="opacity: 0;width: 150px;height: 155px;position: relative;top: -155px;" onchange="EventBase.fireEvent(\'openPPT\',this)"/></a>' +
                '</div></div>' +
                '</div>' +
                '</div>');
            var top= 75;
            dlg.css("paddingTop",top);
            dlg.modal({show: true,keyboard:false,backdrop : "static"});
            dlg.on('hidden.bs.modal', function (e) {
                dlg.remove();
                Global.isEditing = false;
            });

            // ppt画廊
            dlg.find('.ppt_gallery').on('click', function () {
                dlg.modal('hide');
                dlg.on('hidden.bs.modal', function (e) {
                    dlg.remove();
                    var _t = null;
                    try {
                        _t = new fabric.PPT();
                    } catch (error) {
                        throw('没有找到ppt应用对象');
                    }
                    _t.showEditDialog();
                });
            });

            // 导入ppt
            dlg.find('.ppt_insert').on('click', function () {
                dlg.modal('hide');
                dlg.on('hidden.bs.modal', function (e) {
                    dlg.remove();

                });
            });
        });

        //分类题
        $("#widget_pickCard").on('click', function () {
            $('#hdmb_list_box').hide();
            var _t = null;
            try {
                _t = new fabric.Pickcard();
            } catch (error) {
                commands.showPop(commands.getErrorMsg(2231), 1000);
                throw(commands.getErrorMsg(2231));
            }
            _t.showEditDialog(null);
        });

        //连线题
        $("#widget_matchCard").on('click', function () {
            $('#hdmb_list_box').hide();
            var _t = null;
            try {
                _t = new fabric.Matchcard();
            } catch (error) {
                commands.showPop(commands.getErrorMsg(2231), 1000);
                throw(commands.getErrorMsg(2231));
            }
            _t.showEditDialog(null);
        });

        //资源上传
        $("#btn_upLoad").on('click', function (e) {
            if (Global.SlideArray.length < 1)return;
            urlCheck.pingBaidu().done(function (ret) {
                if (ret) {
                    Global.AppState.upload.value = true;
                    $('#btn_save')[0].click();
                } else {
                    commands.showSelectorPop("请联网后再上传!", function () {
                        commands.hidePop();
                    }, null, this, [
                        {
                            label: '确定',
                            cssClass: 'btn-primary',
                            action: function () {
                                commands.hidePop();
                            }
                        }
                    ])
                }
            });
        });

        $('#btn_new').on('click', function () {
            appUtil.executeApp('..\\..\\iFlySlide.exe');
        });
    }

    /**
     * 打开一个wgt文件
     * @param _filePath
     */
    function openWidget(_filePath) {
        if (commands.getExtName(_filePath) != '.ict') {
            commands.showPop(commands.getErrorMsg(2004), 2000);
            return;
        }
//        if (!commands.changeFilePathIsSpeailCharts(_filePath, null, false)) {
//            return;
//        }

        var slide = Global.CurrentSlide.c;

        var _name = AppContext.getCurSlidePackPath();

        var relID = commands.randomString(5);

        _name = AppContext.joinPath(_name, 'slides', Global.CurrentSlide.c.Name, 'media', relID);

        commands.showPop(commands.getErrorMsg(2005));

        IO.unZip(_filePath, _name).done(function (e) {
            commands.hidePop();
            if (e) {
                IO.readFile(_name + "/meta.json").done(function (jsonStr) {
                    if(jsonStr){
                        jsonStr = jsonStr.replace(/\n/g, '\\n');
                        var cmd = JSON.parse(jsonStr);
                        creatWidget(cmd.cardtype, relID, _name);
                        LM.statisticsMoudleTime('4104','trigger','widget_import_count');
                        Global.isVariety = true;
                    }else{
                        commands.showPop(commands.getErrorMsg(2006), 2000);
                    }
                });
            } else {
                setTimeout(function () {
                    commands.showPop(commands.getErrorMsg(2006), 5000);
                }, 500);
            }
        });
    }

    /**
     * 创建、保存widget对象
     * @param cardtTypeStr
     * @param relID
     * @param realPath
     */
    function creatWidget(cardtTypeStr, relID, realPath) {
        cardtTypeStr = cardtTypeStr.toLowerCase();
        var slide = Global.CurrentSlide.c;

        switch (cardtTypeStr) {
            case 'history':
                _t = new fabric.History();
                var thumbImgPath = paths.join(realPath, "thumbnail.png");

                var rel = {"id": slide.NewRId(), "src": paths.join('media', relID), "title": "", "des": "", "type": "dir"};
                slide.addRelationInfo(rel);
                _t.rid = rel.id;
                _t.setRelInfo(rel);

                _t.setSrc(thumbImgPath + '?' + commands.randomString(5), function () {
                    _t.scaleX = 1.3;
                    _t.scaleY = 1.3;
                    var mainSize = slide.getCanvasSize();
                    _t.left = (mainSize[0] - _t.width * _t.scaleX) * 0.5;
                    _t.top = (mainSize[1] - _t.height * _t.scaleY) * 0.5;
                    slide.add(_t);

                    slide.renderAll();
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                });
                break;
            case 'flipcard':
                _t = new fabric.Flipcard();
                var thumbImgPath = paths.join(realPath, "thumbnail.png");

                var rel = {"id": slide.NewRId(), "src": paths.join('media', relID), "title": "", "des": "", "type": "dir"};
                slide.addRelationInfo(rel);
                _t.rid = rel.id;
                _t.setRelInfo(rel);

                _t.setSrc(thumbImgPath + '?' + commands.randomString(5), function () {
                    _t.scaleX = 1.3;
                    _t.scaleY = 1.3;
                    var mainSize = slide.getCanvasSize();
                    _t.left = (mainSize[0] - _t.width * _t.scaleX) * 0.5;
                    _t.top = (mainSize[1] - _t.height * _t.scaleY) * 0.5;
                    slide.add(_t);

                    slide.renderAll();
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                });
                break;
            case 'matchcard':
                _t = new fabric.Matchcard();
                var thumbImgPath = paths.join(realPath, "thumbnail.png");

                var rel = {"id": slide.NewRId(), "src": paths.join('media', relID), "title": "", "des": "", "type": "dir"};
                slide.addRelationInfo(rel);
                _t.rid = rel.id;
                _t.setRelInfo(rel);

                _t.setSrc(thumbImgPath + '?' + commands.randomString(5), function () {
                    _t.scaleX = 1.3;
                    _t.scaleY = 1.3;
                    var mainSize = slide.getCanvasSize();
                    _t.left = (mainSize[0] - _t.width * _t.scaleX) * 0.5;
                    _t.top = (mainSize[1] - _t.height * _t.scaleY) * 0.5;
                    slide.add(_t);

                    slide.renderAll();
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                });
                break;
            case 'pickcard':
                _t = new fabric.Pickcard();
                var thumbImgPath = paths.join(realPath, "thumbnail.png");

                var rel = {"id": slide.NewRId(), "src": paths.join('media', relID), "title": "", "des": "", "type": "dir"};
                slide.addRelationInfo(rel);
                _t.rid = rel.id;
                _t.setRelInfo(rel);

                _t.setSrc(thumbImgPath + '?' + commands.randomString(5), function () {
                    _t.width = 715;
                    _t.height = 572;
                    _t.scaleX = 1.1;
                    _t.scaleY = 1.1;

                    var mainSize = slide.getCanvasSize();
                    _t.left = (mainSize[0] - _t.width * _t.scaleX) * 0.5;
                    _t.top = (mainSize[1] - _t.height * _t.scaleY) * 0.5;
                    slide.add(_t);

                    slide.renderAll();
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                });
                break;
            case 'gallery':
                _t = new fabric.Gallery();
                var thumbImgPath = paths.join(realPath, "thumbnail.png");

                var rel = {"id": slide.NewRId(), "src": paths.join('media', relID), "title": "", "des": "", "type": "dir"};
                slide.addRelationInfo(rel);
                _t.rid = rel.id;
                _t.setRelInfo(rel);

                _t.setSrc(thumbImgPath + '?' + commands.randomString(5), function () {
                    _t.width = 660;
                    _t.height = 530;
                    _t.scaleX = 1.2;
                    _t.scaleY = 1.2;

                    var mainSize = slide.getCanvasSize();
                    _t.left = (mainSize[0] - _t.width * _t.scaleX) * 0.5;
                    _t.top = (mainSize[1] - _t.height * _t.scaleY) * 0.5;
                    slide.add(_t);

                    slide.renderAll();
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                });
                break;
            case 'exercise':
                _t = new fabric.Exercise();
                var thumbImgPath = paths.join(realPath, "thumbnail.png");

                var rel = {"id": slide.NewRId(), "src": paths.join('media', relID), "title": "", "des": "", "type": "dir"};
                slide.addRelationInfo(rel);
                _t.rid = rel.id;
                _t.setRelInfo(rel);

                _t.setSrc(thumbImgPath + '?' + commands.randomString(5), function () {
                    _t.width = 700;
                    _t.height = 585;
                    _t.scaleX = 1.1;
                    _t.scaleY = 1.1;

                    var mainSize = slide.getCanvasSize();
                    _t.left = (mainSize[0] - _t.width * _t.scaleX) * 0.5;
                    _t.top = (mainSize[1] - _t.height * _t.scaleY) * 0.5;
                    slide.add(_t);

                    slide.renderAll();
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                });
                break;
            case 'cn_word':
                _t = new fabric.CnEval();
                var thumbImgPath = paths.join(realPath, "thumbnail.png");

                var rel = {"id": slide.NewRId(), "src": paths.join('media', relID), "title": "", "des": "", "type": "dir"};
                slide.addRelationInfo(rel);
                _t.rid = rel.id;
                _t.setRelInfo(rel);

                _t.setSrc(thumbImgPath + '?' + commands.randomString(5), function () {
                    _t.width = 905;
                    _t.height = 540;
                    _t.scaleX = 1.2;
                    _t.scaleY = 1.2;

                    var mainSize = slide.getCanvasSize();
                    _t.left = (mainSize[0] - _t.width * _t.scaleX) * 0.5;
                    _t.top = (mainSize[1] - _t.height * _t.scaleY) * 0.5;
                    slide.add(_t);

                    slide.renderAll();
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                });
                break;
            case 'en_word':
                _t = new fabric.EnEval();
                var thumbImgPath = paths.join(realPath, "thumbnail.png");

                var rel = {"id": slide.NewRId(), "src": paths.join('media', relID), "title": "", "des": "", "type": "dir"};
                slide.addRelationInfo(rel);
                _t.rid = rel.id;
                _t.setRelInfo(rel);

                _t.setSrc(thumbImgPath + '?' + commands.randomString(5), function () {
                    _t.width = 905;
                    _t.height = 540;
                    _t.scaleX = 1.2;
                    _t.scaleY = 1.2;

                    var mainSize = slide.getCanvasSize();
                    _t.left = (mainSize[0] - _t.width * _t.scaleX) * 0.5;
                    _t.top = (mainSize[1] - _t.height * _t.scaleY) * 0.5;
                    slide.add(_t);

                    slide.renderAll();
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                });
                break;
            case 'situ':
                _t = new fabric.Situdlg();
                var thumbImgPath = paths.join(realPath, "thumbnail.png");

                var rel = {"id": slide.NewRId(), "src": paths.join('media', relID), "title": "", "des": "", "type": "dir"};
                slide.addRelationInfo(rel);
                _t.rid = rel.id;
                _t.setRelInfo(rel);

                _t.setSrc(thumbImgPath + '?' + commands.randomString(5), function () {
                    _t.width = 905;
                    _t.height = 590;
                    _t.scaleX = 1.2;
                    _t.scaleY = 1.2;

                    var mainSize = slide.getCanvasSize();
                    _t.left = (mainSize[0] - _t.width * _t.scaleX) * 0.5;
                    _t.top = (mainSize[1] - _t.height * _t.scaleY) * 0.5;
                    slide.add(_t);

                    slide.renderAll();
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                });
                break;
            case 'ppt':
                _t = new fabric.PPT();
                var thumbImgPath = paths.join(realPath, "thumbnail.png");

                var rel = {"id": slide.NewRId(), "src": paths.join('media', relID), "title": "", "des": "", "type": "dir"};
                slide.addRelationInfo(rel);
                _t.rid = rel.id;
                _t.setRelInfo(rel);

                _t.setSrc(thumbImgPath + '?' + commands.randomString(5), function () {
                    _t.scaleX = 1.5;
                    _t.scaleY = 1.5;

                    var mainSize = slide.getCanvasSize();
                    _t.left = (mainSize[0] - _t.width * _t.scaleX) * 0.5;
                    _t.top = (mainSize[1] - _t.height * _t.scaleY) * 0.5;
                    slide.add(_t);

                    slide.renderAll();
                    commands.showThumbImg(Global.CurrentSlide.c._canvas);
                });
                break;
            default :
                commands.showPop(commands.getErrorMsg(3006), 2000);
                break;
        }
    }

    /**
     * 打开一个icw文件
     * @param _url
     */
    function openPackage(_url) {
        if (commands.getExtName(_url) != '.icw') {
            commands.showPop(commands.getErrorMsg(2004), 2000);
            return;
        }
        if (!commands.changeFilePathIsSpeailCharts(_url, null, true)) {
            return;
        }
        Global.saveToPath = _url;
        Global.isEditing = false;
        Global.isVariety = false;
        Global.isAdded = false;
        commands.resetUndoBtn();
        commands.toggerCmdBtns(true);
        Global.DefaultBackground = {src: null, color: null, repeat: false, use: false};
//        $('#background_use_all')[0].checked = false;
        var _name = AppContext.joinPath(_url);
        _name = _name.split('/');
        _name = _name[_name.length - 1];
        _name = _name.substr(0, _name.lastIndexOf('.'));
        var _sname = _name;

        _name = _name + "_" + commands.randomStringAlpha(1) + commands.randomStringNumber(2);

        _name = AppContext.joinPath(AppContext.getTmpPackPath(), _name);

        commands.showPop(commands.getErrorMsg(2005));
        IO.unZip(_url, _name).done(function (e) {
            commands.hidePop();
            commands.resetAppState();
            if (e) {
                Global.PackagePath = AppContext.setCurSlidePackPath(_name);
                $('#saveAsPackage').attr('nwsaveas', _sname.split('.')[0]);
                $('#fileName_title').text(_sname.split('.')[0] + ' - 畅言课件制作工具');
                getFileData(AppContext.getPackageJsonPath());
            } else {
                setTimeout(function () {
                    commands.showPop(commands.getErrorMsg(2006), 5000);
                }, 500);
            }
        });
    }

    /**
     * 删除事件帧听
     */
    function removeEventListener() {

    }

    /**
     * 设置当前选择的thumbe色
     * @param _tar
     */
    function updateSelectPage(_tar, _clear,_unfocus) {
        commands.resetExportBtn(false);

        _clear || $('#pageArea_list>li').removeClass('current current2');

        var _selector = null;
        if (typeof _tar == "number") {
            _selector = '#pageArea_list>li:nth-of-type(' + (_tar + 1) + ')';
        } else {
            _selector = _tar.content;
        }

        $(_selector).addClass('current');
        if(_unfocus === true){    //设置该页为编辑状态
            $(_selector).addClass('current2');
            commands.resetDeleteBtn(false);
        }
    }

    function edtiorSelectionObject(target) {

    }

    /**
     * 打开包
     * 获取指定路径的json信息
     * @param url
     */
    function getFileData(url) {
        IO.readFile(url).done(function (data, err) {
            if (data) {
                resetSlide();
                try {
                    Global.PackageJson = JSON.parse(data);
                    var _sc = Global.PackageJson.presentfmt.split(':');
                    if(Number(_sc[0])!=DEFAULT_STAGE.width){
                        //todo 固定分辨率需要强行修改已前的课件
                        Global.PackageJson.presentfmt = DEFAULT_STAGE.width+':'+DEFAULT_STAGE.height
                        IO.writeFile(AppContext.getPackageJsonPath(), JSON.stringify(Global.PackageJson)).done(function(e){
                            _sc = Global.PackageJson.presentfmt.split(':');
                            resizeStage({width: _sc[0], height: _sc[1]});
                        })
                    }else
                    {
                        resizeStage({width: _sc[0], height: _sc[1]});
                    }

                } catch (err) {
                    throw  'json error'
                }
                if (Global.PackageJson.ver != AppCfg.ICWVersion) {
                    commands.showPop(commands.getErrorMsg(2018))
                    return;
                }
                createPages();
                updateStage(0, 3);
            } else {
                commands.showPop(commands.getErrorMsg(2006, 41), 2000);
            }
        });
    }

    /**
     * 找到页的内容
     * @param url
     * @param callback
     */
    function getSlideData(url, callback) {
        IO.readFile(url).done(function () {
            var a = JSON.parse(arguments[0]);
            if (a) {
                callback(a);
            }
        })
    }

    /**
     * 清空所有/重置
     */
    function resetSlide() {
        if (!Global.CurrentSlide) return;
        $('#pageArea_list').html('');
        $('#stageArea').html('');
//        EventBase.removeListener()
        Global.CurrentSlide.c.clear();
        delete  Global.CurrentSlide;
        $.each(Global.SlideArray, function (i) {
            delete  i;
        })
        Global.KeyLists = [];
        Global.SlideArray = [];
        Global.undos = [];
        commands.resetUndoBtn();
        Global.CurrentSlide = null;
        Global.isEditing = false;
        Global.isVariety = false;
        Global.isVarietyType = 0;
        Global.DefaultBackground = {src: null, color: null, repeat: false, use: false};
//        $('#background_use_all')[0].checked = false;
    }
    function clearGlobalDefind(){
        if(Global.CurrentSlide)
        {
            Global.CurrentSlide.c.clear();
        }
        Global.curStageJson = null;
    }

    /**
     * 保存当前的slide
     */
    function saveSlide(_callback, nowrite) {
        //setTimeout(function(){
        var data = Global.CurrentSlide.t.canvas[0];
        if (!nowrite && data.src.indexOf('data:image/png;') == 0) {
            try {
                var _url = commands.changeFolderToMedia(data.src, Global.CurrentSlide.c.getCurSlidePath()).replace(/\?.*/, '');
                IO.copyFile(_url, Global.CurrentSlide.c.getCurThumbPath()).done(function (err) {
                    if (err) {
                        console.log('保存缩略图成功！');
                    }
                })
            } catch (err) {

            }

        }

        var _slidejson = Global.CurrentSlide.c.toJSON();
        try {
            IO.writeFile(Global.CurrentSlide.c.getCurJsonPath(), _slidejson).done(function (err) {
                if (err) {
                    _callback && _callback();
                }
            });
        } catch (err) {
            throw  err
        }
    };

    //复制图片文件到media目录
    function copyImgToFolder(_src, _callback, _opt) {
        var _tosrc = commands.changeFolderToMedia(_src, _opt && _opt.to || null, _opt && _opt._en || null);
        if(_src==_tosrc)
        {
            _callback(_tosrc, _opt);
        }else
        {
            IO.copyFile(_src, _tosrc).done(function () {
                _callback(_tosrc, _opt);
            })
        }

    };

    //复制动态图文件
    function copyGifToFolder(_src, _callback, _opt){
        if(commands.getExtName(_src)[0] == ".gif"){
            var _to = _opt && _opt.to || null;
            var _en = _opt && _opt._en || null;
            var _srcPath = encodeURI(AppContext.joinPath(_src));
            _srcPath = decodeURI(_srcPath).replace('file:///', '');
            if (_en) {
                _srcPath = commands.changeFileName(_srcPath)
            }
            var widgetId = Global.CurrentSlide.c.NewWId("Gif");
            var wdir = AppContext.joinPath(_to || Global.CurrentSlide.c.getCurMediaPath(), widgetId);
            IO.mkdir(wdir).done(function () {
                var _gifSrc = AppContext.joinPath(wdir, _srcPath.substr(_srcPath.lastIndexOf('/'), _srcPath.length));
                IO.copyFile(_src, _gifSrc).done(function () {
                    _callback({"gifSrc":_gifSrc,"widgetId":widgetId}, _opt);
                });
            });
        }}

    /**
     * 取 url中package
     * @param val
     * @returns {*}
     * @constructor
     */
    function QueryUrlString(val) {
        var uri = window.location.search;
        var reg = new RegExp("" + val + "=([^&?]*)", "ig");
        return ((uri.match(reg)) ? (uri.match(reg)[0].substr(val.length + 1)) : null);
    }

    /**
     * 显示缩略图区滚动条
     */
    function showThumbScroll() {
        var _h = $('#page_thumb_items').height(), _t = $('#page_thumb_list');
        if (_h > _t.height()) {
            _t.css('overflow-y', 'scroll');
        } else {
            _t.css('overflow-y', 'hidden');
        }
    }

    /**
     * 托动排序完成
     */
    function pageSortEnd() {
        updateSortNumber();
        commands.setAppState('init', false);
        Global.isVariety = true;
        IO.writeFile(AppContext.getPackageJsonPath(), JSON.stringify(Global.PackageJson)).done(function (e) {
            commands.resetAppState();
        });
    }

    /**
     * 复制图片作为包的缩略图
     */
    function copyPakcageThumb(_callback) {

        var _src = AppContext.joinPath(AppContext.getCurSlidePackPath(), 'slides', Global.PackageJson.slides[0], 'thumb.jpg');
        var _tosrc = AppContext.getPackageThumbPath();
        IO.exists(_src).done(function (is) {
            if (is) {
                IO.copyFile(_src, _tosrc).done(function () {
                    _callback(_tosrc);
                })
            } else {
                _callback(_tosrc);
            }
        })

    }

    /**
     * 对多页进行背景设置
     * @param _slides   选择slides
     * @param _bg   图片
     * @param _bc   色
     * @param _repeat   平铺
     * @param _isf   是否覆盖当前
     */
    function setAllSlideBackground(_slides, _bg, _bc, _repeat, _isf) {
        var _cn = 0, num = _slides.length - 1;
        var _cur = Global.CurrentSlide.t.content.attr('id');
        var _curDefaultBG = {};
        for(var i in Global.DefaultBackground)
        {
            _curDefaultBG[i] = Global.DefaultBackground[i];
        }
        var __slides = [];
        /*if(_bc)
         {
         Global.DefaultBackground.src = null;
         Global.DefaultBackground.color = _bc;
         Global.DefaultBackground.repeat = false;
         }else if(_bg)
         {
         Global.DefaultBackground.src = decodeURI(AppContext.joinPath(_bg));
         Global.DefaultBackground.color = null;
         Global.DefaultBackground.repeat = false;
         }*/

        for (var c = _slides.length - 1; c >= 0; c--) {
            __slides.push(_slides[c]);
        }
        commands.showPop(commands.getErrorMsg(2023), null, true);
        function start() {
            var _callee = arguments.callee;
            var _slide = __slides[_cn].t || __slides[_cn];
            if(_bg){
                Global.DefaultBackground.use = true;
                Global.DefaultBackground.src = decodeURI(_bg);
                Global.DefaultBackground.color = null;
                Global.DefaultBackground.repeat = _repeat;
            }else if(_bc){
                Global.DefaultBackground.use = true;
                Global.DefaultBackground.src = null;
                Global.DefaultBackground.repeat = false;
                Global.DefaultBackground.color = _bc;
            }
            if (_cur == _slide.content.attr('id') && !_isf) {
                _isf && (Global.DefaultBackground = {src: null, color: null, repeat: false, use: false});
                updateStage(_slide, 2).done(function () {
                    saveSlide(function () {
                        if (++_cn <= num) {
                            setTimeout(_callee, 800);
                        } else {
                            commands.hidePop();
                            commands.resetAppState();
                        }
                    }, true);
                });
            } else {
                if (_bg) {
                    updateStage(_slide, 4).done(function () {
                        saveSlide(function () {
                            if (++_cn <= num) {
                                setTimeout(_callee, 800);
                            } else {
                                commands.hidePop();
                                commands.resetAppState();
                                _isf && (Global.DefaultBackground = _curDefaultBG);
                            }
                        }, true);
                    });
                } else if (_bc) {
                    updateStage(_slide, 4).done(function () {
                        saveSlide(function () {
                            if (++_cn <= num) {
                                setTimeout(_callee, 800);
                            } else {
                                commands.hidePop();
                                commands.resetAppState();
                                _isf && (Global.DefaultBackground = _curDefaultBG);
                            }
                        }, true);
                    });
                }
            }

        }

        setTimeout(start, 500);
    }

    // 自动更新
    setTimeout(function () {
        urlCheck.pingBaidu().done(function (ret) {
//            console.log("isOnline:" + ret);

            if (ret == false) {
                return;
            }

            updateCheck.checkUpdate().done(function (info) {
//                console.log("update info:" + info);

                // 没有更新
                if (info === "" || info == "0") {
                    return;
                }

                var tipMsg = "";
				var btn_ok = "";
				var btn_cancel = "";

                if (info == "1") {
                    tipMsg = '检测到有新版本，是否更新升级？'
					btn_ok = '是';
					btn_cancel = '否';

                }

                if (info == "2") {
                    tipMsg = '检测到有新版本，需要立即更新。'
					btn_ok = '同意';
					btn_cancel = '拒绝';
                }


                if ($('#modal_content_update_panel')) {
                    $('#modal_content_update_panel').remove();
                }

                // 用统一的弹出框有BUG...  还是这样靠谱
                var dlg = $('<div id="modal_content_update_panel" class="modal fade in" tabindex="-1" role="dialog"' +
                    'style="padding-top: 15%; overflow: hidden; display: block;" aria-hidden="false">' +
                    '<div class="pop_warp pop_tips">' +
                    '<div class="pop_tit"><span class="fl">温馨提示</span>' +
                    '<div class="w_func fr" id="btn_update_pop_close"><a href="javascript:;" title="关闭" class="w_func_close" data-dismiss="modal"></a>' +
                    '</div>' +
                    '</div>' +
                    '<div class="pop_con"><p class="pop_tips_con" >' + tipMsg + '</p></div>' +
                    '<div class="pop_btn_box t_center" id="pop_btns_box">' +
                    '<a href="javascript:void(0)" class="pop_btn" id="btn_update_yes"><span>'+btn_ok+'</span></a>' +
                    '<a href="javascript:void(0)" class="pop_btn" id="btn_update_not"><span>'+btn_cancel+'</span></a>' +
                    '</div>' +
                    '</div>' +
                    '</div>'
                );

                $('body').append(dlg);

                dlg.find('#btn_update_pop_close').bind('click', function () {
                    dlg.remove();
                    if (info == "2") {
                        commands.closeWindow();
                    }
                });

                dlg.find('#btn_update_yes').bind('click', function () {
                    dlg.remove();
                    appUtil.executeApp('.\\node_modules\\update\\upgrade\\bin\\AUC.exe');
                    setTimeout(function () {
                        commands.closeWindow();
                    }, 500);
                });

                dlg.find('#btn_update_not').bind('click', function () {
                    dlg.remove();
                    if (info == "2") {
                        commands.closeWindow();
                    }
                });
            });
        });
    }, 3000);

    // 检查桌面快捷方式
    //setTimeout(function () {
    //    // 判断软件第一次启动
    //    if (gui.App.argv[0] == 'true') {
    //        // 获取桌面路径
    //        var dpath = appUtil.getDesktopDir();
    //        // 是否有快捷方式
    //        var isShutcutHold = false;
    //
    //        // 遍历桌面 判读快捷方式是否存在
    //        var files = [];
    //        if (FS.existsSync(dpath)) {
    //            files = FS.readdirSync(dpath);
    //            for (var i = 0; i < files.length; i++) {
    //                if (files[i] == '畅言课件制作工具.lnk') {
    //                    isShutcutHold = true;
    //                    break;
    //                }
    //            }
    //        }
    //
    //        // 读配置文件判读是否 不在提示
    //        var binpath = AppContext.getBinPath();
    //        var innerBin = '';
    //        var dat_conf = binpath + '/dat';
    //        var isRemembed = false;
    //        if (FS.existsSync(dat_conf)) {
    //            var content = FS.readFileSync(dat_conf,'utf-8');
    //            try{
    //                var contentObj = JSON.parse(content);
    //                innerBin = contentObj['binPath'] + 'bin\\main';
    //                isRemembed = contentObj['isRemember'];
    //            }catch (error)
    //            {
    //               // throw  error
    //            }
    //        }
    //
    //        condition1 = isShutcutHold;                                     // 条件一：桌面是否存在快捷方式
    //        condition2 = isRemembed;                                        // 条件二：是否已勾选不再提示
    //        condition3 = (innerBin == '') && condition1;                                  // 条件三：说明程序是新下载的版本
    //        condition4 = (innerBin !='' &&innerBin != binpath);             // 条件四：说明程序被移动
    //
    //        //如果桌面没有 配置文件没有
    //        if ( (!condition1 && !condition2) || condition3 || condition4 ) {
    //            if ($('#modal_content_shortcut')) {
    //                $('#modal_content_shortcut').remove();
    //            }
    //            var tipContent = '';
    //            if(!condition1 && !condition2) {
    //                tipContent = '是否创建桌面快捷方式？';
    //            } else if(condition3) {
    //                tipContent = '您已下载新版本，需要重新创建快捷方式？';
    //            } else if(condition4) {
    //                tipContent = '您已移动程序位置，需要重新创建快捷方式';
    //            }
    //
    //            var dlg = $('<div id="modal_content_shortcut" class="modal fade in" tabindex="-1" role="dialog"' +
    //                'style="padding-top: 15%; overflow-x: hidden; display: block;" aria-hidden="false">' +
    //                '<div class="pop_warp pop_tips">' +
    //                '<div class="pop_tit"><span class="fl">温馨提示</span>' +
    //                '<div class="w_func fr" id="btn_shot_pop_close"><a href="javascript:;" title="关闭" class="w_func_close" data-dismiss="modal"></a>' +
    //                '</div>' +
    //                '</div>' +
    //                '<div class="pop_con"><p class="pop_tips_con" >' + tipContent + '</p></div>' +
    //                '<div class="pop_btn_box t_center" id="pop_btns_box">' +
    //                '<a href="javascript:void(0)" class="pop_btn" id="btn_shot_yes" style="margin-left:100px;"><span>是</span></a>' +
    //                '<a href="javascript:void(0)" class="pop_btn" id="btn_shot_not"><span>否</span></a>' +
    //                '<input type="checkbox" id="ck_not_pop" style="margin-left:20px;"/><span>不再提示</span>' +
    //                '</div>' +
    //                '</div>' +
    //                '</div>'
    //            );
    //
    //            $('body').append(dlg);
    //
    //            dlg.find('#btn_shot_pop_close').bind('click', function () {
    //                dlg.remove();
    //                binpath = binpath.substr(0, binpath.length - 8);
    //                var content = {'binPath':binpath,'isRemember':false};
    //                FS.writeFileSync(dat_conf, JSON.stringify(content));
    //            });
    //
    //            dlg.find('#btn_shot_yes').bind('click', function () {
    //                dlg.remove();
    //                binpath = binpath.substr(0, binpath.length - 8);
    //                var slide_exe_path = binpath + 'iFlySlide.exe';
    //                console.log(slide_exe_path);
    //                appUtil.createLink(slide_exe_path, dpath);
    //
    //                if (dlg.find('#ck_not_pop').prop('checked') == true) {
    //                    var content = {'binPath':binpath,'isRemember':true};
    //                    FS.writeFileSync(dat_conf, JSON.stringify(content));
    //                } else {
    //                    var content = {'binPath':binpath,'isRemember':false};
    //                    FS.writeFileSync(dat_conf, JSON.stringify(content));
    //                }
    //            });
    //
    //            dlg.find('#btn_shot_not').bind('click', function () {
    //                dlg.remove();
    //                binpath = binpath.substr(0, binpath.length - 8);
    //                if (dlg.find('#ck_not_pop').prop('checked') == true) {
    //                    var content = {'binPath':binpath,'isRemember':true};
    //                    FS.writeFileSync(dat_conf, JSON.stringify(content));
    //                } else {
    //                    var content = {'binPath':binpath,'isRemember':false};
    //                    FS.writeFileSync(dat_conf, JSON.stringify(content));
    //                }
    //            });
    //        }
    //    }
    //}, 2000);

//    // 每 30 秒
//    // 检测一下本地记录，有就上传
//    setTimeout(function(){
//        var _callee = arguments.callee;
//        urlCheck.pingBaidu().done(function(ret) {
//            console.log('editor check online ---- '+ret);
//            if(ret) {
//                LM.upLocalLog();
//            }
//        });
//        setTimeout(_callee,30000);
//    },30000);

    // 时常统计
    setTimeout(function(){
        LM.statisticsMoudleTime('4101','entry','open_close_time');
    },6000);

    // 统计使用课件次数
    setTimeout(function(){
        LM.statisticsMoudleTime('4102','trigger','open_count');
    },4000);

    init();

    // ----------------------------------------------------------------------
    // 课件崩溃恢复功能 写配置文件操作
    //    setTimeout(function () {
    //        var asf = AppContext.joinPath(AppContext.getCurSlidePackPath(), 'autosave.dat');
    //
    //        var autoSaveObj = {
    //            "packageName": paths.filename(AppContext.getCurSlidePackPath()),
    //            "event": "editing",
    //            "icwPath": ""
    //        };
    //
    //        if (gui.App.argv.length > 1 && paths.extname(gui.App.argv[1]) == '.icw') {
    //            autoSaveObj.icwPath = gui.App.argv[1];
    //        }
    //
    //        IO.writeFile(asf, JSON.stringify(autoSaveObj));
    //        console.log(JSON.stringify(autoSaveObj));
    //    }, 2000);
//    exports.updateStage = updateStage
});