$(function(){

    window.SendSoftMessage = function(cmd, param){
        console.info(cmd, param);
        try{
            if(cmd == "newGroup"){
                var id = new Date().getTime().toString(16);
                p = JSON.parse(param);
                var pid = currFirstId;
                if(p.id){
                    var $obj = $("#" + p.type + "-" + p.id);
                    pid = $obj.data("pid") || currFirstId;
                }
                layer.open({
                    type: 1,
                    title: '新建分组',
                    shadeClose: false,
                    shade: 0.6,
                    maxmin: false,
                    area: ['350px', '160px'],
                    content: utils.formatByJson(document.querySelector("#newGroupTpl").innerHTML, {
                        id: id, type: p.type, action: "new", value: "", gid: "", pid: pid
                    })
                });
            } else if(cmd == "editGroup"){
                var id = new Date().getTime().toString(16);
                p = JSON.parse(param);
                var $obj = $("#" + p.type + "-" + p.id);
                var value = $obj.text();
                var pid = $obj.data("pid") || currFirstId;
                layer.open({
                    type: 1,
                    title: '修改分组',
                    shadeClose: false,
                    shade: 0.6,
                    maxmin: false,
                    area: ['350px', '160px'],
                    content: utils.formatByJson(document.querySelector("#newGroupTpl").innerHTML, {
                        id: id, type: p.type, action: "edit", value: value, gid: p.id, pid: pid
                    })
                });
            } else if(cmd == "delGroup"){
                var p = JSON.parse(param);
                var value = $("#" + p.type + "-" + p.id).text();
                layer.confirm('您确定要删除分组【'+value+'】吗？<br>将会同时删除分组下所有项目，请谨慎操作！', {
                    btn: ['确定删除','不了'],
                    title: "警告",
                    icon: 7
                }, function(){
                    SendSoftMessage("delGroupSubmit", param);
                    layer.closeAll();
                }, function(){
                    layer.msg("已取消");
                });
            } else if(cmd == "editSoft"){
                if(currFirstId && currSecondId){
                    var appId = param;
                    var name = $("#soft-"+appId+" .title").text();
                    var img = $("#soft-"+appId+" img").attr("src");
                    window['_editapp'] = {
                        id: appId, parentId: currSecondId,
                        name: name,
                        src: img
                    };
                    var w = $(window).width();
                    var h = $(window).height();
                    layer.open({
                        type: 2,
                        title: '启动属性',
                        shadeClose: false,
                        shade: 0.6,
                        maxmin: false,
                        area: [(w < 400 ? w-20 : 400)+'px', (h < 430 ? h - 20 : 430)+'px'],
                        content: 'startboot.html'
                    });
                }
            } else if(cmd == "delSoft"){          
                var appId = param;
                var value = $("#soft-" + appId + " .title").text();
                layer.confirm('您确定要删除【'+value+'】吗？', {
                    btn: ['确定删除','不了'],
                    title: "警告",
                    icon: 7
                }, function(){
                    SendSoftMessage("delSoftSubmit", "" + appId);
                    layer.closeAll();
                }, function(){
                    layer.msg("已取消");
                });
            } else if(cmd == "newItem"){          
                if(currFirstId && currSecondId){
                    window['_editapp'] = {
                        id: appId, parentId: currSecondId,
                        name: name,
                        src: img
                    };
                    var w = $(window).width();
                    var h = $(window).height();
                    layer.open({
                        type: 2,
                        title: '新增项目',
                        shadeClose: false,
                        shade: 0.6,
                        maxmin: false,
                        area: [(w < 400 ? w-20 : 400)+'px', (h < 430 ? h - 20 : 430)+'px'],
                        content: 'startboot.html'
                    });
                }
            } else if(cmd == "sortUse"){          
                if(currFirstId && currSecondId){
                    owlssky_soft("sortUse", JSON.stringify({
                        "fid": currFirstId, "sid": currSecondId
                    }));
                }
            } else if(cmd == "login"){
                var w = $(window).width();
                var h = $(window).height();
                layer.open({
                    type: 2,
                    title: '用户登录',
                    shadeClose: false,
                    shade: 0.6,
                    maxmin: false,
                    area: [(w < 400 ? w-20 : 400)+'px', (h < 390 ? h - 20 : 390)+'px'],
                    content: 'login.html'
                });
            } else if(cmd == "setting" || cmd == "about"){
                $("#func_set").click();
            } else if(cmd == "reload"){
                document.location.reload();
            } else if(cmd == "setSkin"){
                owlssky_soft(cmd, param);
            } else if(cmd == "vip"){
                $("#func_vip").click();
            } else if(cmd == "changePwd"){
                var w = $(window).width();
                var h = $(window).height();
                layer.open({
                    type: 2,
                    title: '修改密码',
                    shadeClose: false,
                    shade: 0.6,
                    maxmin: false,
                    area: [(w < 400 ? w-20 : 400)+'px', (h < 390 ? h - 20 : 390)+'px'],
                    content: 'changepassword.html'
                });
            } else {
                if(window['owlssky_soft']){
                    try{
                        owlssky_soft(cmd, param);
                        if(cmd == "runApp" && !!OwlConfig.autoUseOrder){
                            SendSoftMessage("sortUse", ""); 
                        }
                    }catch(ex){
                        console.error(ex.message);
                    }           
                }
            }
        }catch(ex){
            console.error(ex.message);
        }
    };

    window['_call_server'] = function(cmd, param){
        if(window['owlssky_call']){
            owlssky_call(cmd, param);
        }        
    };

    window.desktop = new YXDesktop($("#box"));
    window.currFirstId = 0;
    window.currSecondId = 0;
    window.leftBox = new PanelMenu({
        "body": $("#menu-box"),
        "type": "f"
    });
    window.topBox = new PanelMenu({
        "body": $("#top"),
        "type": "t"
    });
    window.SysBox = new SysMenu({
        "body": $(".sysbtn.menu")
    });

    window.showFirst = function(arr){
        var apps = [];
        for(var i = 0; i < arr.length; i++){
            apps.push(arr[i]);
        }
        apps.sort((a, b)=>{ return a.order - b.order; });
        var tpl = document.getElementById("firsttpl").innerHTML;
        var list = [];
        currFirstId = 0;
        for(var i = 0; i < apps.length; i++){            
            var html = utils.formatByJson(tpl, {
                "id": apps[i].id,
                "title": apps[i].title,
                "set": apps[i].setting,
                "order": i,
                "active": currFirstId == 0 && apps[i].active ? "active" : ""
            });
            if(apps[i].active){
                currFirstId = apps[i].id;
            }
            list.push(html);
        };
        $("#menu-box").html(list.join(''));
        if(currFirstId == 0 && apps.length){
            currFirstId = apps[0].id;
            $("#f-" + currFirstId).addClass("active");
        }
        if(apps.length && currFirstId){            
            SendSoftMessage("load", JSON.stringify({"level": 2, "id": currFirstId}));
        }
    };

    window.addFirst = function(app){
        layer.closeAll();
        currFirstId = app.id;
        $("#menu-box .menu-item").removeClass("active");
        var tpl = document.getElementById("firsttpl").innerHTML;
        var html = utils.formatByJson(tpl, {
            "id": app.id,
            "title": app.title,
            "set": app.setting,
            "order": $("#menu-box .menu-item").length,
            "active": "active"
        });
        $("#menu-box").prepend(html);
        if(currFirstId){
            SendSoftMessage("load", JSON.stringify({"level": 2, "id": currFirstId}));
        }        
    };

    window.showSecond = function(arr, pid){
        var apps = [];
        for(var i = 0; i < arr.length; i++){
            apps.push(arr[i]);
        };
        apps.sort((a, b)=>{ return a.order - b.order; });
        var tpl = document.getElementById("secondtpl").innerHTML;
        var list = [];       
        currSecondId = 0; 
        for(var i = 0; i < apps.length; i++){                     
            var html = utils.formatByJson(tpl, {
                "id": apps[i].id,
                "title": apps[i].title,
                "parentId": apps[i].parentId,
                "set": apps[i].setting,
                "order": i,
                "active": currSecondId == 0 && apps[i].active ? "active" : ""
            });
            if(apps[i].active){
                currSecondId = apps[i].id;
            } 
            list.push(html);
        };
        $("#top").html(list.join(''));
        if(currSecondId == 0 && apps.length){
            currSecondId = apps[0].id;
            $("#t-" + currSecondId).addClass("active");
        }        
        if(apps.length && currSecondId){
            var w = (list.length + 1) * 90;
            SendSoftMessage("load", JSON.stringify({"level": 3, "id": currSecondId, "width": w}));
        } 
    };

    window.addSecond = function(app){
        layer.closeAll();
        currSecondId = app.id;
        $("#top .menu-item").removeClass("active");
        var tpl = document.getElementById("secondtpl").innerHTML;
        var html = utils.formatByJson(tpl, {
            "id": app.id,
            "title": app.title,
            "parentId": app.parentId,
            "set": app.setting,
            "order": $("#top .menu-item").length,
            "active": "active"
        });
        $("#top").append(html);
        var w = ($("#top .menu-item").length + 1) * 90;
        SendSoftMessage("load", JSON.stringify({"level": 3, "id": currSecondId, "width": w}));
    };

    window.showApps = function(arr, pid){
        desktop.clear();
        var apps = [];
        for(var i = 0; i < arr.length; i++){
            apps.push(arr[i]);
        };
        apps.sort((a, b)=>{ return a.order - b.order; });
        var order = 0;
        for(var i = 0; i < apps.length; i++){
            var soft = new SoftItem({
                "id": apps[i].id,
                "parentId": apps[i].parentId,
                "title": apps[i].title,
                "order": order++,
                "type": apps[i].type,
                "icon": apps[i].icon,
                "setting": apps[i].setting,
                "desc": utils.unicode4ToAnsi(apps[i].cmd)
            });
            desktop.addApp(soft);
        };
    };

    window.insertApp = function(app){
        var soft = new SoftItem({
            "id": app.id,
            "parentId": app.parentId,
            "title": app.title,
            "order": $("#box .soft-item").length,
            "type": app.type,
            "icon": app.icon,
            "setting": app.setting
        });
        desktop.addApp(soft);
    };

    window.updateApp = function(app){
        var $soft = $("#soft-" + app.id);
        $soft.find("img").attr("src", utils.unicode4ToAnsi(app.icon));
        $soft.find(".title").text(utils.unicode4ToAnsi(app.title));
    };

    window.removeApp = function(id){
        desktop.removeApp(id);
    };

    window.removeGroup = function(id, type){
        $("#" + type + "-" + id).remove();
        document.location.reload();
    };

    window.dragapps = function(arr){
        var apps = [];
        for(var i = 0; i < arr.length; i++){
            apps.push(arr[i]);
        }
        for(var i = 0; i < apps.length; i++){
            parent.SendSoftMessage("saveItemSubmit", JSON.stringify({
                "name": apps[i].name, 
                "type": apps[i].type, 
                "path": apps[i].path, 
                "icon": apps[i].icon, 
                "args": "", 
                "parentId": currSecondId
            }));
        }        
    };

    // first
    var firstDatas = [];
    firstDatas.push({
        "id": 1,
        "order": 2,
        "title": "精品推荐",
        "parentId": 0,
        "setting": "sys",
        "active": true
    });
    firstDatas.push({
        "id": 2,
        "order": 1,
        "title": "系统工具",
        "setting": "sys",
        "parentId": 0
    });
    showFirst(firstDatas);

    // second
    var secondDatas = [];
    secondDatas.push({
        id: 3,
        "order": 1,
        title: "常用",
        "setting": "sys",
        parentId: 1
    });
    secondDatas.push({
        id: 4,
        "order": 1,
        title: "常用",
        "setting": "sys",
        parentId: 2
    });
    showSecond(secondDatas, 2);

    // apps
    var appDatas = [];
    appDatas.push({
        "id": 5,
        "parentId": 3,
        "order": 1,
        "title": "Owlssky",
        "type": 'url',
        "setting": "sys",
        "path": "http://www.owlssky.com",
        "icon": "icons/owlssky.ico",
        "desc": "Owlssky-给每个账号创建一个专属浏览器环境"
    });

    appDatas.push({
        "id": 6,
        "parentId": 3,
        "order": 2,
        "title": "办公神器",
        "type": 'url',
        "setting": "sys",
        "path": "http://da.yinsin.net",
        "icon": "icons/da.png",
        "desc": "办公神器-神器在手，天下我有"
    });
    showApps(appDatas);

    //new Function().constructor('debugger').apply('action')

    window.showImportWait = function(flag){
        if(!!flag){
            $(".waitting").show();
        } else {
            $(".waitting").hide();
        }
    };

    $("#func_set").on("click", function(){
        var w = $(window).width();
        var h = $(window).height();
        layer.open({
            type: 2,
            title: '软件设置',
            shadeClose: false,
            shade: 0.6,
            maxmin: false,
            area: [(w)+'px', (h)+'px'],
            content: 'setting.html'
        });
    });

    $("#func_search").on("click", function(){
        showSearchPanel();
    });

    $("#func_vip").on("click", function(){
        if(!!window.user){
            var w = $(window).width();
            var h = $(window).height();
            layer.open({
                type: 2,
                title: '我的VIP服务',
                shadeClose: false,
                shade: 0.6,
                maxmin: false,
                area: [(w < 540 ? w : 540) + 'px', (h < 300 ? w : 300) + 'px'],
                content: 'vips.html'
            });
        } else {
            SendSoftMessage("login", "");
        }        
    });

    $("#menu-box").on("click", ".menu-item", function(){
        var that = $(this);
        if(!that.hasClass("active")){
            $("#menu-box .menu-item").removeClass("active");
            that.addClass("active");
            var id = that.data("id");
            if(currFirstId != id){
                currFirstId = id;
                currSecondId = 0;
                SendSoftMessage("load", JSON.stringify({"level": 2, "id": id, "way": "hand"}));
            }
        }        
    });

    ///hoverChange
    $("#menu-box").on("mouseover", ".menu-item", function(){
        if(!!OwlConfig.hoverChange || window.selected){
            var that = $(this);
            if(!that.hasClass("active")){
                $("#menu-box .menu-item").removeClass("active");
                that.addClass("active");
                var id = that.data("id");
                if(currFirstId != id){
                    currFirstId = id;
                    currSecondId = 0;
                    SendSoftMessage("load", JSON.stringify({"level": 2, "id": id, "way": "hand"}));
                }
            }
        }        
    });       

    $("#top").on("click", ".menu-item", function(){
        $("#top .menu-item").removeClass("active");
        var that = $(this);
        that.addClass("active");
        var id = that.data("id");
        if(currSecondId != id){
            currSecondId = id;
            SendSoftMessage("load", JSON.stringify({"level": 3, "id": id}));
        }
    });

    ///hoverChange
    $("#top").on("mouseover", ".menu-item", function(){
        if(!!OwlConfig.hoverChange || window.selected){
            var that = $(this);
            if(!that.hasClass("active")){
                $("#top .menu-item").removeClass("active");
                that.addClass("active");
                var id = that.data("id");
                if(currSecondId != id){
                    currSecondId = id;
                    SendSoftMessage("load", JSON.stringify({"level": 3, "id": id}));
                }
            }
        }        
    });

    $("body").on("click", ".btn.btn-add", function(){
        var $btn = $(this);
        var id = $btn.data("id");
        var name = $("#n" + id).val();
        var value = $("#n" + id).data("value");
        var gid = $("#n" + id).data("gid") || 0;
        if(name){
            if(value == name){
                layer.closeAll();
                layer.msg("未变化");
                return;
            }
            var type = $btn.data("type");
            var action = $btn.data("action");
            var pid = $btn.data("pid");
            name = utils.ansiToUnicode4(name);
            SendSoftMessage("newGroupSubmit", JSON.stringify({
                "id": gid, "type": type, "name": name, "action": action, "pid": pid
            }));
            if(action == "edit" && gid) {
                $("#" + type + "-" + gid).text($("#n" + id).val());
                layer.closeAll();
            }
        } else {
            layer.msg("请输入分组名称");    
        }
    });

    $("body").on("click", ".btn.btn-cancel", function(){
        layer.closeAll();
        layer.msg("已取消");
    });

    var leftSelected = null, topSelected = null;
    var leftTemp = null, topTemp = null;
    $("#menu-box").on("mousedown", ".menu-item", function(){
        var that = $(this);
        var id = that.attr("id");
        if(parseInt(id.substring(2)) > 50){
            leftSelected = that;
        }        
    });
    $("#top").on("mousedown", ".menu-item", function(){
        var that = $(this);
        var id = that.attr("id");
        if(parseInt(id.substring(2)) > 50){
            topSelected = that;
        } 
    });

    $("body").on("mousemove", function(e){
        if(!!leftSelected){
            if(leftTemp == null){
                leftTemp = leftSelected.clone();
                leftTemp.css({"position": "absolute", "z-index": 10000});
                $("body").append(leftTemp);
            }
            leftTemp.css({"left": e.clientX + 3, "top": e.clientY + 3});
        } else if(!!topSelected){
            if(topTemp == null){
                topTemp = topSelected.clone();
                topTemp.css({"position": "absolute", "z-index": 10000});
                $("body").append(topTemp);
            }
            topTemp.css({"left": e.clientX + 3, "top": e.clientY + 3});
        }
    });
    $("body").on("mouseup", function(e){
        if(!!leftSelected){
            var target = $(e.target);
            var tid = target.attr("id");
            var fid = leftSelected.attr("id");
            if(tid != fid && tid.indexOf("f-") != -1 && parseInt(tid.substring(2)) > 50){
                if(leftSelected.position().top > target.position().top){
                    leftSelected.insertBefore(target);
                } else {
                    target.insertBefore(leftSelected);
                }
                var trd = target.data("order");
                var frd = leftSelected.data("order");
                SendSoftMessage("sortGroup", JSON.stringify({
                    "type": 1,
                    "tid": tid, "fid": fid, "tor": frd, "for": trd
                })); 
            }          
        }
        if(!!topSelected){
            var target = $(e.target);
            var tid = target.attr("id");
            var fid = topSelected.attr("id");
            if(tid != fid && tid.indexOf("t-") != -1 && parseInt(tid.substring(2)) > 50){
                if(topSelected.position().left > target.position().left){
                    topSelected.insertBefore(target);
                } else {
                    target.insertBefore(topSelected);
                }
                var trd = target.data("order");
                var frd = topSelected.data("order");
                SendSoftMessage("sortGroup", JSON.stringify({
                    "type": 2,
                    "tid": tid, "fid": fid, "tor": frd, "for": trd
                })); 
            }
        }
        try{
            leftTemp.remove();
        }catch(e1){}
        try{
            topTemp.remove();
        }catch(e2){} 
        leftTemp = null;
        topTemp = null;
        topSelected = null;
        leftSelected = null;
    });

    $(".sysbtn.close").on("click", function(){
        SendSoftMessage("close", "");        
    });

    $(".sysbtn.skin").on("click", function(){
        var w = $(window).width();
        var h = $(window).height();
        layer.open({
            type: 2,
            title: '软件设置',
            shadeClose: false,
            shade: 0.6,
            maxmin: false,
            area: [(w)+'px', (h)+'px'],
            content: 'setting.html#skin'
        });
    });

    $("body").on('mousemove', function(e){
        if(window.selected){
            if(!window.selectSoft){
                window.selectSoft = window.selected.copy();
                window.selectSoft.on("mouseup", function(){
                    window.selected = null;
                    window.selectSoft.remove();
                    window.selectSoft = null;
                });
            } else {
                window.selectSoft.css({
                    "display": "block",
                    "left": e.clientX + 3, 
                    "top": e.clientY + 3
                });
            }                    
        }
    });

    window.reload = function(){
        SendSoftMessage("load", JSON.stringify({"level": 3, "id": currSecondId}));
    };

    window['OwlConfig'] = {};
    window._getConfig = function(cfg){
        console.info(JSON.stringify(cfg));
        window['OwlConfig'] = cfg;
        if(cfg.skinType && cfg.skinValue){
            setSkin(cfg.skinType, cfg.skinValue);
        }
        
    };

    window.setSkin = function(type, value){
        if(type == 'color'){
            $("#main").css("background", "#" + value);
        } else if(type == 'image'){
            $("#main").css("background", "url('" + value + "')");
        } else if(type == 'url'){
            $("#main").css("background", "url('" + value + "')");
        }
        OwlConfig.skinType = type;
        OwlConfig.skinValue = value;
    };

    var rechargeLayer = 0;
    window.showRecharge = function(vip){
        var w = $(window).width();
        var h = $(window).height();
        var vipName = "";
        if(vip == "cplus"){
            vipName= '【ChromePlus】';
        }
        rechargeLayer = layer.open({
            type: 2,
            title: '购买VIP服务' + vipName,
            shadeClose: false,
            shade: 0.6,
            maxmin: false,
            area: [w + 'px', h + 'px'],
            content: "recharge_" + vip + ".html"
        });
    };

    window.closeRecharge = function(){
        layer.close(rechargeLayer);
    };

    $(window).on("resize", function(){
        control.orderApp();
    });

    var notkeys = ',8,9,13,16,17,18,20,91,';
    var searchLayer = 0;
    $(document).on("keydown", function(e){
        var kcode = e.keyCode;
        if(e.altKey || e.ctrlKey || e.shiftKey || e.metaKey){
            if(e.altKey && kcode >= 48 && kcode <= 57){

            }
            return;
        }        
        if(notkeys.indexOf(','+kcode+',') == -1 && !!OwlConfig.anysearch){
            var iframe = document.querySelector(".layui-layer");
            if(!!iframe){
                return;
            };
            showSearchPanel();
        }
    });

    function showSearchPanel(){
        if(searchLayer > 0){
            layer.close(searchLayer);
        }
        var w = $(window).width();
        var h = $(window).height();
        searchLayer = layer.open({
            type: 2,
            title: '搜索',
            shadeClose: false,
            shade: 0.6,
            maxmin: false,
            area: [(w)+'px', (h)+'px'],
            content: 'search.html'
        });
    }
    
    var readynum = 0;
    var readyInter = setInterval(function(){
        if(!!window['readyed'] || readynum > 50){
            clearInterval(readyInter);
            readynum = 0;
        } else {
            SendSoftMessage("ready", "");
        }
        readynum++;
    }, 100);

    window.ready = function(){
        window['readyed'] = true;
        clearInterval(readyInter);
        SendSoftMessage("loadcfg", "");
        SendSoftMessage("load", JSON.stringify({"level": 1, "id": 0}));
        _call_server("toauginlo", "");
        setTimeout(function(){
            SendSoftMessage("lur", "");
        }, 5000);
    };

    setInterval(function(){
        if(window['owlssky_soft']){
            var iframe = document.querySelector(".layui-layer");
            owlssky_soft("fiexd", iframe ? "true": "false");
        }        
    }, 100);
});