roshanoracle
3/20/2020 - 2:21 PM

Adobe Target Integration Code : Async : AT.js

// Create object to store functions
window.bk_so_integration = window.bk_so_integration || {};
window.bk_so_integration.functions = window.bk_so_integration.functions || {};
window.bk_so_integration.data = window.bk_so_integration.data || {};
window.bk_so_integration.config = window.bk_so_integration.config || {};

// CONFIG : EDIT THIS PART

// BlueKai Config
window.bk_so_integration.config.bluekai_jsonreturn_id = JSONRETURNCONTAINERID; // Oracle will supply with you with the ID to use here
window.bk_so_integration.config.wait_in_ms = 1; // How long to wait before asking BlueKai for the latest categories and firing data to third party (default 5000ms)
window.bk_so_integration.config.include_audience_names = true; // Set to false to not share audience names to any vendors
window.bk_so_integration.config.enable_cookie = false;

// Vendor code : Adobe Target
window.bk_so_integration.config.enable_adobetarget = true;
window.bk_so_integration.config.adobe_at_js = true;
window.bk_so_integration.config.adobe_company = "ADOBECOMPANYNAME"; // Set to company name (usually in COMPANYNAMEHERE.tt.omtrdc.net in mbox code)

/*
 * ##########################################################################################
 * DO NOT EDIT BELOW THIS LINE
 * ##########################################################################################
 */

// FUNCTION : Looper
window.bk_so_integration.functions.looper = function(function_condition, function_execute, delay, loop_max, loop_count) {

	setTimeout(function() {

		bk_so_integration.functions.logger('LOOPER : start loop');
		bk_so_integration.functions.logger('LOOPER : looping in ' + delay + "ms for a maximum of " + loop_max + " loops");

		// add loop counter to set a max
		condition = function_condition()
		loop_count = loop_count || 0; // calculate current loop		
		loop_count++ // increase loop count				

		bk_so_integration.functions.logger("LOOPER : loop count = " + loop_count);

		// figure out if loop should stop

		if (condition) {

			bk_so_integration.functions.logger("LOOPER : loop condition completed");
			bk_so_integration.functions.logger("LOOPER : stopping loop");
			function_execute();

		} else if (loop_count < loop_max) {

			bk_so_integration.functions.logger('LOOPER : loop again');
			window.bk_so_integration.functions.looper(function_condition, function_execute, delay, loop_max, loop_count);

		} else {

			bk_so_integration.functions.logger("LOOPER : loop max exceeded");
			bk_so_integration.functions.logger("LOOPER : stopping loop");
		}

	}, delay);
}

// FUNCTION : Local Storage Send
bk_so_integration.functions.localstorage_cookie_sender = function(data, name_of_var) {

	// Set data in first-party cookie if required
	if (window.bk_so_integration.config.enable_cookie || window.bk_so_integration.config.enable_google_optimize) {

		// encode cookie value if sending audience names
		var cookie_data = (name_of_var === "bk_audience_names") ? encodeURIComponent(data).replace(/'/g, "%27").replace(/"/g, "%22") : data;

		document.cookie = name_of_var + "=" + cookie_data + ";path=/;domain=." + location.hostname.split('.').reverse()[1] + "." + location.hostname.split('.').reverse()[0] + ";expires=Thu, 31 Dec 2099 00:00:00 GMT";

		bk_so_integration.functions.logger("COOKIES : storing '" + JSON.stringify(cookie_data) + "' as '" + name_of_var +
			"' cookie");
	}

	if (typeof(Storage) !== "undefined") {

		bk_so_integration.functions.logger("LOCAL STORAGE : storing '" + JSON.stringify(data) + "' as '" + name_of_var +
			"' in local storage");
		localStorage.setItem(name_of_var, JSON.stringify(data));

	} else {

		bk_so_integration.functions.logger("LOCAL STORAGE : SEND DATA : HTML 5 NOT SUPPORTED");
		return "no storage"; // HTML 5 NOT SUPPORTED
	}

}

// FUNCTION : Local Storage Retrieve
bk_so_integration.functions.localstorage_retriever = function(name_of_var) {

	if (typeof(Storage) !== "undefined") {

		var result = JSON.parse(localStorage.getItem(name_of_var));
		if (!result) {
			bk_so_integration.functions.logger("Local Storage : no " + name_of_var +
				" values available in local storage. Setting to empty array.");
			return [];
		}
		bk_so_integration.functions.logger("Local Storage : Retrieved following '" + name_of_var +
			"' from local storage : " + result);
		return result;
	}

}

// FUNCTION : Local Storage fallback
bk_so_integration.functions.localstorage_fallback = function() {

	bk_so_integration.functions.logger("Local Storage : attempting fallback");

	// category IDs
	if (typeof(Storage) !== "undefined") {

		window.bk_so_integration.data.bk_category_ids = bk_so_integration.functions
			.localstorage_retriever("bk_cat_ids");
		window.bk_so_integration.data.bk_campaign_ids = bk_so_integration.functions
			.localstorage_retriever("bk_campaign_ids");
		if (window.bk_so_integration.config.include_audience_names) {
			window.bk_so_integration.data.bk_audience_names = bk_so_integration.functions
				.localstorage_retriever("bk_audience_names");
		}

		// Send data
		if (window.bk_so_integration.data.bk_campaign_ids.length > 0) {
			bk_so_integration.functions.sendTargets();
		}

	} else {
		bk_so_integration.functions.logger("LOCAL STORAGE : SEND DATA : HTML 5 NOT SUPPORTED");
		return "no storage"; // HTML 5 NOT SUPPORTED
	}
}

bk_so_integration.functions.logger = function(message, attribute_object) {

	if (document.location.href.indexOf('bk_so_logger=true') > -1) {

		setCookie = function(cookieName, cookieValue, sessionCookieFlag) {
			
			function get_top_domain() {
				var i, h,
					weird_cookie = 'weird_get_top_level_domain=cookie',
					hostname = document.location.hostname.split('.');
				for (i = hostname.length - 1; i >= 0; i--) {
					h = hostname.slice(i).join('.');
					document.cookie = weird_cookie + ';domain=.' + h + ';';
					if (document.cookie.indexOf(weird_cookie) > -1) {
					// We were able to store a cookie! This must be it
					document.cookie = weird_cookie.split('=')[0] + '=;domain=.' + h + ';expires=Thu, 01 Jan 1970 00:00:01 GMT;';
					return h;
					}
				}
			}

			cookieDetails = cookieName + "=" + cookieValue + ";path=/;domain=." + get_top_domain() + ";expires=";
			if (!sessionCookieFlag) {
				cookieDetails += "Thu, 31 Dec 2099 00:00:00 GMT"
			}

			document.cookie = cookieDetails;

		};

		// session cookie
		setCookie("bk_so_logger","true",true);
		
	}

	if (document.cookie.indexOf('bk_so_logger=true') > -1) {

		if (typeof attribute_object === "undefined") {
			console.log("BLUEKAI SO : " + message);
		} else {
			for (varName in attribute_object) {
				console.log("BLUEKAI SO : " + message + varName + "=" + attribute_object[varName]);
			}
		}
	}

};

bk_so_integration.functions.arrayAddUnique = function(array, entry) {
	if (array.indexOf(entry) < 0) {
		array.push(entry);
	}

}

// FUNCTION : Parse BlueKai data and send to DFP
bk_so_integration.functions.parseBkResults = function() {

	// Parse BlueKai Campaign Results
	window.bk_so_integration.data.bk_category_ids = [];
	window.bk_so_integration.data.bk_campaign_ids = [];
	window.bk_so_integration.data.bk_audience_names = [];

	if (typeof(bk_results) != "undefined") {

		if (typeof(bk_results.campaigns[0]) != "undefined") {

			bk_so_integration.functions.logger("'bk_results' object found");

			for (var i = 0; i < bk_results.campaigns.length; i++) {

				var campaignId = bk_results.campaigns[i].campaign

				bk_so_integration.functions.arrayAddUnique(window.bk_so_integration.data.bk_campaign_ids, campaignId);

				if (window.bk_so_integration.config.include_audience_names) {

					var audience_name = bk_results.campaigns[i].BkDmpAudienceName;

					if (typeof(audience_name) != "undefined") {
						audience_name = decodeURIComponent(audience_name.replace(/\+/g, " ")); // decode URI
						bk_so_integration.functions.logger("Audience name found: " + audience_name);
						bk_so_integration.functions.arrayAddUnique(window.bk_so_integration.data.bk_audience_names,
							audience_name)
					}

				}
				for (var j = 0; j < bk_results.campaigns[i].categories.length; j++) {

					if (typeof(bk_results.campaigns[i].categories[j].categoryID) != "undefined") {

						var categoryId = bk_results.campaigns[i].categories[j].categoryID;

						bk_so_integration.functions.arrayAddUnique(window.bk_so_integration.data.bk_category_ids,
							categoryId);

					}
				}
			}

			// Send data to Local Storage
			bk_so_integration.functions
				.localstorage_cookie_sender(window.bk_so_integration.data.bk_category_ids, "bk_cat_ids");
			bk_so_integration.functions.localstorage_cookie_sender(window.bk_so_integration.data.bk_campaign_ids,
				"bk_campaign_ids");
			if (window.bk_so_integration.config.include_audience_names) {
				bk_so_integration.functions.localstorage_cookie_sender(window.bk_so_integration.data.bk_audience_names,
					"bk_audience_names");
			}

			// Send data to DFP
			bk_so_integration.functions.sendTargets();

		} else {

			bk_so_integration.functions.logger("No campaigns object");
		}
	}
}

bk_so_integration.functions.sendTargets = function() {

	bk_so_integration.functions.logger("Determine target systems to send data");


	if (window.bk_so_integration.config.enable_adobetarget) {
		bk_so_integration.functions.sendATT();
	}


}

/*
 * ##########################################################################################
 * ADOBE TEST AND TARGET CODE
 * ##########################################################################################
 */

bk_so_integration.functions.sendATT = function() {

	// Check Target Version
	if (window.bk_so_integration.config.adobe_at_js) {

		// AT JS integration
		bk_so_integration.functions.logger("BLUEKAI ADOBE TARGET : AT JS Method Declared");

		// Loop until adobe.target available		
		var adobe_target_check = function() {
			if (window.adobe && window.adobe.target && window.adobe.target.getOffer) {
				return true
			}
		};

		var adobe_target_run = function() {

			var profile_params = {
				"profile.bkCampaignIds": "|" + window.bk_so_integration.data.bk_campaign_ids.join("|") + "|",
				"profile.bkCategoryIds": "|" + window.bk_so_integration.data.bk_category_ids.join("|") + "|",
			}

			if (window.bk_so_integration.data.bk_audience_names) {
				profile_params["profile.bkAudienceNames"] = "|" + window.bk_so_integration.data.bk_audience_names.join("|") + "|";
			}

			bk_so_integration.functions.logger("BLUEKAI ADOBE TARGET : Calling adobe.target.getOffer()");

			adobe.target.getOffer({
				'mbox': 'bk_data_feed',
				'params': profile_params,
				'success': function(offers) {

					bk_so_integration.functions.logger("BLUEKAI ADOBE TARGET : adobe.target.getOffer() successful");

				},
				'error': function(status, error) {
					bk_so_integration.functions.logger("BLUEKAI ADOBE TARGET : adobe.target.getOffer() fail - see below");
					bk_so_integration.functions.logger(status);
					bk_so_integration.functions.logger(error);
				},
				'timeout': 500
			});


		};

		// Begin loop
		window.bk_so_integration.functions.looper(adobe_target_check, adobe_target_run, 500, 30);

	} else {

		// Non-AT JS integration
		bk_so_integration.functions.logger("BLUEKAI ADOBE TARGET : NON-AT JS Method Declared");


		// Parse BlueKai Campaign Results
		window.bk_so_integration.data.insertProfileBKCamps = ("profile.bkCampaignIds=|" + window.bk_so_integration.data.bk_campaign_ids
			.join("|") + "|");
		window.bk_so_integration.data.insertProfileBKCatIds = ("profile.bkCategoryIds=|" + window.bk_so_integration.data.bk_category_ids
			.join("|") + "|");

		if (window.bk_so_integration.config.include_audience_names) {
			window.bk_so_integration.data.insertProfileBKAudienceNames = ("profile.bkAudienceNames=|" + window.bk_so_integration.data.bk_audience_names
				.join("|") + "|");
		}

		// Declare Profile Params
		window.bk_so_integration.data.profileParams = window.bk_so_integration.data.insertProfileBKCamps + "&" + window.bk_so_integration.data.insertProfileBKCatIds;
		if (window.bk_so_integration.data.insertProfileBKAudienceNames) {}
		window.bk_so_integration.data.profileParams += "&" + window.bk_so_integration.data.insertProfileBKAudienceNames;

		var img_url = "//" + window.bk_so_integration.config.adobe_company + ".tt.omtrdc.net/m2/" +
			window.bk_so_integration.config.adobe_company + "/ubox/image?mbox=bk_data_feed&" + window.bk_so_integration.data.profileParams;

		img_url = img_url + "&mboxDefault\x3d//tags.bkrtx.com/1x1.gif";

		// Parse BlueKai Campaign Results
		(new Image).src = img_url;

		bk_so_integration.functions.logger("BLUEKAI ADOBE TARGET : Profile Pixel fired");
		bk_so_integration.functions.logger("BLUEKAI ADOBE TARGET : Pixel URL: " + img_url);
	}

}

// FUNCTION : Call BlueKai
bk_so_integration.functions.callBlueKai = function(bluekai_jsonreturn_id) {

	// Check if JSON return tag and bk_results already there
	if ((window.bk_results) &&
		(document.head && document.head.innerHTML.indexOf(bluekai_jsonreturn_id + '?ret=js') > -1) ||
		(document.body && document.body.innerHTML.indexOf(bluekai_jsonreturn_id + '?ret=js') > -1)) {

		bk_so_integration.functions.logger("JSON Return tag found");
		bk_so_integration.functions.logger("Parsing 'bk_results' directly");
		bk_so_integration.functions.parseBkResults(); // Parse results (don't
		// call JSON ret tag)

	} else {

		bk_so_integration.functions.logger("JSON Return tag NOT found");
		bk_so_integration.functions.localstorage_fallback(); // Grab from
		// local storage
		bk_so_integration.functions.logger("Waiting " + window.bk_so_integration.config.wait_in_ms +
			"ms before calling JSON Return Tag");

		setTimeout(function() {

			bk_so_integration.functions.logger("Calling JSON Return tag");
			var bk_json_ret = document.createElement("script");
			bk_json_ret.type = "text/javascript";
			bk_json_ret.onload = function() {
				bk_so_integration.functions.logger("JSON Return tag loaded");
				bk_so_integration.functions.logger("Parsing 'bk_results'");
				bk_so_integration.functions.parseBkResults(); // Parse results
			};
			bk_json_ret.src = "//tags.bluekai.com/site/" + bluekai_jsonreturn_id +
				"?ret=js&limit=1&phint=integration=so";

			document.head.appendChild(bk_json_ret);

		}, window.bk_so_integration.config.wait_in_ms);
	}
};

// CONFIG LOGGING : Loop through config and log
for (configs in window.bk_so_integration.config) {

	bk_so_integration.functions.logger("CONFIG : " + configs + " = " + window.bk_so_integration.config[configs]);

}

// RUN CODE
bk_so_integration.functions.callBlueKai(window.bk_so_integration.config.bluekai_jsonreturn_id);