/*Event Codes
	1 :: FrontPage
	2 :: Article Full
	3 :: Article Summary
	4 :: Focus Page
	5 :: Source Page
	6 :: Search
	7 :: Category (Entity Level 1)
	8 :: Sub-Category (Entity Level 2)
*/

function DMLogVisit(StoryId,EventCode){
	if (EventCode == null)
		EventCode = 1;
	
	//Check if tracking is disabled
	if (_DMreadCookie('DMTrackingCodeOFF')	!= null && _DMreadCookie('DMTrackingCodeOFF') == "1")
		return;
	var AccountId  = _DMreadCookie('DMTrackingCode');
	if(AccountId != null) AccountId = AccountId.split(":")[0];
	var Referer = document.referrer;
	var QueryString = window.location.search.substring(1);
	
	Referer = Referer == null || Referer == '' ? '0' : Referer;
	QueryString = QueryString == null || QueryString == '' ? '0' : QueryString;
	
	Referer = encodeURI(Referer);
	QueryString = encodeURI(QueryString);
	
	if((EventCode == 2 || EventCode == 3) && StoryId == "")
		StoryId = document.location.href;
	
	StoryId = encodeURI(StoryId);
	
	_DM_CallLogVisitWS(AccountId,StoryId,Referer,QueryString,EventCode);
}
function _DM_CallLogVisitWS(AccountId,StoryId,Referer,QueryString,EventCode){	
	var url = 'http://service.dailyme.com/v1/webroot/index.php?output=jsonrest&service=histogram&call=logvisit&apikey='+_DM_Newstogram_APIKEY+'&userid='+AccountId+'&storyid='+StoryId+'&referer='+Referer+'&querystring='+QueryString+'&eventcode='+EventCode+'&callback=_DM_TrackCompleted';
	var scriptTag = _DM_CreateScriptTag();
	scriptTag.setAttribute("src", url);	
}
function _DM_CallLogSessionWS(AccountId){
	var url = 'http://service.dailyme.com/v1/webroot/index.php?output=jsonrest&service=histogramsession&call=logsession&apikey='+_DM_Newstogram_APIKEY+'&userid='+AccountId+'&callback=_DM_LogSessionCompleted';
	var scriptTag = _DM_CreateScriptTag();
	scriptTag.setAttribute("src", url);
}
function _DM_TrackCompleted(JSON){
	if(typeof JSON.Histogram == 'undefined') return;
	if (JSON.Histogram.status == "saved"){
		var _DM_CookieVal = _DMreadCookie('DMTrackingCodeIP');
		if (_DM_CookieVal != JSON.Histogram.ip){
			_DMcreateCookie('DMTrackingCodeIP', JSON.Histogram.ip ,365);//Modify the cookie with the new IP
			//Call the WS Histogram Session
			var AccountId  = _DMreadCookie('DMTrackingCode').split(":")[0];
			_DM_CallLogSessionWS(AccountId);
		}

	}
}
function _DM_LogSessionCompleted(){}
