function outputRegStat(){
	//unique id
	var u = generateUniqueId();
	//time
	var t = getCurrentTime();
	//url
	var ur = getReferer();
	// affiliate id
	var af = getAfId();

	document.write(constructImageURL(u,t,ur,af));
}

function generateUniqueId(){
	var id;
	for(var i = 0; i < 5; i++)
	{
		id = (Math.random() * Math.pow(10, 17) + Math.random() * Math.pow(10, 17) + Math.random() * Math.pow(10, 17) + Math.random() * Math.pow(10, 17));
	}
	return id;
}

function getCurrentTime(){
	var date = new Date();
	return date.getTime();
}

function getReferer(){
	return escape(window.location.href);
}

function getAfId(){
	var afid = getURLParam("afid");
	if (afid != "") {
		restoreCookies(afid);
	} else {
		afid = getTranslatedCookieValue("afid");
	}
	return afid;
}

function getURLParam( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null ) {
    return "";
  } else {
    return results[1];
  }
}

function restoreCookies(val) {
	var quan_vid = getTranslatedCookieValue("quan_vid");
        var expireDate = new Date();
        //set cookie expire time to 30 days.
        var lefttime=1000 * 86400 * 30;
        expireDate.setTime (now + lefttime);
	document.cookie = "quan_stat_3=afid=" + val + "|quan_vid=" + escape(quan_vid) + "; expires=" + expireDate.toGMTString() +  "; path=/; domain=.360quan.com";
}

function getFromCookie (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 "";
}

function getCookieVal(offset)
{
	var endstr = document.cookie.indexOf (";", offset);

	if (endstr == -1) {
		endstr = document.cookie.length;
	}

	return unescape(document.cookie.substring(offset, endstr));
}

function constructImageURL(uid, time, url, afid){
	return "<img src='http://tiger.stat.360quan.com/statreg.html?u=" + uid + "&t=" + time + "&ur=" + url + "&af=" + afid + "' style='display:none' />";
}

function getTranslatedCookieValue (name)
{
    value = cookieArray[name];
    if (typeof value == "undefined") {
        value = null;
    }
    return value;
}

function translateCookiesToArray(result, key) {
    rawString = getFromCookie(key);
    if (rawString != null) {
		tokenizedString = rawString.split("|");

		for (i=0;i<tokenizedString.length;i++){
			innerArray = tokenizedString[i].split("=");
			result[innerArray[0]] = innerArray[1];
		}
    }

    return result;
}

var cookieArray = translateCookiesToArray(new Array(), "quan_stat_3");

outputRegStat();