//BIS Global Client Api
//Version: 1.0
//Deprecated, do not use, only https://webapi.charityengine.net/api.js should be used

console.log('Warning - attempting to load unsupported CharityEngine web api (sm_trackcampaign.js).  Keeping this in place could have unintended consequences and affect your website, online forms or other apps.  Remove and use https://webapi.charityengine.net/api.js instead.');

//globals
//---------

var gl_clapi_debugLogToConsole = false;

function clapi_logDiagnostics(message) {
    if (message && gl_clapi_debugLogToConsole)
        console.log(message);
}

function smctm_clapi_documentReady(f){/in/.test(document.readyState)?setTimeout('smctm_clapi_documentReady('+f+')',100):f()}
 
var CEVisitorInfoHelperCookieStub = screen.width.toString() + '|' + screen.height.toString();
var CEVisitorInfoHelperCookieExpires = new Date();
CEVisitorInfoHelperCookieExpires.setDate(CEVisitorInfoHelperCookieExpires.getDate() + 18250);

//Client Web API & WAF Core Ajax Framework
//--------------------------

var xmlHttpOpenPtr = window.XMLHttpRequest.prototype.open;
var xmlHttpSendPtr = window.XMLHttpRequest.prototype.send;        

function xmlHttpOpenReplacement(method, url, async, user, password) {

    this._url = url;

    return xmlHttpOpenPtr.apply(this, arguments);

}

function xmlHttpSendReplacement(data) {

    if (this.onreadystatechange)
        this._onreadystatechange = this.onreadystatechange;    

    //log event
    if(this._url)
        clapi_logDiagnostics('Ajax send override fired with url: ' + this._url);
    else
        clapi_logDiagnostics('Ajax send override fired with null url');

    //check url for endpoint     
    if(this._url)
        if (this._url.length >= 37 && (this._url.substring(0, 37) == 'https://webapi.charityengine.net/v/1/' || this._url.substring(0, 41) == 'https://betawebapi.charityengine.net/v/1/')) {

            //log event
            clapi_logDiagnostics('web api match detected - add headers');

            //check for context
            var clid = smctn_clidToUse();
            var casId = smctm_casIdToUse();
            var cntId = smctm_cntIdToUse();

            if (clid > 0 && casId > 0) {

                //log event
                clapi_logDiagnostics('add header: ' + clid.toString() + '-' + casId.toString() + '-' + cntId.toString());

                this.setRequestHeader('CeWebApiContext', clid.toString() + '-' + casId.toString() + '-' + cntId.toString());                

            }
            else
                clapi_logDiagnostics('no header value: ' + clid.toString() + '-' + casId.toString() + '-' + cntId.toString());            

        }        

    //TODO: add outbound WAF proxy call (i.e. appsapi/logAjax)

    return xmlHttpSendPtr.apply(this, arguments);

}

window.XMLHttpRequest.prototype.open = xmlHttpOpenReplacement;
window.XMLHttpRequest.prototype.send = xmlHttpSendReplacement;

//Client Web API Wrappers
//--------------------------

function CE_GetVisitor(clientApiKey,onSuccess,onFail) {
    
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://webapi.charityengine.net/v/1/Rest/' + clientApiKey + '/PageVisitorProfile', true);        
    xhr.setRequestHeader('content-type', 'application/json');
    xhr.onload = onSuccess;
    xhr.onerror = onFail;    
    xhr.send();

}

//Tracking Helpers
//--------------------------

function gl_casAcceptor(casId, cntId) {    
    if(casId > 0)
        if(typeof cntId != 'undefined' && cntId > 0)
            sm_setCookie_new('CharityEngineVisitorInfoHelper_' + smctn_clidToUse(), cntId.toString() + '|' + CEVisitorInfoHelperCookieStub + '|' + casId.toString());
        else
            sm_setCookie_new('CharityEngineVisitorInfoHelper_' + smctn_clidToUse(), '0|' + CEVisitorInfoHelperCookieStub + '|' + casId.toString());
}

function appInstToUse() {
    var retVal = 0;
    if (typeof app_clapi_gl_aiid != 'undefined' && app_clapi_gl_aiid > 0)
        retVal = app_clapi_gl_aiid;
    return retVal;
}

function smctn_clidToUse() {
    var retVal = 0;
    if (typeof cas_clapi_gl_cid != 'undefined' && cas_clapi_gl_cid > 0)
        retVal = cas_clapi_gl_cid;
    else
        if (typeof cas_clapi_ovr_cid != 'undefined' && cas_clapi_ovr_cid > 0)
            retVal = cas_clapi_ovr_cid;
    return retVal;
}

function smctm_cntIdToUse() {
    var retVal = 0;
    if (typeof cas_clapi_ovr_cntid != 'undefined' && cas_clapi_ovr_cntid > 0)
        retVal = cas_clapi_ovr_cntid;
    else
        if (typeof cas_clapi_gl_cntid != 'undefined' && cas_clapi_gl_cntid > 0)
            retVal = cas_clapi_gl_cntid;
        else
            if (sm_cmptrk_getCookie('CharityEngineVisitorInfoHelper_' + smctn_clidToUse()).length > 0) {
                var csArr = sm_cmptrk_getCookie('CharityEngineVisitorInfoHelper_' + smctn_clidToUse()).split("|");
                retVal = csArr[0];
            }
    return retVal;    
}

function smctm_casIdToUse() {
    var retVal = 0;
    if (typeof cas_clapi_ovr_casid != 'undefined' && cas_clapi_ovr_casid > 0)
        retVal = cas_clapi_ovr_casid;
    else
        if (typeof cas_clapi_gl_casid != 'undefined' && cas_clapi_gl_casid > 0)
            retVal = cas_clapi_gl_casid;
        else
            if (sm_cmptrk_getCookie('CharityEngineVisitorInfoHelper_' + smctn_clidToUse()).length > 0) {
                var csArr = sm_cmptrk_getCookie('CharityEngineVisitorInfoHelper_' + smctn_clidToUse()).split("|");
                retVal = csArr[3];
            }
    return retVal;
}

smctm_clapi_documentReady(function () {
    sm_setCookie_new('CharityEngineVisitorInfoHelper_' + smctn_clidToUse(), smctm_cntIdToUse().toString() + '|' + CEVisitorInfoHelperCookieStub + '|' + smctm_casIdToUse().toString());       
});

function sm_setCookie_new(cName, cValue) {
    var rootDomain = sm_extractRootDomain(window.location.href);
    document.cookie = cName + '=' + cValue + ";path=/;domain=." + rootDomain;
}

//sm_cmptrk_getCookie: gets client cookie
function sm_cmptrk_getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return '';
	} 
	else begin += 2;
		
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) end = dc.length;
		
	return unescape(dc.substring(begin + prefix.length, end));
}

//sm_cmptrk_setCookie: sets client cookie
function sm_cmptrk_setCookie(name, value, expires, path, domain, secure) {
    
	var curCookie = name + "=" + escape(value) + 
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		//((path) ? "; path=" + path : "") +
		"; path=/" +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");

	document.cookie = curCookie;
}

//sm_cmptrk_doesUrlHaveToken: checks if url has parameters
function sm_cmptrk_doesUrlHaveToken(fullUrl,tokenName){	
	return (fullUrl.indexOf("?"+tokenName+"=") > 0 || fullUrl.indexOf("&"+tokenName+"=") > 0);
}

//sm_cmptrk_replaceUrlToken: replaces a url parameter value
function sm_cmptrk_replaceUrlToken(fullUrl,tokenName,newTokenValue){
	
	var retVal = fullUrl;
	
	if(sm_cmptrk_doesUrlHaveToken(retVal,tokenName))
	{
		
		var tokenPrefix = "&";
		if(retVal.indexOf("?"+tokenName+"=") > 0)
			tokenPrefix = "?";
		
		var stubBefore = retVal.substring(0,retVal.indexOf(tokenPrefix+tokenName+"=") + (tokenName.length+2));
		var stubAfter = retVal.substring(stubBefore.length);
		
		//check for more parameters or end
		if(stubAfter.indexOf("&") > 0)
			stubAfter = stubAfter.substring(stubAfter.indexOf("&"),stubAfter.length-stubAfter.indexOf("&"));
		else
			stubAfter = "";
			
		//finally add new token value
		retVal = stubBefore+newTokenValue+stubAfter;
		
		//kill variables
		stubAfter = null;
		stubBefore = null;
		tokenPrefix = null;
		
	}
	
	return retVal;
	
} 

//startup - track URL/Cookie
//--------------------------

//encoded url parameter
var cookaddr_str = encodeURIComponent(document.URL);

if (document.URL.indexOf('?') != -1) { 

	var addr_str = document.URL.substring(document.URL.indexOf('?')+1, document.URL.length);
	var tokenName = '';
	var tokenVal = '';
	var trackType = 1;		
	var foundSMGUID = 0;
	var smGuid = '';
	
	for (count = 0; count < addr_str.length; count++){
		if (addr_str.charAt(count) == '&') {
			if(tokenName.toLowerCase() == 'sm_guid'){
				foundSMGUID = 1;
				smGuid = tokenVal;
			}						
	
			trackType = 1;
			tokenName = '';
			tokenVal = '';
		}
		if (addr_str.charAt(count) == '=') trackType = 2;
		if (addr_str.charAt(count) != '&' && addr_str.charAt(count) != '='){
			if(trackType == 1) tokenName = tokenName + addr_str.charAt(count);
			if(trackType == 2) tokenVal = tokenVal + addr_str.charAt(count);
		}
	}

	if(tokenName.toLowerCase() == 'sm_guid'){
		foundSMGUID = 1;
		smGuid = tokenVal;
	}

    //FOUND URL - CHECK/CREATE COOKIE
    if (foundSMGUID == 1)
        sm_cmptrk_setCookie('bisSMGUID', smGuid);
    else
        smGuid = sm_cmptrk_getCookie('bisSMGUID');

    //CHECK COOKIE - TRACK (2 - CLICK)
    if (smGuid.length > 0) {
        document.getElementById('bisFollowPix').src = document.location.protocol + '//smartmailerclick.bisglobal.net/act_logClick.aspx?refPage=' + cookaddr_str + '&ttid=2&sm_guid=' + smGuid + '&aiid=' + appInstToUse().toString();
        if (typeof sm_disableThirdPartyPageViewTracking == 'undefined' || sm_disableThirdPartyPageViewTracking != 1)
            document.getElementById('bisFollowPix').src = document.location.protocol + '//smartmailerclick.bisglobal.net/act_tpWebPageView.aspx?refPage=' + cookaddr_str + '&cntid=' + smctm_cntIdToUse().toString() + '&sm_guid=' + smGuid + '&aiid=' + appInstToUse().toString();
    }
    else
        if (typeof sm_disableThirdPartyPageViewTracking == 'undefined' || sm_disableThirdPartyPageViewTracking != 1)
            document.getElementById('bisFollowPix').src = document.location.protocol + '//smartmailerclick.bisglobal.net/act_tpWebPageView.aspx?refPage=' + cookaddr_str + '&cntid=' + smctm_cntIdToUse().toString() + '&aiid=' + appInstToUse().toString();

}
else{
	
	//NO URL VARIABLES - CHECK COOKIES - TRACK
    if (sm_cmptrk_getCookie('bisSMGUID').length > 0) {
        document.getElementById('bisFollowPix').src = document.location.protocol + '//smartmailerclick.bisglobal.net/act_logClick.aspx?refPage=' + cookaddr_str + '&ttid=2&sm_guid=' + sm_cmptrk_getCookie('bisSMGUID') + '&aiid=' + appInstToUse().toString();
        if (typeof sm_disableThirdPartyPageViewTracking == 'undefined' || sm_disableThirdPartyPageViewTracking != 1)
            document.getElementById('bisFollowPix').src = document.location.protocol + '//smartmailerclick.bisglobal.net/act_tpWebPageView.aspx?refPage=' + cookaddr_str + '&cntid=' + smctm_cntIdToUse().toString() + '&sm_guid=' + sm_cmptrk_getCookie('bisSMGUID') + '&aiid=' + appInstToUse().toString();
    }
    else
        if (typeof sm_disableThirdPartyPageViewTracking == 'undefined' || sm_disableThirdPartyPageViewTracking != 1)
            document.getElementById('bisFollowPix').src = document.location.protocol + '//smartmailerclick.bisglobal.net/act_tpWebPageView.aspx?refPage=' + cookaddr_str + '&cntid=' + smctm_cntIdToUse().toString() + '&aiid=' + appInstToUse().toString();
	
}

//link tracking function - oninit - unless disabled manually
//----------------------------------------------------------
function sm_guid_addLinkTracking(sm_guid_urlTokenValue)
{
	//document.addEventListener('DOMContentLoaded', function () {

		$('a[href]').each(function(i){
			  
			var currHref = $.trim($(this).attr("href"));
		  
			if(currHref.length > 0)
			{
			  
				//first let's check for non-url hyperlinks (e.g. javascript:, mailto:, etc.)
				if(currHref.toLowerCase().substring(0,10) != "javascript" 
					&& currHref.toLowerCase().substring(0,6) != "mailto"
					&& currHref.toLowerCase().substring(0,1) != "#")
				{
					
					//next let's clean URL for starnge legal URL configurations (e.g. www.url.com?)
					if(currHref.charAt(currHref.length-1) === '?')
						currHref = currHref.substring(0,currHref.length-1);
					
					//next let's see if we have any url parameters
					if(currHref.indexOf("?") > 0)
					{
						
						//since we have parameters, let's see if we already have a token for SmartMailer
						if(sm_cmptrk_doesUrlHaveToken(currHref,"sm_guid"))
							$(this).attr("href",sm_cmptrk_replaceUrlToken(currHref,"sm_guid",sm_guid_urlTokenValue));
						else
							$(this).attr("href",currHref+"&sm_guid="+sm_guid_urlTokenValue);
						
					}
					else
						$(this).attr("href",currHref+"?sm_guid="+sm_guid_urlTokenValue);
						
				}
			
			} //currHref.length > 0
				  
			//kill variable
			currHref = null;
		  
		});
				  
	//});
}

//Startup link/tracking
//---------------------
//global variable for JS $ Conflict
var sm_thisPageUsingOtherJSLibrary = false;

//variable for tracking load on demand timeout
function sm_jquery_loadOnDemand(success) {    

    //load jquery on demand
	var script = document.createElement('script');
	script.src = document.location.protocol + "//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js";
	
	var head = document.getElementsByTagName('head')[0];
	done = false;

	// Attach handlers for all browsers
	script.onload = script.onreadystatechange = function() {
	
		if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
		
			done = true;
			
			// callback function provided as param
			success();
			
			script.onload = script.onreadystatechange = null;
			head.removeChild(script);
			
		};
	
	};
	
	head.appendChild(script);

}

//only call startup detection and trigger routines if we have a token identified for a campaign and if the client has not disabled tracking
if(typeof sm_disableLinkTracking == 'undefined' && sm_cmptrk_getCookie('bisSMGUID').length > 0)
{	

	//check if jquery is loaded and load on demand if not
	if(typeof jQuery == 'undefined'){        
	
		if (typeof $ == 'function')
			sm_thisPageUsingOtherJSLibrary = true;
	
		    sm_jquery_loadOnDemand(function() {	            
	
				if (typeof jQuery != 'undefined') {
			
				   if (sm_thisPageUsingOtherJSLibrary)
						$.noConflict(); 
	
					sm_guid_addLinkTracking(sm_cmptrk_getCookie('bisSMGUID'));     
						
				}
	
			});   
	
	}
	else
		sm_guid_addLinkTracking(sm_cmptrk_getCookie('bisSMGUID')); 	
	
}

function sm_extractHostname(url) {
    var hostname;
    //find & remove protocol (http, ftp, etc.) and get hostname

    if (url.indexOf("://") > -1) {
        hostname = url.split('/')[2];
    }
    else {
        hostname = url.split('/')[0];
    }

    //find & remove port number
    hostname = hostname.split(':')[0];
    //find & remove "?"
    hostname = hostname.split('?')[0];

    return hostname;
}

function sm_extractRootDomain(url) {
    var domain = sm_extractHostname(url),
        splitArr = domain.split('.'),
        arrLen = splitArr.length;

    //extracting the root domain here
    if (arrLen > 2) {
        domain = splitArr[arrLen - 2] + '.' + splitArr[arrLen - 1];
    }
    return domain;
}
