/*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 == '')
		EventCode = 1;
	
	if(StoryId == '' && parseInt(EventCode) == 2 || parseInt(EventCode) == 3)
		return;
	
	
	//Check if tracking is disabled
	if (_DMreadCookie('DMUserTrackOFF')	!= null && _DMreadCookie('DMUserTrackOFF') == "1")
		return;
	var AccountId  = _DMreadCookie('DMUserTrack').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);
	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/jsonrest/histogram/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/jsonrest/histogramsession/logsession?apikey='+_DM_Newstogram_APIKEY+'&userid='+AccountId+'&callback=_DM_LogSessionCompleted';
	var scriptTag = _DM_CreateScriptTag();
	scriptTag.setAttribute("src", url);
}
function _DM_TrackCompleted(JSON){
	if (JSON.Histogram.status == "saved"){
		var _DM_CookieVal = _DMreadCookie('DMUserTrackIP');
		if (_DM_CookieVal != JSON.Histogram.ip){
			_DMcreateCookie('DMUserTrackIP', JSON.Histogram.ip ,365);//Modify the cookie with the new IP
			//Call the WS Histogram Session
			var AccountId  = _DMreadCookie('DMUserTrack').split(":")[0];
			_DM_CallLogSessionWS(AccountId);
		}

	}
}
function _DM_LogSessionCompleted(){}