configExtList=['.txt','.xc','.xml','.json'];
var modrecord;

var ModRecorder = function() {
    if (checkERROR(config.get("path"))) {
        return;
    }
    this.db = new Config(toPath(config.get("path") + "/res_mods/"+config.get("gameversion")+"/modrecord.db"));//保存在res_mods下
}
ModRecorder.prototype={
    //对文件列表进行判断，返回有问题的id列表
    testFileList: function(list){
        var result=new Object();
        for(var i in list){
            var res=this.testFile(list[i]);
            if(res==null||res==0){
                continue;
            }
            if(res==undefined){
                result['unknown']=1;
            }else{
                result[res.toString()]=1;
            }
        }
        return result;
    },
    //判断是否已有此文件
    testFile: function (file) {
        file=toPath(file);
        if(!checkERROR(this.db)){
            if(file in this.db.json){//有文件记录
                if(!fs.existsSync(file)){
                    //文件已不存在,状态改变
                    if(!checkERROR(modManager.getLocalMod(this.db[file]))){
                        if(modManager.getLocalMod(this.db[file]).state<2){
                            modManager.getLocalMod(this.db[file]).state=2;
                        }
                    }
                    modManager.db.update();
                    this.remove(file);
                    return null;
                }else{
                    if(!checkERROR(modManager.getLocalMod(this.db[file]))){
                        if(modManager.getLocalMod(this.db[file]).state<1){
                            modManager.getLocalMod(this.db[file]).state=1;
                        }
                    }
                }
                return this.db.get(file);
            }else if(fs.existsSync(file)){
                if(file.toLowerCase().indexOf('__init__')!=-1||file.toLowerCase().indexOf('cameranode')!=-1){
                    return null;
                }
                //未知文件
                return undefined;
            }
        }
        return null;
    },
    //更新记录
    updateRecord: function (file,modid){
        //跳过公用文件
        file=toPath(file);
        if(file.toLowerCase().indexOf('__init__')!=-1||file.toLowerCase().indexOf('cameranode')!=-1){
            return;
        }
        this.db.set(file,modid);
    },
    //获取需要删除的文件列表
    getUninstallFile: function(modid){
        var filelist=new Array();
        for(var i in this.db.json){
            if(this.db.get(i)==modid){
                filelist.push(i);
            }
        }
        return filelist;
    },
    //删除文件记录
    remove: function(file){
        this.db.remove(file);
    }
}

function toPath(filepath){
    return filepath.replace(/\\/g, "/").replace(/\/\//g, "/");
}
var ModManager = function () {
    this.db = null;
    this.jsonlist = null;
    this.minver = 0;
    this.loadLocalList();
}
ModManager.prototype = {
    //记录手动安装和沙盘安装的插件
    newModRecord: function (paths, modid, name, time) {    //保存位置, modid, 名称, 时间
        if (checkERROR(this.db.json.modlist)) {
            this.db.json.modlist = new Object();
        }
        if (checkERROR(modid)) {
            for (var i in this.db.json.modlist) {
                if (this.db.json.modlist[i].path==paths) {
                    modid = this.db.json.modlist[i].id;
                }
            }
        }
        //遍历寻找失败，赋默认值
        if (checkERROR(modid)) {
            modid = --this.minver;
        }
        this.db.json.modlist[modid.toString()] = {
            id: modid,
            path: paths,
            name: name,
            time: time,
            state: 1    //mod状态,0.未安装,1.已安装,2.文件不全
        };
        this.db.update();
        return modid;
    },
    getLocalMod: function(id){
        if(checkERROR(this.db.json)){
            return null;
        }
        if(checkERROR(this.db.json.modlist)){
            return null;
        }
        return this.db.json.modlist[id];
    },
    //读取本地的安装记录
    loadLocalList: function () {
        this.db = new Config("mod.db");
        for (var i in this.db.json.modlist) {
            if (i < this.minver) {
                this.minver = i;
            }
            if(checkERROR(this.db.json.modlist[i].state)){
                this.db.json.modlist[i].state=0;
            }
        }
    },
    getRemoteMod: function(id){
        if(checkERROR(this.jsonlist)){
            return null;
        }
        return this.jsonlist[id];
    },
    //读取服务器的插件列表
    loadRemoteList: function (callback) {
        //if(checkERROR(this.jsonlist)) {
            var ver=!checkERROR(config.get('gameversion'));
            $.get("http://rank.kongzhong.com/ModDownload/action/WowsModAction/modList"+(ver?'?ver='+config.get('gameversion'):''), function (data, status) {
                try {
                    var json=(data);
                    var change=(JSON.stringify(json).length!=JSON.stringify(modManager.jsonlist).length);
                    modManager.jsonlist = json;
                    if (typeof(callback) == "function") {
                        callback(change);
                    }
                }
                catch (e) {
                    console.log("getModList error", e);
                    customAlert("插件列表错误", "warning");
                }
            });
        /*}
        else{
            if (typeof(callback) == "function") {
                callback();
            }
        }*/
    },
    //下载插件
    downloadMod: function (id) {
        var mod = this.jsonlist[id];
        if (mod == null) {
            customAlert("选择的插件不存在", "warning");
            return;
        }
        var url = "http://rank.kongzhong.com/ModDownload/action/WowsModAction/download?modid="+mod.id+"&ver="+mod.ver;
        var savepath = "download_mods/["+mod.ver+"]" + mod.name+mod.ext;
        downloadCenter.add(url, savepath, mod.name, function (paths) {
            var id=getUniqueId();
            new CleverInstaller(id, mod.name, paths, "install",false,mod.id);
            modManager.newModRecord(paths, mod.id, "["+mod.ver+"]"+mod.name, id);
        });
    }
}

//更新插件列表
function refreshModList() {
    if (checkERROR(config.get("path"))){
        customAlert("未找到游戏路径，请先在沙盘设置中指定","danger","5000");
        return;
    }
    if(!checkNowPage("modlist",true)){
        return;
    }
    if ($("#modlist").html().length > 0) {
        $("#modlist").html("");
    }

    modrecord=new ModRecorder();
    $("#modlist").load("modlist.html #moddiv", function (data) {
        if(checkNowPage("modlist",false)){
            return;
        }
        modManager.loadRemoteList(function(change){
            if(change){
                checkNowPage("",true);
                refreshModList();
            }
        });
        if(checkERROR(modManager.jsonlist)){
            $("#moddiv").before('插件列表获取中，请等待');
            checkNowPage("",true)
            //setTimeout(function(){if(!checkNowPage("",false))refreshModList();},1500);
            return
        }
        modLayout();
        var l=config.get("defaultLayout");
        $(".modlayout").hide();
        if(l=="pic") {
            $("#modpiclayout").show();
        }else{
            $("#modlistlayout").show();
        }
        $("#moddiv").after('如果你对插件版权有异议，请在这里反馈<a style="color:red;" href="http://xvm.garphy.com/?p=10585">点击反馈</a>');
        // });
        $(".listlayout").click(function(){
            $(".modlayout").hide();
            $("#modlistlayout").show();
            config.set("defaultLayout","list");
            $("#modfilterBy").children(".filterbtn").click();
        });
        $(".piclayout").click(function(){
            $(".modlayout").hide();
            $("#modpiclayout").show();
            config.set("defaultLayout","pic");
            $("#modfilterBy").children(".filterbtn").click();
        });
    });
}

//mod排版
function modLayout(){
    var lasttime=modManager.db.get("lastTime");
    var now=getUniqueId();
    if(checkERROR(lasttime)){
        lasttime=getUniqueId();
    }
    if(now-lasttime>3600*1000) {
        modManager.db.set("lastTime", now);
    }
    var modlist=modManager.jsonlist;
    if (modlist == null) {
        return;
    }
    var tagslist=['#62c462','#4b9eb8','#b37724','#cc524e','#8a9299'];
    var modsort=new Object();
    for (var i in modlist) {
        var mod = modlist[i];
        if (mod == null||i==0) {
            continue;
        }
        var localmod=modManager.getLocalMod(mod.id);

        var bInstalled=0;      //0未安装,1已安装,2可更新
        if(!checkERROR(localmod)){
            if (localmod.updatetime < mod.updatetime) {
                bInstalled=2;
            }else{
                bInstalled=1;
            }
        }

        if(mod.sort==""){
            mod.sort="未分类";
        }
        if (mod.url != "") {
            var newer=false;
            if(lasttime<mod.updatetime){
                newer=true;
            }
            var d=new Date();
            d.setTime(mod.updatetime);
            //pic方式显示
            var info = '<div class="moddiv modpic panel panel-default"><div class="panel-heading modname"><h3 class="panel-title">' + mod.name+'<div class="pull-right">';
            info+=(newer?"<span style='color:red;'>New!</span>&nbsp;&nbsp;":"")+ (mod.good>0?'<i class="fa fa-thumbs-o-up"></i>&nbsp;&nbsp;':'')+(bInstalled==1?'<span class="label label-success">已安装</span>&nbsp;&nbsp;':'')+(bInstalled==2?'<span class="label label-info">可更新</span>&nbsp;&nbsp;':'');
            info+='</div></h3></div>';
            info+='<div class="panel-body">';
            info+='<div class="modimage"><img class="lazy" data-original="' + mod.image + '"></div>';
            info+='<div class="">' + date2str(d,"yyyy-MM-dd") + '</div>';
            info+='<div class="pull-right text-right">发布者:'+mod.publisher+'</div>';
            info+='<div class="">作者:' + mod.author + '</div>';
            info+='<div class="pull-right text-right">总下载:' + mod.down + '次</div>';
            info+='<div class="">分类:'+mod.sort+'</div>';
            info+='<div class="bottomright">'
            if(mod.config>0) {
                info += '<button type="button"  data-toggle="modal" data-target="#modModal" onclick="showConfigList('+mod.id+')" class="btn btn-sm btn-info modconfig">可选设置</button>&nbsp;&nbsp;';
            }
            info+='<button type="button" class="btn btn-sm btn-success modinstall">'+(bInstalled==2?'更新插件':'下载安装')+'</button></div>';
            info+='<div class="hide url">' + mod.url + '</div>';
            info+='<div class="hide sort">' + mod.sort + '</div>';
            info+='<div class="hide id">' + mod.id + '</div></div>';
            info+='</div>'
            $("#modpiclayout").append(info);

            //list方式显示
            var tr = "<tr onmousemove='showImage(\"" + mod.image
                + "\",\""+mod.description+"\")' onmouseout='hideImage()' class='moddiv modtr' id='" + mod.id + "'>";
            tr += "<td class='name stext'>"+ mod.name +"<div class='pull-right'>"+(newer?"&nbsp;&nbsp;<span style='color:red;'>New!</span>":"")+(bInstalled==1?'<span class="label label-success">已安装</span>&nbsp;&nbsp;':'')+(bInstalled==2?'<span class="label label-info">可更新</span>&nbsp;&nbsp;':'')+(mod.good>0?'<i class="fa fa-thumbs-o-up"></i>':'')+  "</div></td>";
            tr += "<td class='sort stext'>" + mod.sort + "</td>";
            tr += "<td class='stext'>" + mod.author + "</td>";
            tr += "<td class='stext'>" + mod.down + "</td>";
            tr += '<td class="stext">'+date2str(d,"yyyy-MM-dd hh:mm:ss")+'</td>';
            tr += '<td><button type="button" class="btn btn-sm btn-default moddetail" data-toggle="modal" data-target="#modModal">查看详情</button>&nbsp;&nbsp;<button type="button" class="btn btn-sm btn-success modinstall">'+(bInstalled==2?'更新插件':'下载安装')+'</button>&nbsp;&nbsp;';
            if(mod.config>0) {
                tr += '<button type="button"  data-toggle="modal" data-target="#modModal" onclick="showConfigList('+mod.id+')" class="btn btn-sm btn-info modconfig">可选设置</button>&nbsp;&nbsp;';
            }
            tr += '</td>';
            tr += '<td class="hide id">' + mod.id + '</td>';
            tr += "</tr>";
            $("#modbody").append(tr);
            if(mod.sort in modsort){
                modsort[mod.sort]++;
            }else{
                modsort[mod.sort]=1;
            }
        }
    }
    $("img.lazy").lazyload({
        effect : "slideDown",
        threshold: -50
    });
    if($("#modbody").children().length>0){
        $("table#modtable").tablesorter({
            sortInitialOrder : "desc",
            sortList : [ [ 4, 1 ] ]
        });
        $("#modfilterBy").children(".btn").children(".badge").text($("#modbody").children().length);
    }
    for (var sort in modsort){
        var button="<button type='button' class='btn btn-sm filterbtn btn-default'>"+sort+"&nbsp;<span class='badge'>"+modsort[sort]+"</span></button>";
        $("#modsortType").append(button);
    }
    //筛选按钮
    $(".filterbtn").click(function(){
        $(".modlayout:visible").find(".moddiv").show();
        var s=$(this).html().split("&nbsp;")[0];
        $(".moddiv:visible").each(function(i,n){
            if(s!="全部"){
                if($(n).find(".sort").text()!=s){
                    $(n).hide();
                }
            }
        });
        $("#modsortType").append($("#modfilterBy").children(".filterbtn"));
        $("#modfilterBy").append(this);
    });
    $(".moddetail").click(function(){
        var id=$(this).parent().parent().attr("id");
        $("#modbody").children(".active").removeClass("active");
        $(this).parent().parent().addClass("active");
        updateDetail(modManager.getRemoteMod(id));
    });

    $("button.modconfig").click(function(){
        var id = $(this).parent().parent().children(".id").text();
        openConfigList(id);
    });
    $("button.modinstall").click(function (i, e) {
        if (checkERROR(config.get('path'))) {
            customAlert("未找到游戏路径，请先设置", 'warning');
            return;
        }
        console.log("install:" + $(this).parent().parent().children(".id").text());
        modManager.downloadMod($(this).parent().parent().children(".id").text());
    });
}

function refreshModDelList() {  //安装记录列表
    checkNowPage("moddel",true);
    if ($("#modlist").html().length > 0) {
        $("#modlist").html("");
    }
    modrecord=new ModRecorder();
    $("#modlist").load("modtable.html #modtable", function (data) {
        if(checkNowPage("moddel",false)){
            return;
        }
        for (var i in modManager.db.json.modlist) {
            var mod = modManager.db.json.modlist[i.toString()];
            var remotemod=modManager.getRemoteMod(i);
            if(mod==null){
                continue;
            }
            var d=new Date();
            d.setTime(mod.time);
            var image='';
            var desc='';
            if(!checkERROR(remotemod)){
                image=remotemod.image;
                desc=remotemod.description;
            }
            var info = "<tr onmousemove='showImage(\"" + image + "\",\""+desc+"\")' onmouseout='hideImage()' id='mod" + mod.id + "'><td class='stext'><input class='modcheckbox' type='checkbox'></td><td class='tablename stext'><span>" + mod.name + "</span></td><td class='time stext'>" + date2str(d,"yyyy-MM-dd hh:mm:ss") + "</td><td class='modopr'><button type='button' class='btn btn-sm btn-primary modifyconfig'  data-toggle='modal' data-target='#modModal'>自定设置</button>&nbsp;&nbsp;<button type='button' class='btn btn-sm btn-success update'>更新插件</button>&nbsp;&nbsp;<button type='button' class='btn btn-sm btn-info install'>重安装插件</button>&nbsp;&nbsp;<button type='button' class='btn btn-sm btn-warning del'>卸载插件</button>&nbsp;&nbsp;<button type='button' class='btn btn-sm btn-danger remove' title='"+mod.path+"'><i class='fa fa-times'></i></button></td><td class='hide path'>" + mod.path + "</td></tr>";
            $("#modbody").append(info);

            //显示插件状态
            if(!checkERROR(mod.state)) {
                if (mod.state == 0) {
                    $("#mod" + mod.id).children('.tablename').append("&nbsp;<span class='label label-warning pull-right'>未安装</span>&nbsp;");
                } else if (mod.state == 1) {
                    $("#mod" + mod.id).children('.tablename').append("&nbsp;<span class='label label-success pull-right'>已安装</span>&nbsp;");
                    $("#mod" + mod.id).children(".modopr").children(".remove").addClass('disabled');
                } else if (mod.state == 2) {
                    $("#mod" + mod.id).children('.tablename').append("&nbsp;<span class='label label-warning pull-right'>不完整</span>&nbsp;");
                    $("#mod" + mod.id).children(".modopr").children(".remove").addClass('disabled');
                }
            }
            //存在这个id且时间比本地的大
            if(!checkERROR(remotemod)){
                if(remotemod.updatetime>mod.time){
                    $("#mod" + mod.id).children('.tablename').append("&nbsp;<span class='label label-info pull-right'>有更新</span>&nbsp;");
                }else{
                    $("#mod" + mod.id).children(".modopr").children(".update").addClass('disabled');
                }
                if(remotemod.config>0){
                    $("#mod"+mod.id).children(".modopr").prepend('<button type="button" data-toggle="modal" data-target="#modModal" onclick="showConfigList('+mod.id+')" class="btn btn-sm btn-default modconfig">可选设置</button>&nbsp;&nbsp;');
                }
            }else{
                $("#mod" + mod.id).children(".modopr").children(".update").addClass('disabled');
            }
            var exists=fs.existsSync(mod.path);
            if (!exists) {
                $("#mod" + mod.id).children(".modopr").children(".install").addClass('disabled');
                $("#mod" + mod.id).children(".modopr").children(".del").addClass('disabled');
                $("#mod" + mod.id).children(".modopr").children(".modifyconfig").addClass('disabled');
                $("#mod" + mod.id).children(".modopr").attr("title", "文件不存在");
                $("#mod" + mod.id).children(".modopr").children(".remove").removeClass('disabled');
                $("#mod" + mod.id).children(".modopr").children(".update").removeClass('disabled');
            }
            if($("#modbody").children().length>0){
                $("table#modtab").tablesorter({
                    sortInitialOrder : "desc",
                    sortList : [ [ 2, 1 ] ]
                });
            }
        }
        //特别设置
        $("#configconfig").click(function(){
            var paths=config.get("notepadPath");
            if(checkERROR(paths)){
                paths="";
            }
            var div='<div class="modal-dialog">';
            div+='<div class="modal-content">';
            div+='<div class="modal-header">';
            div+='<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>';
            div+='<h4 class="modal-title" id="myModalLabel">文本编辑器路径设置</h4></div>';
            div+='<div class="modal-body">';
            div+='<label for="path" class="control-label">文本编辑器路径</label>';
            div+='<div class="input-group">';
            div+='<input type="text" class="form-control" id="path" value="'+paths+'">';
            div+='<span class="input-group-btn">';
            div+='<button type="button" class="btn btn-default" style="display:none;" id="custompath">保存路径</button>';
            div+='<button type="button" class="btn btn-default" id="configpath">设置路径</button>';
            div+='</span></div>';
            div+='</div>';
            div+='</div></div>';
            $("#modModal").html(div);
            $("#path").change(function(){
                $("#custompath").show();
                $("#configpath").hide();
            });
            $("#custompath").click(function(){
                config.set("notepadPath",$("#path").val());
                customAlert("文本编辑器路径设置为"+$("#path").val(),"success");
                $("#custompath").hide();
            });
            $("#configpath").click(function(){
                console.log("configpath");
                chooseFile(function(paths){
                    var p=unescape(paths);
                    customAlert("文本编辑器路径设置为"+p,"success");
                    config.set("notepadPath",p);
                    $("#path").val(p);
                });
            })
        });

        $("button.modconfig").click(function(){
            var id = $(this).parent().parent().attr('id').split('mod')[1];
            openConfigList(id);
        });

        //自己修改配置
        $("button.modifyconfig").click(function(){
            var name = $(this).parent().parent().children(".tablename").children('span').first().text();
            var paths = $(this).parent().parent().children(".path").text();
            var fname=getFileName(paths);
            if(fname.lastIndexOf(".")!=-1) {
                var ext = fname.substr(fname.lastIndexOf("."));
                var func = null;
                if (ext.toLowerCase() == ".zip" || ext.toLowerCase() == ".wbp") {
                    func = listZip;
                } else if (ext.toLowerCase() == ".rar") {
                    func = listRar;
                } else if (ext.toLowerCase() == ".7z") {
                    func = list7z;
                } else {
                    customAlert("不支持的压缩包格式");
                }
                if (typeof(func) == "function") {
                    func(paths,function (list) {
                        var configlist=[];
                        for(var i in list){
                            var file=list[i].trim();
                            var idx=file.lastIndexOf('.')
                            if(file.indexOf("res_mods")!=-1&&idx!=-1&&idx> file.length-6&&idx< file.length-2){
                                var ext= file.substr(file.lastIndexOf('.'));
                                for (var x in configExtList){
                                    var c=configExtList[x];
                                    if(ext==c){
                                        var realpath=config.get("path")+"/res_mods"+file.split("res_mods")[1];
                                        if(fs.existsSync(realpath)){
                                            configlist.push(realpath);
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                        showCustomConfig(configlist);
                    })
                }
            }
        });
        $("button.update").click(function () {
            var name = $(this).parent().parent().children(".tablename").children('span').first().text();
            var paths = $(this).parent().parent().children(".path").text();
            var id = $(this).parent().parent().attr('id').split('mod')[1];
            //customConfirm("更新插件: " + name, function () {
                console.log("update", name);
                modManager.downloadMod(id);
                $("#mod" + id).children('.tablename').children('.label').remove();
                $("#mod" + id).children('.tablename').append("&nbsp;<span class='label label-success pull-right'>已安装</span>&nbsp;");
            //});
            if(!checkNowPage("moddel",false)){
                refreshModDelList();
            }
        });

        $("button.install").click(function () {
            var name = $(this).parent().parent().children(".tablename").children('span').first().text();
            var paths = $(this).parent().parent().children(".path").text();
            var id = $(this).parent().parent().attr('id').split('mod')[1];
            //customConfirm("重新安装插件: " + name, function () {
                console.log("reinstall", name);
                new CleverInstaller(getUniqueId(), name, paths, 'install',false,id);
                modManager.getLocalMod(id).state=1;
                modManager.db.update();
                $("#mod" + id).children('.tablename').children('.label').remove();
                $("#mod" + id).children('.tablename').append("&nbsp;<span class='label label-success pull-right'>已安装</span>&nbsp;");
            //});
            if(!checkNowPage("moddel",false)){
                refreshModDelList();
            }
        });
        $("button.del").click(function () {
            var name = $(this).parent().parent().children(".tablename").children('span').first().text();
            var paths = $(this).parent().parent().children(".path").text();
            var id = $(this).parent().parent().attr('id').split('mod')[1];
            //customConfirm("即将卸载插件: " + name, function () {
                console.log("del", name);
                new CleverInstaller(getUniqueId(), name, paths, 'delete',true,id);
                modManager.getLocalMod(id).state=0;
                modManager.db.update();
                $("#mod" + id).children('.tablename').children('.label').remove();
                $("#mod" + id).children('.tablename').append("&nbsp;<span class='label label-warning pull-right'>未安装</span>&nbsp;");
            //});
            if(!checkNowPage("moddel",false)){
                refreshModDelList();
            }
        });
        $("button.remove").click(function () {
            var name = $(this).parent().parent().children(".tablename").children('span').first().text();
            var paths = $(this).parent().parent().children(".path").text();
            var id = $(this).parent().parent().attr('id').split('mod')[1];
            //customConfirm("即将删除记录: " + name, function () {
                console.log("remove", name);
                delete modManager.db.json.modlist[id];
                modManager.db.update();
                $("#mod" + id).remove();
            //});
        });
        $("button.updateall").click(function(){
            //close the refresh func
            checkNowPage("moddelall",true);
            $(".modcheckbox:checked").each(function(){
                if(!$(this).parent().parent().children(".modopr").children("button.update").hasClass("disabled")) {
                    $(this).parent().parent().children(".modopr").children("button.update").click();
                }
            });
            checkNowPage("moddel",true);
        });
        $("button.reinstallall").click(function(){
            //close the refresh func
            checkNowPage("moddelall",true);
            $(".modcheckbox:checked").each(function(){
                if(!$(this).parent().parent().children(".modopr").children("button.install").hasClass("disabled")) {
                    $(this).parent().parent().children(".modopr").children("button.install").click();
                }
            });
            checkNowPage("moddel",true);
        });
        $("button.deleteall").click(function(){
            //close the refresh func
            checkNowPage("moddelall",true);
            $(".modcheckbox:checked").each(function(){
                if(!$(this).parent().parent().children(".modopr").children("button.del").hasClass("disabled")) {
                    $(this).parent().parent().children(".modopr").children("button.del").click();
                }
            });
            checkNowPage("moddel",true);
        });
        $("button.clearall").click(function(){
            customConfirm("确定要删除全部插件文件?",function(){
                var modpath=config.get('path')+"/res_mods";
                deleteFolderRecursive(modpath,1);
            });
        });
        $("button.configall").click(function(){
            var configlist=listFolderRecursive(config.get('path')+"/res_mods/"+config.get("gameversion"));
            configlist=configlist.concat(listFolderRecursive(config.get('path')+"/res_mods/xvm"));
            if(checkERROR(configlist)){
                return
            }
            var list=[];
            for (var i in configlist){
                var y=configlist[i].trim();
                var idx=y.lastIndexOf('.')
                if(idx!=-1&&idx> y.length-6&&idx< y.length-2){
                    var ext= y.substr(y.lastIndexOf('.'));
                    for (var x in configExtList){
                        var c=configExtList[x];
                        if(ext==c){
                            list.push(y);
                            console.log(y);
                            break;
                        }
                    }
                }
            }
            showCustomConfig(list);
        });
        $("button.checkall").click(function(){
            if($(":checkbox").size()==$(":checkbox[checked='checked']").size()){
                $(":checkbox").each(function(){
                    $(this).attr("checked",false);
                });
            }else{
                $(":checkbox").each(function(i,n){
                    $(this).attr("checked",true);
                    $(n)[0].checked="checked";
                });
            }
        });
        $("button.removeall").click(function(){
            $(".modcheckbox:checked").each(function(){
                if(!$(this).parent().parent().children(".modopr").children("button.remove").hasClass("disabled")) {
                    $(this).parent().parent().children(".modopr").children("button.remove").click();
                }
            });
        });
    });
}

//自定设置
function showCustomConfig(configlist){
    var pattern;
    var patterninit=false;
    if(fs.existsSync("apps/index/configPattern.json")){
        try {
            var data = fs.readFileSync("apps/index/configPattern.json", 'utf8');
            pattern = JSON.parse(data);
            patterninit = true;
        }catch(e){
            console.log("pattern error", e);
        }
    }else{
        console.log("no pattern file");
    }
    var div='<div class="modal-dialog modal-lg">';
    div+='<div class="modal-content">';
    div+='<div class="modal-header">';
    div+='<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>';
    div+='<h4 class="modal-title" id="myModalLabel">'+name+'设置文件列表</h4></div>';
    div+='<div class="modal-body">';
    if(configlist.length==0){
        div+="<div>找不到可进行设置的文件</div>";
    }else{
        div+='<div>点击链接将打开设置文件</div>';
        for(var i in configlist){
            var filepath=configlist[i];
            var alias='res_mods'+filepath.split("res_mods")[1];
            if(patterninit){
                for(var i in pattern){
                    if(alias.indexOf(i)!=-1){
                        alias=pattern[i];
                        break;
                    }
                }
            }
            var fname=getFileName(filepath);
            div+='<div><a href="#" class="configfile" path="'+filepath+'">'+fname+'<span class="pull-right">&nbsp;'+alias+'</span></a></div>';
        }
    }
    div+='</div>';
    div+='</div></div>';
    $("#modModal").html(div);
    $(".configfile").click(function(){
        var file=$(this).attr("path");
        var notepadPath=config.get("notepadPath");
        if(checkERROR(notepadPath)||notepadPath==""){
            notepadPath="notepad.exe";
        }
        cp.spawn(notepadPath,[file]);
    });
}

function updateDetail(detail){
    if(checkERROR(detail)){
        return;
    }
    var div='<div class="modal-dialog">';
    div+='<div class="modal-content">';
    div+='<div class="modal-header">';
    div+='<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>';
    div+='<h4 class="modal-title" id="myModalLabel">'+detail.name+'</h4></div>';
    div+='<div class="modal-body">';
    div+='<button type="button" class="btn btn-success modinstall" data-dismiss="modal" id="modalinstall">下载安装</button>&nbsp;&nbsp;';
    if(detail.config>0) {
        div += '<button type="button" onclick="window.open(\'configlist.html?modid='+detail.id+'\',\'_blank\')" class="btn btn-info modconfig">查看配置</button>&nbsp;&nbsp;';
    }
    div+='</div>';
    div+='<div class="modal-footer">';
    div+="<p class='sort'>分类:\t"+detail.sort+"</p>";
    div+="<p>原作者:\t"+detail.author+"</p>";
    div+="<p>发布者:\t"+detail.publisher+"</p>";
    div+="<p>下载量:\t"+detail.down+"</p>";
    var d = new Date();
    d.setTime(detail.updatetime);
    div+="<p>更新时间:\t"+date2str(d,"yyyy-MM-dd hh:mm:ss")+"</p>";
    div+="<p>"+detail.description+"</p>";
    div+="<img class='middleimg' src='" + detail.image + "'>";
    div+='</div>';
    div+='</div></div>';
    $("#modModal").html(div);

    $("#modalinstall").click(function (i, e) {
        if (checkERROR(config.get('path'))) {
            customAlert("未找到游戏路径，请先设置", 'warning');
            return;
        }
        console.log("install:" + detail.url);
        modManager.downloadMod(detail.id);
    });
    $("button.modconfig").click(function(){
        var id = detail.id;
        openConfigList(id);
    });
}

var imageout=false;
function showImage(img,desc) {
    if(img!=""){
        imageout=false;
        var top =0;
        var left=0;
        if(window.innerHeight-event.clientY>350) {
            top = event.clientY - 200;
        }else{
            top=window.innerHeight-550;
        }
        if(window.innerWidth-event.clientX>550) {
            left = event.clientX - 200;
        }else{
            left=window.innerWidth-1150;
        }
        if($("#a1").find("img.lazy").first().attr('data-original')==img){
            $("#a1").css("top", document.body.scrollTop + top-92);
            $("#a1").css("left", document.body.scrollLeft + left);
            $("#a1").show();
        }else {
            var id = getUniqueId();
            var t1 = "<div style='margin: 0 auto 0 auto'><img id='img" + id + "' class='lazy middleimg' data-original='" + img + "'></div><div >" + desc + "</div>";
            $("#a1").html(t1);
            $("#a1").css("top", document.body.scrollTop + top-92);
            $("#a1").css("left", document.body.scrollLeft + left);
            $("#a1").show();
            setTimeout(function () {
                $('#img' + id).lazyload({
                    effect: "fadeIn"
                });
            }, 200);
        }
    }
}
function hideImage() {
    imageout=true;
    setTimeout(function () {
        if(imageout) {
            $("#a1").hide();
        }
    }, 200);
}

function openConfigList(id){

}

modManager = new ModManager();