var ni = {
    cobrandId: null,
    eventId: null,
    previousEventId: null,
    userId: null,
    sessionId: null,
    clientLogUrl: null,
	currentEventId: 0,
    
    initialize: function() {
		
		//Parse url parameters into params array
		initializeParams();
		
        //Set a default cobrand Id (should be overriden in the specific page)
        ni.cobrandId = "info.dogpl.rescue"; //set this in specific page to override
 
        ni.userId = cookieId;
		if (ni.userId == null || ni.userId == "") {
            ni.userId = guid[ni.currentEventId++];
        }
		
		//Build the RescueUserProfile cookie
		var userCookie = "";
		
		if (ni.userId != null && ni.userId != "") {
			userCookie += "AnonymousId=" + ni.userId;
		}
		
		var lastSeenDateTime = params["LastSeenDateTime"];
		if(lastSeenDateTime != null && lastSeenDateTime != "") {
			if(userCookie != "") {
				userCookie += "&";
			}
			
			userCookie += "LastSeenDateTime=" + lastSeenDateTime;
		}
		
		var issueDateTime = params["IssueDateTime"];
		if(issueDateTime != null && issueDateTime != "") {
			if(userCookie != "") {
				userCookie += "&";
			}
			
			userCookie += "IssueDateTime=" + issueDateTime;
		}
		
		//Save the user cookie
		if(userCookie != null && userCookie != "") {
			setCookie('RescueUserProfile', userCookie, 36500, 0) //100 year cookie
		}

        ni.sessionId = sessionId;
        if (ni.sessionId == null || ni.sessionId == "") {
            ni.sessionId = guid[ni.currentEventId++];
        }
		
		ni.previousEventId = prevActionId;
        if (ni.previousEventId == null) {
            ni.previousEventId = "";
        }
    },
 
	logClick: function(clickableObjectID, clickableObjectPosition, clickableObjectPaidFlag, clickableObjectPPCRate, clickUrl, linkTitle) {
		ni.logClickSync(clickableObjectID, clickableObjectPosition, clickableObjectPaidFlag, clickableObjectPPCRate, clickUrl, linkTitle, true);
	},
 
	logClickSync: function(clickableObjectID, clickableObjectPosition, clickableObjectPaidFlag, clickableObjectPPCRate, clickUrl, linkTitle, async) {
		
		if(ni.currentEventId >= guid.length)
			return;
		
		//set a new event ID
		//ni.previousEventId = ni.eventId;
		ni.eventId = guid[ni.currentEventId++];
		
		//Write new previous action ID to cookie
		ni.writeSessionCookie();
		
		//Make a call to log the page view
        var client = getXmlHttpObject();
        var logUrl = (this.clientLogUrl ? this.clientLogUrl : "logclick");
        
		logUrl += "?cobrandID=" + encodeURIComponent(this.cobrandId ? this.cobrandId : "");
		logUrl += "&sessionID=" + (this.sessionId ? this.sessionId : "");
		logUrl += "&cookieID=" + (this.userId ? ni.userId : "");
		logUrl += "&eventID=" + (this.eventId ? this.eventId : "");
		logUrl += "&parentEventID=" + (this.previousEventId ? this.previousEventId : "");
		
		logUrl += "&clickableObjectID=" + (clickableObjectID ? clickableObjectID : "");
		logUrl += "&clickableObjectPosition=" + (clickableObjectPosition ? clickableObjectPosition : "");
		logUrl += "&clickableObjectPaidFlag=" + (clickableObjectPaidFlag ? clickableObjectPaidFlag : "");
		logUrl += "&clickableObjectPPCRate=" + (clickableObjectPPCRate ? clickableObjectPPCRate : "");
		
		logUrl += "&clickUrl=" + encodeURIComponent(clickUrl ? clickUrl : "");
		logUrl += "&linkTitle=" + encodeURIComponent(linkTitle ? linkTitle : "");
 
		logUrl += "&userAgent=" + encodeURIComponent(userAgent ? userAgent : "unknown");
		logUrl += "&clientIP=" + (clientIP ? clientIP : "");
		logUrl += "&rand=" + Math.random();
		
        client.open("GET", logUrl, async);
        client.send(null);
    },
	
	writeSessionCookie: function() {
		//Build the session cookie
		var sessionCookie = "";
		
		if(ni.eventId != null && ni.eventId != "") {
			sessionCookie += "ActionId=" + ni.eventId;
		}
		
		var transactionId = params["TransactionId"];
		if(transactionId != null && transactionId != "") {
			if(sessionCookie != "") {
				sessionCookie += "&";
			}
			
			sessionCookie += "TransactionId=" + transactionId;
		}
		
		if (ni.sessionId != null && ni.sessionId != "") {
			if(sessionCookie != "") {
				sessionCookie += "&";
			}
			
			sessionCookie += "SessionId=" + ni.sessionId;
		}
		
		//Save the session cookie
		if(sessionCookie != null && sessionCookie != ""){
			setCookie('RescueSession', sessionCookie, 0, 20); //current session only
		}
	}
};
 
//Helper functions
function getCookie(name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(name + "=");
        if (c_start != -1) {
            c_start = c_start + name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return document.cookie.substring(c_start, c_end);
        }
    }
    return "";
}
 
function setCookie(name, value, expiredays, expireminutes) {
	var today = new Date();
    var exdate = new Date(today.getTime() + (expiredays == null ? 0 : expiredays * 86400000) + (expireminutes == null ? 0 : expireminutes * 60000));
    //document.cookie = name + "=" + value + ((expiredays == null && expireminutes == null) ? "" : ";expires=" + exdate.toGMTString()) + "; path=/; domain=rescue.dogpile.com";
	document.cookie = name + "=" + value + ((expiredays == null && expireminutes == null) ? "" : ";expires=" + exdate.toGMTString()) + "; path=/; domain=testmicrosite.dogpile.com";
}
 
var params = {};

function initializeParams() { 
	params = {};
      
    var qs = location.search.substring(1, location.search.length);
    if (qs.length > 0)
	{
		qs = qs.replace(/\+/g, ' ');
		parseArgs(qs);
	}
	
	var cookie = getCookie('RescueUserProfile');
	if(cookie != null && cookie != "")
	{
		parseArgs(cookie);
	}
	
	cookie = getCookie('RescueSession');
	if(cookie != null && cookie != "")
	{
		parseArgs(cookie);
	}
}

function parseArgs(argString) {
		
	var args = argString.split('&'); // parse out name/value pairs separated via &

	// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		var value = (pair.length==2) ? decodeURIComponent(pair[1]) : name;

		params[name] = value;
	}
}

function getXmlHttpObject() {
    if (window.XMLHttpRequest)
        return new XMLHttpRequest();
    else if (window.ActiveXObject)
        return new ActiveXObject("Microsoft.XMLHTTP");
    else {
        return null;
    }
}
