//set expire date for cookie
var COOKIE_EXPIRE_DATE=new Date("12/31/2019");
//set pageview time constant
//var PAGE_VIEW_DURATION=5000;//page view duration time in miliseconds
//var VISITOR_COUNT=3600000;//visited duration time in miliseconds
var COOKIE_TRACK_NAME="CTrack";//Storing all user's information when he/she visits the site
var COOKIE_CID_NAME="cId";//the unique value is set for each user 
var COOKIE_CLICK_DURATION="drc";//time period the user view a page
var COOKIE_LASTIME_CLICK="ltc";//the time that the user visit at the last on the site
//var COOKIE_VISITED_LEVEL="vl";//the times user visit the site after each session time out
var COOKIE_CIDC_NAME="cIdc";
var HTTP_URL_THIRD_PARTY_DB="http://lg.polyad.net/Default.aspx";//the url that link to the server to storing logging about visiting of the user
//Cookie Class
function Cookie(name,value,expireDate){
	this.name=name;
	this.value=value;
	this.expireDate=expireDate;
	this.getName=function(){
		return this.name;
	}
	this.setName=function(name){
		this.name=name;
	}
	this.getValue=function(){
		return this.value;
	}
	this.setValue=function(value){
		this.value=value;
	}	
	this.getExpireDate=function(){
		return this.expireDate;
	}
	this.setExpireDate=function(expireDate){
		this.expireDate=expireDate;
	}	
}

function LoggingUtil(){
	this.convertStringToMap=function(valueStr,splitChar){
		var map={};	
		if(valueStr==null||valueStr==""){
			return map;	
		}else{		
			var strValueArray=valueStr.split(splitChar);			
			if(strValueArray!=null||strValueArray.length>0){
				var key="";
				var value="";
				for(i=0;i<strValueArray.length;i++){
					key=strValueArray[i].split("=")[0];
					value=strValueArray[i].split("=")[1];
					map[key]=value;
				}
			}	
			return map;
		}
	}
	this.generateCId= function(){  		
		var numberStr="";
		for(i=0;i<10;i++){
			numberStr+=Math.floor(Math.random()*10);
		}
		var currentDate=new Date();	
		return currentDate.getTime()+numberStr;
	}
	this.convertMapToString=function(valueMap,splitChar){
		var strValue="";		
		for (var key in valueMap) {
			strValue+=key+"="+valueMap[key]+splitChar;
		}
		strValue=strValue==""?strValue:strValue.substring(0,strValue.length-1);
		return strValue;
	}
	
	//get value of key from string base on string format key1=value1|key2=value2
	//assume the splitchar is '|'
	this.getValueByKey=function(valueStr,key,splitChar){		
		var valueString=valueStr+splitChar;
		var searchName =key + "=";
		var startOfCookie = valueString.indexOf(searchName);		
		var endOfCookie;
		var result="";
		if (startOfCookie != -1) {
			startOfCookie += searchName.length;			
			endOfCookie = valueString.indexOf(splitChar, startOfCookie);
			result = unescape(valueString.substring(startOfCookie, endOfCookie));
		}			
		return result;
	}	
}

//StringUtil Class
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
function StringUtil(){
	this.IsEmptyOrNull=function(stringValue){
		if(stringValue==null||stringValue==''||stringValue=="")
			return true;
		else
			return false;
	}
}
/*end String Utill*/
function CookieDB(){
	
	this.save=function(cookieObj){			
		document.cookie = cookieObj.getName() + '=' + cookieObj.getValue() + ';path=/; expires=' + cookieObj.getExpireDate().toGMTString();
	}
	//Get Cookie Obj by Name
	this.getCookie=function(cName)	{				
		var strUtil=new StringUtil();//create a StringUtil Instance
		var loggingUtil=new LoggingUtil();
		var myCookie = " " + document.cookie + ";";				
		if(!strUtil.IsEmptyOrNull(document.cookie)){
			var value = loggingUtil.getValueByKey(myCookie,cName,';');
			return new Cookie(cName,value,COOKIE_EXPIRE_DATE);	
		}
	}	
	//get multi value cookie value 
	//     on=name=amit|age=25;
	this.getCookieMultiValue=function(cName, cKey) {	
		
		loggingUtil=new LoggingUtil();
		var cookie = this.getCookie(cName);		
		if(cookie==null||cookie.getValue()==""){
			return "";
		}else{			
			var valueOfKey=loggingUtil.getValueByKey(unescape(cookie.getValue()),cKey,'|');
			return valueOfKey;
		}		
			
	}	
	//append a key and value to the value of current cookie name
	//with cookie format is cName=key1=123|key2=456;
	this.saveOrUpdateCookieMultiValue=function(cookie,cKey,cKeyValue){			
		var cValue=unescape(cookie.getValue());		
		var loggingUtil=new LoggingUtil();
		var strUtil=new StringUtil();
		if(!strUtil.IsEmptyOrNull(cValue)){
			loggingUtil=new LoggingUtil();
			var valueOfcKey=loggingUtil.getValueByKey(cValue,cKey,'|');
			/*add new multi value to current cookie*/	
			if(strUtil.IsEmptyOrNull(valueOfcKey)){
				cValue+="|"+cKey+"="+cKeyValue;
			}else{
				var keyValueCurrent=cKey+"="+valueOfcKey;				
				var keyValueUpdate=cKey+"="+cKeyValue;			
				cValue=cValue.replace(keyValueCurrent,keyValueUpdate);	
			}					
			cookie.setValue(cValue);			
			this.save(cookie);
		}
	}
}
function TimePeriod(startTime,endTime){
	this.startTime=startTime;//in miliseconds
	this.endTime=endTime;//in miliseconds
	this.getDuration=function(){
		return (this.endTime-this.startTime);//in miliseconds
	}
	this.getStartTime=function(){
		return this.startTime;
	}
	this.setStartTime=function(startTime){
		this.startTime=this.startTime;
	}
	this.getEndTime=function(){
		return this.endTime;
	}
	this.setEndTime=function(endTime){
		this.endTime=endTime
	}
}


function Logging(){	
	this.visitTimeOut=3600;//session time out by seconds	
	this.pageViewTimeOut=5;//page view time out by seconds	
	this.PageId=-1;//page id of the site
	this.ServerId=-1;//server id  in config table
	this.SiteId=-1;//site Id 1=vnexpress,2=Ngoisao,3=,..in config table
	this.isHotNews="";
	this.getVisitTimeOut=function(){
		return this.visitTimeOut;
	}
	this.setVisitTimeOut=function(visitTimeOut){
		this.visitTimeOut=visitTimeOut;
	}
	this.getPageViewTimeOut=function(){
		return this.pageViewTimeOut;
	}
	this.setPageViewTimeOut=function(pageViewTimeOut){
		this.pageViewTimeOut=pageViewTimeOut;
	}	
	this.getPageId=function(){
		return this.pageId;
	}
	this.setPageId=function(pageId){
		this.pageId=pageId;
	}	
	this.getSiteId=function(){
		return this.siteId;
	}
	this.setSiteId=function(siteId){
		this.siteId=siteId;
	}
	this.getServerId=function(){
		return this.serverId;
	}
	this.setServerId=function(serverId){
		this.serverId=serverId;
	}
	this.getIsHotNews=function(){
		return this.isHotNews;
	}
	this.setIsHotNews=function(isHotNews){
		this.isHotNews=isHotNews;
	}	
	/*executing collect data from client and send to third party server to store*/
	this.doProcess=function(){
		
		
		var cDB=new CookieDB();	
		var logging=new LoggingUtil();	
		var strUtil=new StringUtil();			
		cookieObj=cDB.getCookie(COOKIE_TRACK_NAME);
		
		//the browser is supported cookie
		if(cookieObj!=null){
			//get CIdC cookie.
			//write CID value to CIDC cookie when the user visit site first time
			cookieCIdObj=cDB.getCookie(COOKIE_CIDC_NAME);			
			if(cookieCIdObj==null||strUtil.IsEmptyOrNull(cookieCIdObj.getValue())){
				cookieCIdObj.setValue(logging.generateCId());
				cookieCIdObj.setExpireDate(COOKIE_EXPIRE_DATE);
				cDB.save(cookieCIdObj);
			}
			var sendParaFlag=true;
			var ltClickStr=cDB.getCookieMultiValue(COOKIE_TRACK_NAME,COOKIE_LASTIME_CLICK);				
			//the time period between lastime visit and current visit
			var currentDate=new Date();
			if(strUtil.IsEmptyOrNull(ltClickStr)){
				cDB.saveOrUpdateCookieMultiValue(cookieObj,COOKIE_LASTIME_CLICK,currentDate.getTime());					
			}else{	
				var timePeriod=new TimePeriod(ltClickStr*1,currentDate.getTime())
				var timeDurationInseconds=Math.floor(timePeriod.getDuration()/1000);
				//get pageview session time & visit session time
				var pageViewSessionTimeOut=parseInt(this.getPageViewTimeOut());
				//update lastime click to cookie
				if(pageViewSessionTimeOut>timeDurationInseconds){
					sendParaFlag=false;
				}else{
					sendParaFlag=true;
					//write cookie lastime click
					cDB.saveOrUpdateCookieMultiValue(cookieObj,COOKIE_LASTIME_CLICK,currentDate.getTime());	
				}
			}			
			//sending data to logging server
			var map=this.buildMap(true);				
			var queryStr=this.buildQueryString(map);			
			if(sendParaFlag){				
				document.write('<img src="'+HTTP_URL_THIRD_PARTY_DB+"?f=1&" + queryStr + '" border=0 style="display:none;"> ');			
			}
		}else{//browser is not supported cookie
			// send data from unsupported cookie browser to server logging
			var map=this.buildMap(false);				
			var queryStr=this.buildQueryString(map);
				
			document.write('<img src="'+HTTP_URL_THIRD_PARTY_DB+"?f=1&" + queryStr + '" border=0>');
		}
		
	}
	//clear cookie
	this.clearCookie=function(){
	
		var cDb=new CookieDB();
		var currentDate=new Date();
		currentDate.setDate(currentDate.getDate()-1);
		//delete CId cookie
		var cIdObj=new Cookie(COOKIE_CID_NAME,"",currentDate);	
		cDb.save(cIdObj);
		//delete CTrack cookie
		cIdObj=new Cookie(COOKIE_TRACK_NAME,"",currentDate);	
		cDb.save(cIdObj);
	}
	/*building querystring for url , that server can get values from url
	 *input is a Map indeed key is key of querystring,value is value that the server will get
	*/
	this.buildQueryString=function(map){
		var queryStr="";		
		for(var key in map){
			queryStr+=key+"="+map[key]+"&";
		}
		queryStr=queryStr==""?queryStr:queryStr.substring(0,queryStr.length-1);
		return queryStr;
	}
	this.buildMap=function(isSupportedCookie){
		cDB=new CookieDB();		
		var map={};	
		if(isSupportedCookie){
			map["cStatus"]=cDB.getCookieMultiValue(COOKIE_TRACK_NAME,"cs");	
			map["cId"]=escape((cDB.getCookie(COOKIE_CIDC_NAME)).getValue());
		}
		map["url"]= escape(document.location.href); //the url of current page
		map["title"]=escape(document.title); //the title at the current page
		map["uAgent"]=escape(navigator.userAgent);//useragent's information
		map["rfr"]=escape(document.referrer); //the reffer that link to current page
		map["sr"]=screen.width + 'x' + screen.height; //screen resolution
		map["cd"]= screen.colorDepth; // color depth				
		map["pId"]=this.getPageId();//the id of current page in database	
		map["hn"]=this.getIsHotNews();
		map["st"]=this.getSiteId();//domain of site
		map["sId"]=this.getServerId();//id of domain server		
		return map;
	}
}
