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

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 init() {
    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;
    //--登录在线计时
    init();
    window.setTimeout('show_secs()', 1);
    //--
    //获取用户登录信息
    GetUserData();
}

//掉线重新登录框
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; 
				//2014-7-14 zhao 增加刷新主窗口
				//如果主窗口还没加载系统菜单，就刷新主窗口
				//获取系统菜单第3个按钮，如果是帮助按钮，说明还没加载系统菜单      
				var helpnode = $("#mainToolbarMenu>a:nth-child(3)").first();
				if (helpnode) {
					var text = helpnode.text();
					if (text.indexOf("帮助") > 0) {
						breload = true;
						window.location.reload();
					}
				}
				if (!breload && g_TargetWindow) {
					g_TargetWindow.location.reload();
				}
                
            }
            g_OpenReLoginWindow = false;
            g_TargetWindow = null;
        }
    });
}
//打开修改密码窗口 zhao 2014-09-17
function openPwdChgDlg() {
    mini.open({
        url: "../index/userEditPwd.html?autoclose=1",
        title: "修改密码",
        width: 600,
        height: 430,
        showMaxButton: false,
        showCloseButton: false,
        showModal: true,
        allowResize: true,
        allowDrag: true,
        onload: function () { },
        ondestroy: function (action) {
            if (action == "close" || action != "Changed") {
                mini.alert("必须修改过于简单的密码后才能登录系统", "提醒", function (e) {
                    openPwdChgDlg();
                });
            }  
        }
    });
}
//主界面首次加载时 获取用户登录信息及加载界面
function GetUserData() {
    // alert("获取用户登录信息");
    $.ajax({
        url: "../Service/_AdminLoginService.ashx?method=GetUserData&rnd=" + Math.random(),
        cache: false,
        success: function (text) {
            var o = mini.decode(text);
            if (!o.error) { 
                //取值     
                $("#spanUserName").html(o.UserName);
                //     
                //加载菜单
                //加载菜单和默认首页
                GetSysMenuToolBar();
                //加载桌面
                AddDockTab("mydesk", "icon-desktop", "我的桌面", "desk.html");
                //获取授权信息
                GetAuthor("");
            } else {
                //打开重新登录窗口               
                ReLoginWindow();
            }
        }
    });
}

/*
*验证用户是否登录并返回指定页面的权限
*zhaoshunlu 2014-10-08
*/
function CheckUserData(win,pwInfo, fun) {
    $.ajax({
        url: "../Service/_AdminLoginService.ashx?method=GetUserData&pw=" + escape(pwInfo),
        cache: false,
        success: function (text) {
            var result = mini.decode(text);
            //
            if (result.error && (result.errorCode == "" || result.errorCode == "1000")) {
                //错误代码1000：表示未登录或者会话超时  
                mini.alert(result.error, "提醒", function (e) {
                    //打开重新登录窗口          
                    ReLoginWindow(win);
                });
            } else {
                //其他错误信息由调用页面处理
                if (typeof fun == "function") { //arguments.length
				    try{
                        return fun(result);
					}catch(e){
					    //e.message
					}
                }
            }
        }
    });
}

//获取授权信息
function GetAuthor(CompanyCode) {
    if(!CompanyCode || 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);
            }
        }
    });
}

//按设定的时间频率 循环调用 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 (bShowOnLineUser == true || bShowOnLineUser == "true") usertree.loadList(result.OnLineUser, "id", "pid");
                //系统消息
                if (result.OnLineMsg.length > 0) {
                    //for (var i = 0; i < result.OnLineMsg.length; i++) {
                    //    var msgitem = result.OnLineMsg[i];
                    //    $("#lbSysMsg").html(msgitem.text);
                    //    //alert(msgitem.text);
                    //}
                }
				*/
            }
        }
    });
    if (IsGoChk) {
        timer_out = setTimeout("CheckOnLine()", global_Query); //global_Query默认每10分钟查询一次
    }
}
//注销退出
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";
                        }
                    });
                }
            }
        );
} 

//////////////////////////////////////////////////////////////////////
//树型节点选择事件
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);
    }
});
//展开节点后发生
var textindex = 0;
menuTree.on("beforeexpand", function (e) {
    //sender: Object,         //树对象
    //group: Object, 
    //node: Object    //nodeu 不可用
    if (e.group.title == "内部邮件") {
        
    }
});

//皮肤切换
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);
     
    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");
    }
}


function onDrawNode(e) {
    var tree = e.sender;
    var node = e.node;
    if (tree.isLeaf(node)) {
        //if (node.isLeaf) {         
        if (e.node.icon == "男") {
            e.iconCls = "male";
        } else {
            e.iconCls = "female";
        }
    }
}
//在线节点选择事件
mini.get("OnLineUserTree").on("nodedblclick", function (e) {
    if (e.node.UserCode && e.node.UserCode != "") {
        OpenUserView(e.node.UserCode);
    }
});
 
function onClick(e) {
    var text = this.getText();
    mini.alert(text);
}