var update=0;
var baseurl="apps\\";
var dossier=new Object();
var version;
var tanksjson;
var mapsjson;
var gui = require('nw.gui'); 
var win = gui.Window.get();
//win.maximize();
gui.App.setCrashDumpDir("dump\\");
gui.App.clearCache();
var nowpage="";
$(document).ready(function() {
	//检测更新补丁
	getPatchList(examinePatch);
	//启动监控程序
	//wowpStart();
    setInterval(monitorStart, 30000);
    setInterval(replayStart, 30000);
	//显示新闻
	newsPage();
    checkVersion();
    //获取插件更新
    modManager.loadRemoteList(function(){
        //对当前列表进行对比
        var canupdate=0;
        var unread=0;
        var cantitle="";
        var unreadtitle="";
        var lt=modManager.db.get("lastTime");
        for(var i in modManager.jsonlist){
            if(i=="0"){
                continue;
            }
            var mod=modManager.jsonlist[i];
            if(!checkERROR(modManager.db.json.modlist))
                var localmod=modManager.getLocalMod(i);
                if(!checkERROR(localmod)) {
                    if (localmod.time < mod.time) {
                        canupdate++;
                        cantitle+=mod.name+"\n";
                    }
                }
            if(!checkERROR(lt)&&lt<mod.time){
                unread++;
                unreadtitle+=mod.name+"\n";
            }
        }
        if(unread>0) {
            var ur = '&nbsp;<span class="badge btn-info" title="'+unread+'个新插件\n'+unreadtitle+'" id="unread">' + unread + '</span>';
            $("#unread").attr('title',unread+'个新插件\n'+unreadtitle);
            $("#unread").text(unread);
            $("#unread").show();
        }
        if(canupdate>0) {
            var cu = '&nbsp;<span class="badge" title="'+canupdate+'个可更新插件\n'+cantitle+'" id="canupdate">' + canupdate + '</span>';
            $("#canupdate").attr('title',canupdate+'个可更新\n'+cantitle);
            $("#canupdate").text(canupdate);
            $("#canupdate").show();
        }
    });
    //插件包初始化
    assembleManager.initList();
    //配置列表初始化
    configManager.loadRemoteConfig();

	$("#begin").remove();
	$("#tanks").load("..\\dossier\\tanks.json",function(data){
        try {
            tanksjson = JSON.parse(data);
        }catch(e){
            console.log(e);
            customAlert("加载坦克失败","warning");
        }
	});
	
	$("#maps").load("..\\dossier\\maps.json",function(data){
        try {
            mapsjson = JSON.parse(data);
        }catch(e){
            customAlert("加载坦克失败","warning");
        }
	});
	//页面按钮地址初始化
	$("#modlistbutton").click(function(){
		modPage();
	});
	$("#tanknewsbutton").click(function(){
		newsPage();
	});
	$("#battlestatbutton").click(function(){
		battlePage();
	});
	$("#playerbutton").click(function(){
		playerPage();
	});
	$("#configbutton").click(function(){
		configPage();
		//customPath();
	});
    $("#tankinspectorbutton").click(function(){
        inspectorPage();
    });
	$("#startgamebutton").click(function(){
		startgame();
	});
	$("#replaySimbutton").click(function() {
        if (fs.existsSync("apps/replaySim/index.html")) {
            window.open("../replaySim/index.html");
        }
        else {
            customAlert("请安装录像模拟器补丁", 'warning');
        }
    });
	$("#replaybutton").click(function(){
		changePage();
        $("#replaypage").show();
        replayList();
		$("#replaybutton").parent().addClass("active");
	});
	$("#msgbutton").click(function(){
		msgPage();
	});
	$('#search').click(function(){
		console.log($('#searchbar').val());
		console.log($('#searchzone').val());
		if ($('#searchbar').val().trim()!=''){
			var name=$('#searchbar').val();
			var zone='';
			if($(this).text()=='北区'){
				zone='north';
			}else {
				zone='south';
			}
			window.open('http://rank.kongzhong.com/index.html?name='+name+'&area='+zone,'_blank');
		}
	});	
	window.setTimeout(function() {

		if(nowpage==""){//无页面操作
			battlePage();
		}else{
            showRecentBattles(false);
        }
	}, 15000);
	$('.dropdown-menu').children('li').children('a').click(function(){
		$(this).parent().parent().parent().children('button:first').text($(this).text());
	});
	$("#minibutton").click(function(){min2tray();});
//	$("#wowpicon").click(function(){
//		changeApp("wowp\\index.html",'wowp',false);
//	});
    deleteFolderRecursive(cleverInstallDirname,0);
    $("#count").load('count.html #countindex');
    $('body').mousewheel(function(event, delta) {
        if(delta!=0){
            var imageHeight=$("#bodybackground").height();
            var winHeight=window.innerHeight;
            var top=$(this).scrollTop();
            var offset=top;
            if(offset>imageHeight-winHeight){
                offset=imageHeight-winHeight;
            }
            $("#bodybackground").css('top',-offset);
        }
    });
    if(!fs.existsSync("apps/index/css/wotbg.png")){
        $("#bodybackground").remove();
    }
});
//启动游戏
function startgame(){
	if (checkERROR(config.get('path'))){
		customAlert("请先设置游戏路径",'warning');
		return;
	}
    if(fs.existsSync(config.get('path')+"\\wotLauncher.exe")) {
        cp.spawn(config.get('path') + "\\wotLauncher.exe");
    }else{
        customAlert("<font style='color:red'>启动文件"+config.get('path')+"\\WOTLauncher.exe</font>不存在","danger");
    }
}

function newsPage(){
	changePage();
	newsList();
    $("#newspage").show();
	$("#tanknewsbutton").parent().addClass("active");
}

//实时效率页面
function battlePage(){
	changePage();
    showRecentBattles();
	$("#battlepage").show();
	$("#battlestatbutton").parent().addClass("active");
}

//效率分析页面
function playerPage(){
	changePage();
    $("#playerpage").show();
	playerlist();
	$("#playerbutton").parent().addClass("active");
}
//装甲密档页面
function inspectorPage(){
    changePage();
    $("#inspectorpage").show();
    inspectorShow();
    $("#tankinspectorbutton").parent().addClass("active");
}
//配置页面
function configPage(){
	changePage();
    $("#configpage").show();
	refreshConfig();
	$("#configbutton").parent().addClass("active");
}

//消息盒子页面
function msgPage(){
	changePage();
	$("#messagepage").show();
	message.read();
}

//插件页面
function modPage(){
	changePage();
	if ($("#modpage").html().length>0){
		$("#modpage").html("");
	}
	$("#modpage").load("mod.html #nav",function(data){
        $("#modassemblebutton").click(function(){
            //切换active
            $(this).parent().parent().children(".active").removeClass("active");
            $(this).parent().addClass("active");
            assembleManager.initHtml();//assemble.js
        });
		$("#modinstallbutton").click(function(){
			//切换active
			$(this).parent().parent().children(".active").removeClass("active");
			$(this).parent().addClass("active");
            refreshModList();//mod.js
		});
        $("#paintinstallbutton").click(function(){
            //切换active
            $(this).parent().parent().children(".active").removeClass("active");
            $(this).parent().addClass("active");
            refreshPaintList();//paint.js
        });
		$("#moddeletebutton").click(function(){
			//切换active
			$(this).parent().parent().children(".active").removeClass("active");
			$(this).parent().addClass("active");
            refreshModDelList();//mod.js
		});
        $("#modbakbutton").click(function(){
            //切换active
            $(this).parent().parent().children(".active").removeClass("active");
            $(this).parent().addClass("active");
            modbakpage();
        })
		$("#modclever").click(function(){
			//切换active
			$(this).parent().parent().children(".active").removeClass("active");
			$(this).parent().addClass("active");
            cleverinstallpage();
		})
		$("#modpage").append("<div id='modlist'></div>");
        $("#count").load('count.html #countmod');
        $("#modinstallbutton").click();
        $("#modpage").show();
		//统计页
	});
	$("#modlistbutton").parent().addClass("active");
}
function togglemenu(){
	if($('#menu').css("display")=="none"){
		$('#wrapper').css('padding-left',225);
		$("#togglemenu").html('<i class="fa fa-caret-square-o-left fa-fw"></i>')
	}else{
		$('#wrapper').css('padding-left',0);
		$("#togglemenu").html('<i class="fa fa-caret-square-o-right fa-fw"></i>')
	}
	$('#menu').toggle();

}
//切换页面的预动作
function changePage(){
	$(".index").hide();
	$("#menu .active").removeClass("active");
	clearInterval(showRecentBattles);
}

function checkNowPage(page,update){
    if (nowpage==page){
        return false;
    }else{
        if (update) {
            nowpage = page
        }
        return true;
    }
}
