// create singleton tracking class
var t = new function() {
	this.event = null;
	this.pageName = null;
	this.pageChannel = null;
	this.userId = null;
	this.campaignId = null;
	this.abTestId = null;
	this.cVars = new Array(50);
	this.productId = null;
	this.purchasePrice = null;
	this.response = function(responseText) {};
	this.send = function() {
		// make sure to prefix the URL...normally there should be none, but for this project there is
		var url = "/abc-tracking/tracking.do";
		var params = this.getParams();
		url += "?" + params;
	  	var http_request = createRequestObject(url, true,'POST', this.response());  
	    if (http_request) {
	    	http_request.send(null);
	    } else {
	    	alert("Error sending tracking: " + url);
	    }
	}

	this.getParams = function() {
		
		// create parameter values
		var params = "";
		
		// add page variables, name and channel (REQUIRED)
		params += "pg=" + this.pageName;
		params += "&pc=" + this.pageChannel;

		// add event parameters if valid
		var eventParam = "";
		if (this.event != null) {
			eventParam = this.event.replace(/=/g,":");
		}		if (eventParam != null) params += "&ev=" + eventParam;
		
		// add specific variables
		if (this.userId != null) params += "&uid=" + this.userId;
		if (this.campaignId != null) params += "&cid=" + this.campaignId;
		if (this.abTestId != null) params += "&abid=" + this.abTestId;
		if (this.productId != null) params += "&pr=" + this.productId;
		if (this.purchasePrice != null) params += "&pp=" + this.purchasePrice;
		
		// add dynamic variables
		for (var i=0;i<this.cVars.length;i++) {
			if (this.cVars[i] != null) {
				params += "&c" + i + "=" + this.cVars[i];
			}
		}		
		return params;
	}

}

function readTrackingCookie(name) {
	var nameEQ = name + "=";
	var tokens = document.cookie.split(';');
	var index = 0;
	while (tokens != null && (index < tokens.length)) {
		var c = tokens[index++];
		while (c.charAt(0)==' ') {
			c = c.substring(1,c.length);
		}
		if (c.indexOf(nameEQ) == 0) {
			return c.substring(nameEQ.length,c.length);
		}		
	}
	return null;
}

function getURLParam(strParamName){
	var strReturn = "";
	var strHref = window.location.href;
	if (strHref.indexOf("?") > -1 ){
		var strQueryString = strHref.substr(strHref.indexOf("?") + 1);
	    var aQueryString = strQueryString.split("&");
	    for (var iParam = 0; iParam < aQueryString.length; iParam++ ) {
	    	var paramPair = aQueryString[iParam];
	    	var aParam = paramPair.split("=");
	    	if (aParam.length > 1) {
	    		if (aParam[0].toLowerCase() == strParamName.toLowerCase()) {
	    			strReturn = aParam[1];
	    			break;
	    		}
	    	}
	    }
	}
    return unescape(strReturn);
} 

function getURLParameters() {
	var strHref = window.location.href;
	if (strHref.indexOf("?") > -1 ){
		return strHref.substr(strHref.indexOf("?") + 1);
	}	
	return null;
}

function getHttpRequestObject() {
	var http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari, IE7 ...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
            // See note below about this line
        }
    } else if (window.ActiveXObject) { // IE 6 and previous ...
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }
   
    return http_request;
}

function createRequestObject(url,avoidCaching,httpMethod,processResponseCallback){

	var http_request = getHttpRequestObject();

    if (!http_request) {
        // alert('Giving up :( Cannot create an XMLHTTP instance');
        // TODO handle error
        return false;
    }

	//The third parameter of open method is to set that the method is asynchronous.
	//If TRUE, the execution of the JavaScript function will continue while the response of the server has not yet arrived. 
	//This is the A in AJAX.
    http_request.open(httpMethod, url, true);     

    if (avoidCaching) {
    	http_request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" ); // avoids caching in IE
    }

    http_request.onreadystatechange = function() {    
 			// anonymous function definition
 			if (http_request.readyState == 4) {
     			if (http_request.status == 200) {
     				if (processResponseCallback != null) {
     					if (http_request.responseText != null &&
     						http_request.responseText.length > 0) {
     						processResponseCallback(http_request.responseText);
     					}
     				}
     			} else {
     				// alert('There was a problem with the request.');
     			}
 			}
    };

    return http_request;
}

///////////////////////////////////////////////////////////////////////////////
// MBox Functions
///////////////////////////////////////////////////////////////////////////////
function getContentForDiv(url, div) {
	var http_request = createRequestObject(url, true, 'GET', 
			function (responseText) {
				div.innerHTML = responseText;
			});  
    if (http_request) {
    	http_request.send(null);
    } else {
    	alert("Error sending tracking: " + url);
    }	
}

// finds the last div in the DOM before createMBox is called
function findDiv(className) {
	var div = null;
    var divCollection = document.getElementsByTagName("div");
    for (var i=0; i<divCollection.length; i++) {
        if(divCollection[i].className == className) {
        	div = divCollection[i];
        } 
    }
	return div;
}
/* Unlimited arguments
function createMBox() {
	var mbox = arguments[0];
	var mboxDiv = findDiv('mboxDefault');
	var value = arguments[1];
    var url = "/abtrack/loadMBox.do?mbox=" + mbox;
    if (value != null) {
	    url += "&value=" + value;
    }

    // append original url parameters
    var oParams = getURLParameters();
    if (oParams != null) {
    	url += "&" + oParams;
    }
    
    getContentForDiv(url, mboxDiv);
}
*/
function createMBox(mboxId, tracker) {
    var mboxDiv = findDiv('mboxDefault');
	// var mboxDiv = document.getElementById(mboxId);
    var url = "/abtrack/loadMBox.do?mbox=" + mboxId;
    if (tracker != null) {
	    var tParams = tracker.getParams();
	    url += "&" + tParams;
    }

    // append original url parameters
    var oParams = getURLParameters();
    if (oParams != null) {
    	url += "&" + oParams;
    }
    
    getContentForDiv(url, mboxDiv);
}

