﻿// 给需要统计用户在线时间的页面调用

//当前用户ID.
var onLineUserId = 0;

onLineUserId = GetCookie("OnlineUserID"); //修改为你当前页面的用户ID传给

//用于统计的动态页面,要根据你的地址修改
var baseURL = "UserOnlineCount.aspx?"; 

loginStart();
//隔时请求一次服务器
var refreshTime = 1000 * 120;
setInterval(loginStart, refreshTime);


//当用户关闭浏览器时触发
window.onbeforeunload=function()   
{  
    loginOut(onLineUserId);
}

//登入
function loginStart()
{
    postCount("in");
}

//登出
function loginOut()
{
    postCount("out");
}

//发送统计信息
function postCount(aType)
{
    if(onLineUserId != null && onLineUserId >0)
    {
        var param = baseURL + "userid="+ onLineUserId +"&type="+aType +"&key="+getTimeKey();
        requestURL(param, false);
    }
}


function getTimeKey()
{
    var toDay = new Date();
    return toDay.getTime();
}


function GetCookieVal(offset){
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1)
    endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
 }

function GetCookie(name){
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen){
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
        return GetCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
    }
    return null;
}

//请求一个url,支持同步,异步
function requestURL(url,sync)
{
	var http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
    
    http_request.open('POST', url, sync);
    http_request.send();
}