/*
 *	main.js
 *  主框架核心功能脚本
 *  创建：zhaoshunlu@163.com 
 *  维护：zhaoshunlu@163.com 2014-08-25 获取指定ID的选项卡重新加载URL ReLoadTab() 
 */
mini.parse();
var menuTree = mini.get("leftTree");            //左侧树形导航菜单
var tabs = mini.get("mainTabs");            //主选项卡控件，所有业务窗口都可以停靠于此
var mainLayout = mini.get("mainLayout");
var mainSplitter = mini.get("mainSplitter"); 

var currentTab = null;                      //主选项卡控件当前选中的选项卡
// -- 
var global_Query = 600000;                  //设置每多少毫秒请求一次服务器（循环调用 CheckOnLine() 获取用户在线信息及业务消息），默认600000毫秒 = 10分钟 
var bShowOnLineUser = false;                //bShowOnLineUser 是否加载显示在线用户，在主框架"在线"选项卡显示，默认false不显示  

//-在线计时相关开始--------
var ap_name = navigator.appName;
var ap_vinfo = navigator.appVersion;
var ap_ver = parseFloat(ap_vinfo.substring(0, ap_vinfo.indexOf('(')));
var time_start = new Date();
var clock_start = time_start.getTime();
var dl_ok = false;
function initTime() {
    if (ap_name == "Netscape" && ap_ver >= 3.0)
        dl_ok = true;
    return true;
}
function get_time_spent() {
    var time_now = new Date();
    return ((time_now.getTime() - clock_start) / 1000);
}
function show_secs() {
    var i_total_secs = Math.round(get_time_spent());
    var i_secs_spent = i_total_secs % 60;
    var i_mins_spent = Math.round((i_total_secs - 30) / 60);
    var s_secs_spent = "" + ((i_secs_spent > 9) ? i_secs_spent : "0" + i_secs_spent);
    var s_mins_spent = "" + ((i_mins_spent > 9) ? i_mins_spent : "0" + i_mins_spent);
    document.getElementById("time_spent").innerHTML = s_mins_spent + ":" + s_secs_spent;
    window.setTimeout('show_secs()', 1000);
}
//-在线计时相关结束--------

var CanSet = false; //能否设置Cookies
window.onload = function () {

    var skin = mini.Cookie.get("miniuiSkin");
    if (skin) {
        var selectSkin = document.getElementById("selectSkin");
        if (selectSkin) selectSkin.value = skin;
    }
    CanSet = true;
    //--登录在线计时
    initTime();
    window.setTimeout('show_secs()', 1);
    //-- 
    //获取用户登录信息
    GetUserData(function (e) {
        $("#spanUserName").html(e.UserName); 
        GetAuthor(""); 
        AddDockTab('mydesk', 'icon-desktop', '我的桌面', 'desk.html');
        //按 global_Query 设定的频率检查是否超时
        CheckOnLine();
    });
}
 
//树型节点选择事件
menuTree.on("nodeclick", function (e) {
    if (e.node.url && e.node.url != "") {
        AddDockTab(e.node.id, e.node.iconCls, e.node.text, e.node.url);
    }
});

//注销退出
function onLogOut() {
    mini.confirm("确定要退出系统吗？", "确定？",
            function (action) {
                if (action == "ok") {
                    $.ajax({
                        url: "../Service/_AdminLoginService.ashx?method=Logout",
                        cache: false,
                        success: function (text) {
                            location.href = "../index.html";
                        }
                    });
                }
            }
        );
 }
 //掉线重新登录框
 var g_OpenReLoginWindow = false;
 var g_ReLoginWindowID;
 var g_TargetWindow;
 //显示重新登录窗口
 function ReLoginWindow(win) {
     if (g_OpenReLoginWindow == true) { return; }
     g_TargetWindow = win;
     g_OpenReLoginWindow = true;
     g_ReLoginWindowID = mini.open({
         url: "relogin.html",
         title: "重新登录",
         width: 280,
         height: 200,
         showModal: true,
         allowResize: false,
         onload: function () { },
         ondestroy: function (action) {
             var result = mini.decode(action);
             if (result.action == "success") {
                 //登录成功
                 var breload = false;                 
                if ( g_TargetWindow) {
                    g_TargetWindow.location.reload();
                }
             }
             g_OpenReLoginWindow = false;
             g_TargetWindow = null;
         }
     });
 }
 
//主界面首次加载时 获取用户登录信息及加载界面
 function GetUserData(fun) {    
    $.ajax({
        url: "../Service/_AdminLoginService.ashx?method=GetUserData&rnd=" + Math.random(),
        cache: false,
        success: function (text) {           
            var o = mini.decode(text);
            if (!o.error) {                           
                if (arguments.length=1 && typeof fun =="function") {                 
                    return fun(o);
                }
            } else {
                //打开重新登录窗口               
                ReLoginWindow();
            }
        }
    });
}
function CheckUserData(win,pageInfo,fun) {
    $.ajax({
        url: "../Service/_AdminLoginService.ashx?method=GetUserData&rnd=" + Math.random(),
        cache: false,
        success: function (text) {
            var o = mini.decode(text);
            if (!o.error) {
                if (arguments.length = 1 && typeof fun == "function") {
                    return fun(o);
                }
            } else {
                //打开重新登录窗口               
                ReLoginWindow();
            }
        }
    });
}
//按设定的时间频率 循环调用 CheckOnLine() 获取用户在线信息
var timer_out; //超时定时器
var IsGoChk = true;
      
//检查用户在线信息
function CheckOnLine() {    
    var bShowUsers = (bShowOnLineUser == true || bShowOnLineUser == "true") ? "true" : "false";
    $.ajax({
        url: "../Service/_AdminLoginService.ashx?method=GetOnLineUser&showuser=" + bShowUsers, //检查是否超时
        cache: false,
        success: function (text) {
            //
            var result = mini.decode(text);
            if (result.LoginState == false) {
                //防止一直弹出超时错误提示
                IsGoChk = false;
                clearTimeout(timer_out); //清除定时器
               //
                ReLoginWindow();
            } else {
                //在线
            }
        }
    });
    if (IsGoChk) {
        timer_out = setTimeout("CheckOnLine()", global_Query); //global_Query默认每10分钟查询一次
    }
}

//获取授权信息
function GetAuthor(CompanyCode) {
    CompanyCode="_default";
    var surl =  "../CommonData/" + CompanyCode + "/adornment.txt";
    $.ajax({
        url: surl,
        success: function (text) {
            var result = mini.decode(text);
            $("#divHeaderAd").css("backgroundImage", "url(" + result.headerLogo.url + ")");
            $("body").css("backgroundImage", "url(" + result.headerGround.url + ")");
            $("body").css("backgroundRepeat", "no-repeat");
        },
        error: function (jqXHR, textStatus, errorThrown) {
            mini.alert("异常:" + jqXHR.responseText);
        }
    });
    $.ajax({
        url: "../CommonData/" + CompanyCode + "/Authorization.txt",
        cache: false,
        success: function (text) {
            var result = mini.decode(text);
            //            

            if (result.ShowMakerOnHelp) Global_debugger = (result.ShowMakerOnHelp == "true") ? true : false; //是否显示页面作者，方便页面出问题时找责任人
            if (result.ShowOnLineUser) bShowOnLineUser = (result.ShowOnLineUser == "true") ? true : false;   //是否加载显示在线用户，在主框架"在线"选项卡显示        
            if (result.WebTitle && result.WebTitle != "") document.title = result.WebTitle;  //网站标题
            $("#spanCopyRight").html(result.Warrant);
            $("#spanBrowse").html(result.Browser);
            $("#spanLastUpdate").html(result.Ver + " " + result.LastUpdate);

            //
            //开始超时计时
            //放在这里才调用CheckOnLine()是为了等待获取bShowOnLineUser设置是否加载显示在线用户           
            CheckOnLine();
        }
    });
    //
}
//获取主框架工具栏导航按钮
function GetSysMenuToolBar() {
    $.ajax({
        url: "../Service/_AdminLoginService.ashx?method=GetSysMenuToolBar&rnd=" + Math.random(),
        data: {},
        cache: true,
        success: function (text) {
            var o = mini.decode(text);
            if (typeof o.error == "undefined") {
                //菜单项
                var menus = o.MenuItems;
                var str = "";
                for (var i = 0; i < menus.length; i++) {
                    var btn = menus[i];
                    var icon = btn.iconCls.replace("icon-", "");
                    str += "<a class=\"mini-button textcss\" plain=\"true\"";
                    str += " iconcls=\"" + btn.iconCls + "\"";
                    str += " onclick=\"AddDockTab('" + btn.id + "','" + btn.iconCls + "','" + btn.text + "','" + btn.url + "')\""
                    str += " >" + btn.text + "</a> ";
                    //str += "<a class=\"mini-button mini-button-plan\" href=\"javascript:void()\"";
                }
                //
                $("#mainToolbarMenu>a:nth-child(2)").after(str); //插入新节点 
                mini.parse();

                //默认首页            
                if (o.DefaultPage != null && o.DefaultPage != "null" && o.DefaultPage != "") {
                    var strpage = o.DefaultPage;
                    var i = strpage.indexOf("|");
                    if (i > 0) {
                        var items = strpage.split("|");
                        AddDockTab(items[0], items[1], items[2], items[3]);
                    } else {
                        AddDockTab("mydesk", "icon-desktop", "默认首页", strpage);
                    }
                } else {
                    AddDockTab("mydesk", "icon-desktop", "我的桌面", "desk.html");
                } 

            } else {
                mini.alert("获取导航按钮错误：" + text);
            }
        }
    });
}

//打开修改密码窗口 zhao 2014-09-17
function openPwdChgDlg() {
    mini.open({
        url: "../AdminEditPwd.html?autoclose=1",
        title: "修改密码",
        width: 600,
        height: 430,
        showMaxButton: false,
        showCloseButton: false,
        showModal: true,
        allowResize: true,
        allowDrag: true,
        onload: function () { },
        ondestroy: function (action) { 
                //如果主窗口还没加载系统菜单，就刷新主窗口
                //获取系统菜单第3个按钮，如果是帮助按钮，说明还没加载系统菜单  
                var helpnode = $("#mainToolbarMenu>a:nth-child(3)").first();
                if (helpnode) {
                    var text = helpnode.text();
                    if (text.indexOf("帮助") > 0) {
                        breload = true;
                        window.location.reload();
                    }
                } 
        }
    });
}
//查看用户信息
//zhao 2014-09-11
//参数UserCode    用户编码
//参数CompanyCode 公司编码
//参数UserName    用户名称
//调用：OpenUserView("00001002");或OpenUserView(null,"00001","张国强")
function OpenUserView(UserCode, CompanyCode, UserName) {
    //
    var querys = (UserCode && UserCode != "") ? "?action=read&id=" + UserCode : "?action=read&companycode=" + CompanyCode + "&username=" + escape(UserName);
    mini.open({
        url: "../AdminView.html" + querys,
        title: "查看用户信息",
        width: 600,
        height: 460,
        showMaxButton: true,
        showToolbar: false,
        showFooter: true,
        showModal: true,
        allowResize: true,
        allowDrag: true
    });
}
function onClick(e) {
    var text = this.getText();
    mini.alert(text);
}


//皮肤切换
function onSkinChange(skin) {
    mini.Cookie.set('miniuiSkin', skin);
    window.location.reload();
}
function onBeforeOpen(e) {
    currentTab = tabs.getTabByEvent(e.htmlEvent);
    if (!currentTab) {
        e.cancel = true;
    }
}
///////////////////////////
//关闭选项卡相关方法
function closeTab() {
    tabs.removeTab(currentTab);
}
function closeAllBut() {
    tabs.removeAll(currentTab);
}
function closeAll() {
    tabs.removeAll();
}
function closeAllButFirst() {
    var but = [currentTab];
    but.push(tabs.getTab("first"));
    tabs.removeAll(but);
}
//添加选项卡
//维护：zhao 2014-08-26 增加返回参数，判断是否已经存在指定ID的tab
function AddDockTab(id, icon, text, url) {
    var bHas = false;
    var tabs = mini.get("mainTabs");
    var tabid = "tab$" + id;
    var tab = tabs.getTab(tabid);
    if (!tab) {
        tab = {};
        tab.name = tabid;
        tab.title = text;
        tab.showCloseButton = true;
        tab.iconCls = icon;
        if (tabid == "tab$mydesk") {
            tab.bodyStyle = "background-color:#ffffff;";
        } else {
            tab.bodyStyle = "background-color:#ffffff;";
        }
        //这里拼接了url，实际项目，应该从后台直接获得完整的url地址
        tab.url = url;
        tabs.addTab(tab);
    } else {
        bHas = true; //是否已经存在
    }
    tabs.activeTab(tab);
    //alert("AddDockTab");
    //alert(tabs.getTabIFrameEl(tab));
    //if (text == "资源设置") {
    //    if (mainSplitter.getPane(1).expanded)
    //        mainSplitter.collapsePane(1);
    //}
    return bHas;
}
//获取指定ID的选项卡内部窗口
//创建 zhao 2014-08-26
function ReLoadTab(tabId, url) {
    var tabs = mini.get("mainTabs");
    var m_tabId = "tab$" + tabId;
    var tab = tabs.getTab(m_tabId);
    if (tab) {
        tabs.loadTab(url, tab);
        //alert(tab.title); 
        //alert(tabs.getTabBodyEl(tab));
        //return tabs.getTabIFrameEl(tab)
    }
}
//关闭左侧菜单
function onMyMenu() {
    if (mainSplitter.getPane(1).expanded == false) {
        $("#leftMenuDiv").html("<span class=\"mini-button-icon icon-arrowleft\">&nbsp;</span>");
        mainSplitter.expandPane(1);
    } else {
        $("#leftMenuDiv").html("<span class=\"mini-button-icon icon-arrowright\">&nbsp;</span>");
        mainSplitter.collapsePane(1);
    }
}
//关闭顶部菜单
//north/south/west/east/center
//expandRegion ( String )		展开regoin对象。	
//collapseRegion ( String )		收缩regoin对象。	
//showRegion ( String )		显示regoin对象。	
//hideRegion ( String )
function onShowHideRegion() {
    if (mainLayout.getRegion("north").visible == false) {
        $("#ShowHideRegio").html("<span class=\"mini-button-icon icon-arrowup\">&nbsp;</span>");
        mainLayout.showRegion("north");
        mainLayout.showRegion("south");
    } else {
        $("#ShowHideRegio").html("<span class=\"mini-button-icon icon-arrowdown\">&nbsp;</span>");
        mainLayout.hideRegion("north");
        mainLayout.hideRegion("south");
    }
}
