// 加载当前页时间
var loadPageTimes = '';
// 可操作cookie 变量数组 0 playerInfoCookieName 1 askContentCookieName 2 过期时间 (单位：天) 3
// 路径 4 域 5安全设置
var cookieArguments = '';
// 玩家信息url
var playerInfoUrl = '';
// 用户访问记录url
var askRecordUrl = '';
// 用户访问详细记录url
var askContentUrl = '';
//
var Cookies = {};
//
var asKRecordSessionId = '';

var requestPath = '';

var flag = false;

var isInit = false;

function init() {
	cookieArguments = [ 'wistoneCookies222d2', 'sessionId', 30, '', '', '' ];
	loadPageTimes = getCurrentTimestamp();
	// playerInfoUrl = "http://usagather.wistone.com/datagather/datagather.do?type=1";
	playerInfoUrl = "http://usagather.wistone.com/datagather/datagather.do?type=1";
	askRecordUrl = "http://usagather.wistone.com/datagather/datagather.do?type=2";
	askContentUrl = "http://usagather.wistone.com/datagather/datagather.do?type=3";
	asKRecordSessionId = 's' + loadPageTimes + 'Id';
	requestPath = window.location.host;
	flag = true;

	// 设置cookies
	Cookies.set = function(name, value) {
		var argv = arguments;
		var argc = arguments.length;
		var expires = (argc > 2) ? argv[2] : null;
		var path = (argc > 3) ? argv[3] : '/';
		var domain = (argc > 4) ? argv[4] : null;
		var secure = (argc > 5) ? argv[5] : false;
		document.cookie = name
				+ "="
				+ escape(value)
				+ ((expires == null) ? "" : ("; expires=" + expires
						.toGMTString()))
				+ ((path == null) ? "" : ("; path=" + path))
				+ ((domain == null) ? "" : ("; domain=" + domain))
				+ ((secure == true) ? "; secure" : "");
	};

	// 获取cookies
	Cookies.get = function(name) {
		var arg = name + "=";
		var alen = arg.length;
		var clen = document.cookie.length;
		var i = 0;
		var j = 0;
		while (i < clen) {
			j = i + alen;
			if (document.cookie.substring(i, j) == arg)
				return Cookies.getCookieVal(j);
			i = document.cookie.indexOf(" ", i) + 1;
			if (i == 0)
				break;
		}
		return null;
	};

	// 清空cookies
	Cookies.clear = function(name) {
		if (Cookies.get(name)) {
			var expdate = new Date();
			expdate.setTime(expdate.getTime() - (86400 * 1000 * 1));
			Cookies.set(name, "", expdate);
		}
	};

	// 获取cookies值
	Cookies.getCookieVal = function(offset) {
		var endstr = document.cookie.indexOf(";", offset);
		if (endstr == -1) {
			endstr = document.cookie.length;
		}
		return unescape(document.cookie.substring(offset, endstr));
	};

	isInit = true;
}

// window.onload = function() {
// init();
// }

// 程序入口 currentPageUri--> 当前页面uri
function windowOnload(currentPageUri, identifierId, isSend) {
	if (!isInit) {
		init();
	}
	var cookieValue = Cookies.get(cookieArguments[0]);
	if (identifierId == null || identifierId == ''
			|| identifierId == 'undefined') {

	} else {
		//alert("identifierId==="+identifierId+":"+"isSend"+isSend);
		// 没有设置cookies
		if (cookieValue == null || cookieValue == ''
				|| cookieValue == 'undefined') {
			var exp = new Date();
			exp.setTime(exp.getTime() + cookieArguments[2] * 24 * 60 * 60
					* 1000);
			// 不再在指定cookie则设置cookie
			Cookies.set(cookieArguments[0], identifierId, exp);

			// 用户唯一标识ID
//			var identifierId = var_identifierId;
			// 操作系统
			var os = getOS();
			// 操作系统语言
			var osLanguage = getOSLanguage();
			// flash版本
			var flashVersion = _uFlash();
			// 屏幕分辨率
			var screenResolution = window.screen.width + "*"
					+ window.screen.height;
			// 浏览器分辨率
			var browserResolution = "";
			// 用户来源
			var userSource = "";

			var url = playerInfoUrl + "&identifierId=" + identifierId + "&os="
					+ os + "&osLanguage=" + osLanguage + "&flashVersion="
					+ flashVersion + "&screenResolution=" + screenResolution
					+ "&userSource=" + userSource + "&requestPath="
					+ requestPath;

			// 向服务器发送用户第一次访问信息
			if (isSend) {
				sendPlayerInfo(url);
			}
			// alert('not exist cookies');
		} else {
			// alert('exist cookies');
		}
	}
	var sessionId = Cookies.get(cookieArguments[1]);
	if (sessionId == null || sessionId == '' || sessionId == 'undefined') {
		sessionId = asKRecordSessionId;
		var exp = new Date();
		exp.setTime(exp.getTime() + 12 * 60 * 60 * 1000);
		Cookies.set(cookieArguments[1], sessionId, exp);

	}

	// 等待1秒钟 等待上一个request 消息发送完毕 否则会覆盖上一个request
	setTimeout("sendAskContentInfo('" + currentPageUri + "')", 1000);
}

function windowOnunload(userId) {
	if (!isInit) {
		init();
	}
	if (flag) {
		// 用户唯一标识ID
		var identifierId = Cookies.get(cookieArguments[0]);
		var sessionId = Cookies.get(cookieArguments[1]);
		if (identifierId == '' || identifierId == null
				|| identifierId == 'undefined') {
			return '';
		} else {
			if (sessionId != '' && sessionId != null
					&& sessionId != 'undefined') {

				if (sessionId == asKRecordSessionId) {

					// 由服务器端获得
					var ip = "";
					// 当前页面
					// var content=window.location.pathname;
					// 加载页面时间
					var beginTime = loadPageTimes;
					// 关闭页面时间
					var endTime = getCurrentTimestamp();
					// 浏览器类型
					var browserType = getBrowser();
					// 浏览器版本
					var browserVersion = getBrowerVersion();
					// 浏览器分辩率
					var browserResolution = "";
					var url = askRecordUrl + "&identifierId=" + identifierId
							+ "&sessionId=" + asKRecordSessionId + "&ip=" + ip
							+ "&browserType=" + browserType
							+ "&browserVersion=" + browserVersion
							+ "&browserResolution" + browserResolution
							+ "&beginTime=" + beginTime + "&endTime=" + endTime
							+ "&requestPath=" + requestPath + "&userId="
							+ userId;

					sendPlayerInfo(url);

					// 关闭当前页面 回话结束 清理cookies
					Cookies.clear(cookieArguments[1]);
				}
			}
		}
		flag = false;
	}
}

function sendAskContentInfo(currentPageUri) {
	var askConttentCookieValue = Cookies.get(cookieArguments[1]);
	// session标识id
	var sessionId = '';
	if (null == askConttentCookieValue || askConttentCookieValue == null
			|| askConttentCookieValue == ''
			|| askConttentCookieValue == 'undefined') {
		sessionId = asKRecordSessionId;
	} else {
		sessionId = askConttentCookieValue;

	}
	// 访问(页面)标识(url or ?)
	var content = currentPageUri;
	// 触发事件
	var contentDing = '';
	// 触发时间
	var doingTime = getCurrentTimestamp();

	// var uri=getPageUri();

	var url = askContentUrl + "&sessionId=" + sessionId + "&content=" + content
			+ "&contentDing=" + contentDing + "&doingTime=" + doingTime
			+ "&requestPath=" + requestPath;

	sendPlayerInfo(url);
}

// 向服务器发送采集数据
function sendPlayerInfo(url) {
	url = encodeURI(url);
	// Submit to server with a trick
	var js_obj = document.createElement("script");
	js_obj.type = "text/javascript";
	js_obj.setAttribute("src", url);
	// Get response from server by appending it to document
	document.body.appendChild(js_obj);
	// request.open("GET", url, true);
	// request.onreadystatechange = updatePage;
	// request.send(null);

}

function updatePage() {
	// 只向服务器端发送信息 不关心返回

	if (request.readystate == 4) // 请求状态为4表示成功
	{
		if (request.status == 200) // http状态200表示OK
		{
			// alert('success!');
		}
	}
}

// 获得当前系统时间戳

function getCurrentTimestamp() {
	return new Date().getTime();
}

// 获得flash 版本
function _uFlash() {
	var f = "-", n = navigator;
	if (n.plugins && n.plugins.length) {
		for ( var ii = 0; ii < n.plugins.length; ii++) {
			if (n.plugins[ii].name.indexOf('Shockwave Flash') != -1) {
				f = n.plugins[ii].description.split('Shockwave Flash ')[1];
				break;
			}
		}
	} else if (window.ActiveXObject) {
		for ( var ii = 10; ii >= 2; ii--) {
			try {
				var fl = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash."
						+ ii + "');");
				if (fl) {
					f = ii + '.0';
					break;
				}
			} catch (e) {
			}
		}
	}
	return f;
}

// 获得操作系统类型
function getOS() {
	BrowserDetect.init();
	return BrowserDetect.OS;
}

// 获得浏览器类型
function getBrowser() {
	BrowserDetect.init();
	return BrowserDetect.browser;
}
// 获得浏览器版本
function getBrowerVersion() {
	BrowserDetect.init();
	return BrowserDetect.version;
}

// 获得操作系统语言
function getOSLanguage() {

	var ieLang = window.navigator.userLanguage;

	var notIeLang = window.navigator.language;

	if (ieLang) {
		lang = ieLang;
	} else {
		lang = notIeLang;
	}
	return lang;
}

var BrowserDetect = {
	init : function() {
		this.browser = this.searchString(this.dataBrowser)
				|| "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString : function(data) {
		for ( var i = 0; i < data.length; i++) {
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch
					|| data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			} else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion : function(dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1)
			return;
		return parseFloat(dataString.substring(index
				+ this.versionSearchString.length + 1));
	},
	dataBrowser : [ {
		string : navigator.userAgent,
		subString : "Chrome",
		identity : "Chrome"
	}, {
		string : navigator.userAgent,
		subString : "OmniWeb",
		versionSearch : "OmniWeb/",
		identity : "OmniWeb"
	}, {
		string : navigator.vendor,
		subString : "Apple",
		identity : "Safari",
		versionSearch : "Version"
	}, {
		prop : window.opera,
		identity : "Opera"
	}, {
		string : navigator.vendor,
		subString : "iCab",
		identity : "iCab"
	}, {
		string : navigator.vendor,
		subString : "KDE",
		identity : "Konqueror"
	}, {
		string : navigator.userAgent,
		subString : "Firefox",
		identity : "Firefox"
	}, {
		string : navigator.vendor,
		subString : "Camino",
		identity : "Camino"
	}, { // for newer Netscapes (6+)
				string : navigator.userAgent,
				subString : "Netscape",
				identity : "Netscape"
			}, {
				string : navigator.userAgent,
				subString : "MSIE",
				identity : "Explorer",
				versionSearch : "MSIE"
			}, {
				string : navigator.userAgent,
				subString : "Gecko",
				identity : "Mozilla",
				versionSearch : "rv"
			}, { // for older Netscapes (4-)
				string : navigator.userAgent,
				subString : "Mozilla",
				identity : "Netscape",
				versionSearch : "Mozilla"
			} ],
	dataOS : [ {
		string : navigator.platform,
		subString : "Win",
		identity : "Windows"
	}, {
		string : navigator.platform,
		subString : "Mac",
		identity : "Mac"
	}, {
		string : navigator.userAgent,
		subString : "iPhone",
		identity : "iPhone/iPod"
	}, {
		string : navigator.platform,
		subString : "Linux",
		identity : "Linux"
	} ]
};
