Skip to content

Instantly share code, notes, and snippets.

@englehardt
Created April 11, 2018 02:28
Show Gist options
  • Save englehardt/db3ecea255ccd6aa2b0cb73ca76257d6 to your computer and use it in GitHub Desktop.
Save englehardt/db3ecea255ccd6aa2b0cb73ca76257d6 to your computer and use it in GitHub Desktop.
No boundaries: OnAudience script (http://api.behavioralengine.com/scripts/be-init.js)
var JSON;
if (!JSON) JSON = {};
(function() {
function f(a) {
return a < 10 ? "0" + a : a
}
function quote(a) {
escapable.lastIndex = 0;
return escapable.test(a) ? '"' + a.replace(escapable, function(a) {
var b = meta[a];
return typeof b === "string" ? b : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)
}) + '"' : '"' + a + '"'
}
function str(a, b) {
var c, d, e, f, g = gap,
h, i = b[a];
if (i && typeof i === "object" && typeof i.toJSON === "function") i = i.toJSON(a);
if (typeof rep === "function") i = rep.call(b, a, i);
switch (typeof i) {
case "string":
return quote(i);
case "number":
return isFinite(i) ? String(i) : "null";
case "boolean":
case "null":
return String(i);
case "object":
if (!i) return "null";
gap += indent;
h = [];
if (Object.prototype.toString.apply(i) === "[object Array]") {
f = i.length;
for (c = 0; c < f; c += 1) h[c] = str(c, i) || "null";
e = h.length === 0 ? "[]" : gap ? "[\n" + gap + h.join(",\n" + gap) + "\n" + g + "]" : "[" + h.join(",") + "]";
gap = g;
return e
};
if (rep && typeof rep === "object") {
f = rep.length;
for (c = 0; c < f; c += 1)
if (typeof rep[c] === "string") {
d = rep[c];
e = str(d, i);
if (e) h.push(quote(d) + (gap ? ": " : ":") + e)
}
} else
for (d in i)
if (Object.prototype.hasOwnProperty.call(i, d)) {
e = str(d, i);
if (e) h.push(quote(d) + (gap ? ": " : ":") + e)
};
e = h.length === 0 ? "{}" : gap ? "{\n" + gap + h.join(",\n" + gap) + "\n" + g + "}" : "{" + h.join(",") + "}";
gap = g;
return e
}
};
"use strict";
if (typeof Date.prototype.toJSON !== "function") {
Date.prototype.toJSON = function(a) {
return isFinite(this.valueOf()) ? this.getUTCFullYear() + "-" + f(this.getUTCMonth() + 1) + "-" + f(this.getUTCDate()) + "T" + f(this.getUTCHours()) + ":" + f(this.getUTCMinutes()) + ":" + f(this.getUTCSeconds()) + "Z" : null
};
String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function(a) {
return this.valueOf()
}
};
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap, indent, meta = {
"\b": "\\b",
" ": "\\t",
"\n": "\\n",
"\f": "\\f",
"\r": "\\r",
'"': '\\"',
"\\": "\\\\"
},
rep;
if (typeof JSON.stringify !== "function") JSON.stringify = function(a, b, c) {
var d;
gap = "";
indent = "";
if (typeof c === "number") {
for (d = 0; d < c; d += 1) indent += " "
} else if (typeof c === "string") indent = c;
rep = b;
if (b && typeof b !== "function" && (typeof b !== "object" || typeof b.length !== "number")) throw new Error("JSON.stringify");
return str("", {
"": a
})
};
if (typeof JSON.parse !== "function") JSON.parse = function(text, reviver) {
function walk(a, b) {
var c, d, e = a[b];
if (e && typeof e === "object")
for (c in e)
if (Object.prototype.hasOwnProperty.call(e, c)) {
d = walk(e, c);
if (d !== undefined) {
e[c] = d
} else delete e[c]
};
return reviver.call(a, b, e)
};
var j;
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) text = text.replace(cx, function(a) {
return "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)
});
if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) {
j = eval("(" + text + ")");
return typeof reviver === "function" ? walk({
"": j
}, "") : j
};
throw new SyntaxError("JSON.parse")
}
})();
var MD5 = function(string) {
function RotateLeft(lValue, iShiftBits) {
return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits))
}
function AddUnsigned(lX, lY) {
var lX4, lY4, lX8, lY8, lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8)
} else return (lResult ^ 0x40000000 ^ lX8 ^ lY8)
} else return (lResult ^ lX8 ^ lY8)
}
function F(x, y, z) {
return (x & y) | ((~x) & z)
}
function G(x, y, z) {
return (x & z) | (y & (~z))
}
function H(x, y, z) {
return (x ^ y ^ z)
}
function I(x, y, z) {
return (y ^ (x | (~z)))
}
function FF(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b)
}
function GG(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b)
}
function HH(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b)
}
function II(a, b, c, d, x, s, ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b)
}
function ConvertToWordArray(string) {
var lWordCount, lMessageLength = string.length,
lNumberOfWords_temp1 = lMessageLength + 8,
lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64,
lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16,
lWordArray = Array(lNumberOfWords - 1),
lBytePosition = 0,
lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
lByteCount++
};
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray
}
function WordToHex(lValue) {
var WordToHexValue = "",
WordToHexValue_temp = "",
lByte, lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2)
};
return WordToHexValue
}
function Utf8Encode(string) {
string = string.replace(/\r\n/g, "\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c)
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128)
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128)
}
};
return utftext
};
var x = Array(),
k, AA, BB, CC, DD, a, b, c, d, S11 = 7,
S12 = 12,
S13 = 17,
S14 = 22,
S21 = 5,
S22 = 9,
S23 = 14,
S24 = 20,
S31 = 4,
S32 = 11,
S33 = 16,
S34 = 23,
S41 = 6,
S42 = 10,
S43 = 15,
S44 = 21;
string = Utf8Encode(string);
x = ConvertToWordArray(string);
a = 0x67452301;
b = 0xEFCDAB89;
c = 0x98BADCFE;
d = 0x10325476;
for (k = 0; k < x.length; k += 16) {
AA = a;
BB = b;
CC = c;
DD = d;
a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
a = AddUnsigned(a, AA);
b = AddUnsigned(b, BB);
c = AddUnsigned(c, CC);
d = AddUnsigned(d, DD)
};
var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);
return temp.toLowerCase()
},
SHA1 = function(a) {
function b(a, b) {
var c = a << b | a >>> 32 - b;
return c
}
function c(a) {
var b = "",
c, d, e;
for (c = 0; c <= 6; c += 2) {
d = a >>> c * 4 + 4 & 15;
e = a >>> c * 4 & 15;
b += d.toString(16) + e.toString(16)
};
return b
}
function d(a) {
var b = "",
c, d;
for (c = 7; c >= 0; c--) {
d = a >>> c * 4 & 15;
b += d.toString(16)
};
return b
}
function e(a) {
a = a.replace(/\r\n/g, "\n");
var b = "";
for (var c = 0; c < a.length; c++) {
var d = a.charCodeAt(c);
if (d < 128) {
b += String.fromCharCode(d)
} else if (d > 127 && d < 2048) {
b += String.fromCharCode(d >> 6 | 192);
b += String.fromCharCode(d & 63 | 128)
} else {
b += String.fromCharCode(d >> 12 | 224);
b += String.fromCharCode(d >> 6 & 63 | 128);
b += String.fromCharCode(d & 63 | 128)
}
};
return b
};
var f, g, h, i = new Array(80),
j = 1732584193,
k = 4023233417,
l = 2562383102,
m = 271733878,
n = 3285377520,
o, p, q, r, s, t;
a = e(a);
var u = a.length,
v = new Array();
for (g = 0; g < u - 3; g += 4) {
h = a.charCodeAt(g) << 24 | a.charCodeAt(g + 1) << 16 | a.charCodeAt(g + 2) << 8 | a.charCodeAt(g + 3);
v.push(h)
};
switch (u % 4) {
case 0:
g = 2147483648;
break;
case 1:
g = a.charCodeAt(u - 1) << 24 | 8388608;
break;
case 2:
g = a.charCodeAt(u - 2) << 24 | a.charCodeAt(u - 1) << 16 | 32768;
break;
case 3:
g = a.charCodeAt(u - 3) << 24 | a.charCodeAt(u - 2) << 16 | a.charCodeAt(u - 1) << 8 | 128;
break
};
v.push(g);
while (v.length % 16 != 14) v.push(0);
v.push(u >>> 29);
v.push(u << 3 & 4294967295);
for (f = 0; f < v.length; f += 16) {
for (g = 0; g < 16; g++) i[g] = v[f + g];
for (g = 16; g <= 79; g++) i[g] = b(i[g - 3] ^ i[g - 8] ^ i[g - 14] ^ i[g - 16], 1);
o = j;
p = k;
q = l;
r = m;
s = n;
for (g = 0; g <= 19; g++) {
t = b(o, 5) + (p & q | ~p & r) + s + i[g] + 1518500249 & 4294967295;
s = r;
r = q;
q = b(p, 30);
p = o;
o = t
};
for (g = 20; g <= 39; g++) {
t = b(o, 5) + (p ^ q ^ r) + s + i[g] + 1859775393 & 4294967295;
s = r;
r = q;
q = b(p, 30);
p = o;
o = t
};
for (g = 40; g <= 59; g++) {
t = b(o, 5) + (p & q | p & r | q & r) + s + i[g] + 2400959708 & 4294967295;
s = r;
r = q;
q = b(p, 30);
p = o;
o = t
};
for (g = 60; g <= 79; g++) {
t = b(o, 5) + (p ^ q ^ r) + s + i[g] + 3395469782 & 4294967295;
s = r;
r = q;
q = b(p, 30);
p = o;
o = t
};
j = j + o & 4294967295;
k = k + p & 4294967295;
l = l + q & 4294967295;
m = m + r & 4294967295;
n = n + s & 4294967295
};
var t = d(j) + d(k) + d(l) + d(m) + d(n);
return t.toLowerCase()
};
if (typeof BUtilities === 'undefined') BUtilities = {
serverPath: '//api.behavioralengine.com/',
getCookie: function(cookieName) {
var i, name, value, cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
name = cookies[i].substr(0, cookies[i].indexOf('='));
value = cookies[i].substr(cookies[i].indexOf('=') + 1);
name = name.replace(/^\s+|\s+$/g, '');
if (name === cookieName) return unescape(value)
}
},
setCookie: function(name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var cookieValue = escape(value) + ((exdays === null) ? '' : ';path=/; expires=' + exdate.toUTCString());
document.cookie = name + '=' + cookieValue
},
prepareGet: function(params) {
if (typeof params === 'undefined') return '';
var get = [];
for (var param in params) get.push(param + '=' + params[param]);
if (get.length > 0) return '?' + get.join('&');
return ''
},
sendRequest: function(action, params, callback) {
BCallbackManager.setCallback(action, callback);
var url = BUtilities.serverPath + action + '/';
if (typeof params === 'undefined') params = {};
params.v = '3.0';
BUtilities.getScript(url, params)
},
sendApiRequest: function(action, params, callback) {
BCallbackManager.setCallback(action, callback);
var url = BUtilities.serverPath + 'api/' + action + '/';
if (typeof params === 'undefined') params = {};
params.v = '3.0';
BUtilities.getScript(url, params)
},
sendPostRequest: function(action, getParams, postParams, callback) {
BCallbackManager.setCallback(action, callback);
BUtilities.sendPost(BUtilities.serverPath + action + BUtilities.prepareGet(getParams), postParams, function() {
BCallbackManager.callback(action, {})
})
},
sendPost: function(target, params, callback) {
var transactionHash = BUtilities.generateHash('' + Math.random()),
iframe = document.createElement('iframe');
document.getElementsByTagName('body')[0].appendChild(iframe);
iframe.contentWindow.name = transactionHash;
iframe.style.display = 'none';
iframe.onload = function() {
if (typeof callback === 'function') callback();
window.setTimeout(function() {
if (typeof iframe.parentNode !== 'undefined' && iframe.parentNode !== null) iframe.parentNode.removeChild(iframe);
if (typeof form.parentNode !== 'undefined' && form.parentNode !== null) form.parentNode.removeChild(form)
}, 500)
};
var form = document.createElement('form');
form.target = transactionHash;
form.action = target;
form.method = 'POST';
var inputs = [];
for (var name in params) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = params[name];
form.appendChild(input);
inputs.push(input)
};
document.getElementsByTagName('body')[0].appendChild(form);
form.submit()
},
sendScriptRequest: function(name, action, callback) {
BCallbackManager.setCallback(name, callback);
BUtilities.getScript(BUtilities.serverPath + action)
},
generateHash: function(string) {
return window.SHA1(string)
},
newThread: function(toRun) {
setTimeout(function() {
try {
toRun()
} catch (exc) {}
}, 1)
},
getScript: function(url, getParams, scriptParams) {
var trigger = false,
crossInit = document.createElement('script');
crossInit.setAttribute('type', 'text/javascript');
crossInit.setAttribute('src', url + BUtilities.prepareGet(getParams));
if (typeof scriptParams !== 'undefined')
for (var currentParam in scriptParams) crossInit.setAttribute('data-' + currentParam, params[currentParam]);
if (typeof document.head !== 'undefined') {
document.head.appendChild(crossInit)
} else document.getElementsByTagName('head')[0].appendChild(crossInit);
crossInit.onload = function() {
if (typeof this.parentNode !== 'undefined' && this.parentNode !== null) {
trigger = true;
this.parentNode.removeChild(this)
}
};
if (trigger === false) crossInit.onreadystatechange = function() {
if (this.readyState === 'loaded' && typeof this.parentNode !== 'undefined') this.parentNode.removeChild(this)
}
},
getNumericHash: function(plain) {
var hash = 0,
i, char;
plain = plain + "";
if (plain.length === 0) return hash;
for (i = 0, l = plain.length; i < l; i++) {
char = plain.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash |= 0
};
return hash
},
isNumber: function(value) {
return !isNaN(parseFloat(value)) && isFinite(value)
}
}
function BAdblockChecker(target) {
var self = this;
this.cause = function() {
function loadAdblockCauses(globalConf) {
var container = createAdblockCauses(globalConf.causesConf);
return function(key) {
return container[key]
}
}
function createAdblockCauses(causesConf) {
var container = {};
for (var i = 0; i < causesConf.length; ++i) container[causesConf[i].key] = causesConf[i].value;
return container
}
function createInstanceLoader(instance) {
return function() {
return instance
}
}
function load() {
var instance = loadAdblockCauses(self.globals());
self.cause = createInstanceLoader(instance);
return instance
};
return load()
};
this.globals = function() {
var Internals = null
function init() {
Internals = self.Internals();
return globalData()
}
function getHttpHeaders() {
return {
contentType: Internals.CONTENT_TYPE,
contentLength: Internals.CONTENT_LENGTH
}
}
function getMimeTypes() {
return {
form: Internals.FORM_WWW
}
}
function getHttpConf() {
return {
post: Internals.POST,
get: Internals.GET,
headersContainer: getHttpHeaders(),
mimeTypes: getMimeTypes(),
keyValueSeparator: Internals.KEY_VALUE_SEPARATOR,
querySeparator: Internals.QUERY_SEPARATOR,
queryMarker: Internals.QUERY_MARKER
}
}
function getLoggerConf() {
return {
success: Internals.ADBLOCK_SUCCESS,
error: Internals.ADBLOCK_ERR
}
}
function loadCausesConf() {
return [{
key: Internals.AJAXFAIL_CODE,
value: Internals.AJAXFAIL_MESSAGE
}, {
key: Internals.IMAGEFAIL_CODE,
value: Internals.IMAGEFAIL_MESSAGE
}, {
key: Internals.IMAGEHIDDEN_CODE,
value: Internals.IMAGEHIDDEN_MESSAGE
}, {
key: Internals.NOADBLOCK_CODE,
value: Internals.NOADBLOCK_MESSAGE
}]
}
function causesCodes() {
return {
AJAX: Internals.AJAXFAIL_CODE,
IMAGE_ERR: Internals.IMAGEFAIL_CODE,
IMAGE_EMPTY: Internals.IMAGEHIDDEN_CODE,
NO_ADBLOCK: Internals.NOADBLOCK_CODE
}
}
function globalData() {
return {
domain: Internals.AD_DOMAIN,
imageDest: Internals.IMAGE_DEST,
imageDestWidth: Internals.IMAGE_DEST_WIDTH,
responseType: Internals.ARRAYBUFFER,
showMode: Internals.NONE,
causesConf: loadCausesConf(),
codes: causesCodes(),
logger: self.logger(getLoggerConf()),
http: self.http(getHttpConf())
}
}
function createInstanceLoader(instance) {
return function() {
return instance
}
}
function loadGlobals() {
var instance = init();
self.globals = createInstanceLoader(instance);
return instance
};
return loadGlobals()
};
this.handler = function() {
function createResponseHandler(conf, cause) {
return {
response: {
type: conf.responseType,
onstart: function() {},
handle: function() {}
},
cause: cause
}
}
function createHandler(conf) {
var logger = conf.logger(),
ajax = conf.http(),
responseHandler = createResponseHandler(conf, self.cause());
return new Handler(ajax, logger, responseHandler)
}
function Handler(ajax, logger, responseHandler) {
var userConf = null;
this.success = function(code) {
var dmp;
for (var i = 0; i < userConf.length; i++) {
dmp = userConf[i];
new Image().src = this.getUrl(dmp, code)
}
};
this.getUrl = function(dmp, code) {
var params = this.buildParams(dmp.keys, dmp.codes[code]),
url = dmp.url;
if (params.length > 0) url += '?' + params.join('&');
return url
};
this.buildParams = function(keys, params) {
var urlParams = [];
for (var i = 0; i < keys.length; i++)
if (params[keys[i]]) urlParams.push(keys[i] + "=" + params[keys[i]]);
return urlParams
};
this.loadUserConf = function(confData) {
userConf = confData
};
this.ping = function(dest, parameters) {
ajax.get(dest, parameters, responseHandler.response)
}
}
function createInstanceLoader(instance) {
return function() {
return instance
}
}
function load() {
var instance = createHandler(self.globals());
self.handler = createInstanceLoader(instance);
return instance
};
return load()
};
this.http = function(conf) {
var instance = null
function Http(headersContainer, mimeTypes) {
function setHeaders(xhr, headers) {
for (var i = 0; i < headers.length; ++i) xhr.setRequestHeader(headers[i].name, headers[i].content)
}
function sendRequest(request) {
setHeaders(request.xhr, request.headers);
request.xhr.send(request.data)
}
function createRequest(response) {
var request = null;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest()
} else request = new ActiveXObject();
return prepareResponseHandler(request, response)
}
function makeRequest(dest, method, response) {
var xhr = createRequest(response);
xhr.open(method, dest, true);
return xhr
}
function buildQueryElement(key, value) {
return [key, value].join(conf.keyValueSeparator)
}
function buildQuery(parameters) {
var queryElements = [];
for (var key in parameters) queryElements.push(buildQueryElement(key, parameters[key]));
return queryElements.join(conf.querySeparator)
}
function getMimeType(xhr) {
return xhr.getResponseHeader(headersContainer.contentType)
}
function onStartHandler(xhr, response) {
xhr.responseType = response.type;
response.onstart()
}
function handleResponse(xhr, response) {
switch (xhr.readyState) {
case 1:
onStartHandler(xhr, response);
break;
case 2:
break;
case 3:
break;
case 4:
response.handle(xhr.status, xhr.response, getMimeType(xhr));
break;
default:
break
}
}
function createResponseHandler(xhr, response) {
return function() {
handleResponse(xhr, response)
}
}
function prepareResponseHandler(xhr, response) {
xhr.onreadystatechange = createResponseHandler(xhr, response);
return xhr
}
function getPostHeaders(length) {
return [{
name: headersContainer.contentType,
content: mimeTypes.form
}, {
name: headersContainer.contentLength,
content: length
}]
}
function getDestination(dest, parameters) {
if (Object.keys(parameters).length > 0) {
var query = buildQuery(parameters);
dest += conf.queryMarker + query
};
return dest
};
this.get = function(dest, parameters, response) {
dest = getDestination(dest, parameters);
var request = {
xhr: makeRequest(dest, conf.get, response),
headers: [],
data: null
};
sendRequest(request)
};
this.post = function(dest, parameters, response) {
var query = buildQuery(parameters),
request = {
xhr: makeRequest(dest, conf.post, response),
headers: getPostHeaders(query.length),
data: query
};
sendRequest(request)
}
}
function getInstance() {
if (instance == null) instance = new Http(conf.headersContainer, conf.mimeTypes);
return instance
};
return getInstance
};
this.Internals = function() {
var internals = {
AD_DOMAIN: "http://ced.sascdn.com",
IMAGE_DEST: "http://hit.behavioralengine.com/advertisement/ad.png",
IMAGE_DEST_WIDTH: 100,
KEY_VALUE_SEPARATOR: '=',
POST: "POST",
GET: "GET",
QUERY_SEPARATOR: '&',
QUERY_MARKER: '?',
CONTENT_TYPE: "Content-Type",
CONTENT_LENGTH: "Content-Length",
FORM_WWW: "application/x-www-form-urlencoded",
ADBLOCK_SUCCESS: "Adblock due to ",
ADBLOCK_ERR: "No adblock",
ARRAYBUFFER: "arraybuffer",
NONE: 'none',
AJAXFAIL_CODE: 1,
IMAGEFAIL_CODE: 2,
IMAGEHIDDEN_CODE: 3,
NOADBLOCK_CODE: 4,
AJAXFAIL_MESSAGE: "XmlHttpRequest failed (Adblock Plus in Gecko)",
IMAGEFAIL_MESSAGE: "image loading failed (Adblock Plus in Webkit)",
IMAGEHIDDEN_MESSAGE: "hiding loaded resource (old version of Adblock)",
NOADBLOCK_MESSAGE: "no adblock or adblock disabled"
}
function loadInternals(internals) {
return function() {
return internals
}
}
function load() {
self.Internals = loadInternals(internals);
return internals
};
return load()
};
this.logger = function(conf) {
var instance = null
function Logger() {
function format(cause) {
return conf.success + cause
};
this.success = function(cause) {
console.log(format(cause))
};
this.error = function() {
console.log(conf.error)
}
}
function getInstance() {
if (instance == null) instance = new Logger();
return instance
};
return getInstance
};
this.adblockCheck = function(target) {
var handler = null,
conf = null,
codes = null
function init() {
handler = self.handler();
conf = self.globals();
handler.loadUserConf(prepareUserConf(conf.userConf));
codes = conf.codes
}
function prepareUserConf(clientConf) {
return BehavioralEngine.getBAdblockCheckerUserConf()
}
function ajaxCheck() {
var result = false;
try {
handler.ping(conf.domain, {});
result = true
} catch (err) {};
return result
}
function imageCheck() {
var image = createTestImage();
image.onload = createImageLoadHandler();
image.onerror = createImageErrorHandler();
image.src = conf.imageDest
}
function createTestImage() {
var image = new Image();
image.style.display = conf.showMode;
image.width = conf.imageDestWidth;
target.appendChild(image);
return image
}
function check() {
if (!ajaxCheck()) {
handler.success(codes.AJAX)
} else imageCheck()
}
function checkBlocked(image) {
return (image.width == 0)
}
function createImageLoadHandler() {
return function() {
var isBlocked = checkBlocked(this);
target.removeChild(this);
if (isBlocked) {
handler.success(codes.IMAGE_EMPTY)
} else handler.success(codes.NO_ADBLOCK)
}
}
function createImageErrorHandler() {
return function() {
target.removeChild(this);
handler.success(codes.IMAGE_ERR)
}
}
function run() {
init();
check()
};
run()
};
this.adblockCheck(target)
};
if (typeof BEvent === 'undefined') {
var BEvent = function BEvent(name, callbacks, enabled) {
this.name = (typeof name === 'undefined' ? '' : name);
this.callbacks = (typeof callbacks === 'undefined' ? [] : callbacks);
this.enabled = (typeof enabled === 'undefined' ? true : enabled)
};
BEvent.prototype = {
name: '',
callbacks: [],
enabled: true,
call: function(self, params) {
var result = true;
for (var i = 0; i < self.callbacks.length; i++) {
var callback = self.callbacks[i];
if (typeof callback === 'function') result &= callback(params)
};
return result
},
addCallback: function(self, callback) {
self.callbacks.push(callback)
}
}
};
if (typeof BEventManager === 'undefined') {
var BEventManager = function() {};
BEventManager.prototype = {
events: {},
registerEvent: function(self, event) {
self.events[event.name] = event
},
disableEvent: function(self, name) {
self.events[name].enabled = false
},
callEvent: function(self, name, params) {
var event = self.events[name];
return event.call(event, params)
},
addCallbackToEvent: function(self, name, callback) {
var event = self.events[name];
event.addCallback(event, callback)
}
}
};
if (typeof BCallbackManager === 'undefined') var BCallbackManager = {
callbacks: {},
callback: function(name, data) {
if (typeof BCallbackManager.callbacks[name] === 'function') BCallbackManager.callbacks[name](data)
},
setCallback: function(name, callback) {
BCallbackManager.callbacks[name] = callback
}
};
if (typeof BBlock === 'undefined') {
var BBlock = function(reference, weight, instant, seenBeginning, seenEnding) {
this.reference = (typeof reference === 'undefined' ? null : reference);
this.weight = (typeof weight === 'undefined' ? null : weight);
this.instant = (typeof instant === 'undefined' ? false : instant);
this.seenBeginning = (typeof seenBeginning === 'undefined' ? false : seenBeginning);
this.seenEnding = (typeof seenEnding === 'undefined' ? false : seenEnding)
};
BBlock.prototype = {
reference: null,
weight: null,
instant: false,
seenBeginning: false,
seenEnding: false
}
};
if (typeof BDebug === 'undefined') var BDebug = {
isDebugEnabled: false,
data: [],
init: function() {
BDebug.log('BDebug initiated');
if (BUtilities.getCookie('debug') == 1) BDebug.isDebugEnabled = true
},
log: function(param) {
BDebug.data.push(param)
},
print: function() {
var data = BDebug.data;
for (var i = 0; i < data.length; i++) console.log(data[i])
}
};
if (typeof BProfiler === 'undefined') BProfiler = {
map: {},
startTest: function(name) {
var item = {
name: name,
start: new Date().getTime(),
end: null,
diff: 0
};
BProfiler.map[name] = item.start;
BProfiler.saveItem(item.start, item, true)
},
endTest: function(name) {
var k = BProfiler.map[name];
if (typeof k === 'undefined') return false;
var item = BProfiler.getItem(k);
if (!item) return false;
item.end = new Date().getTime();
item.diff = item.end - item.start;
BProfiler.saveItem(k, item)
},
saveItem: function(key, value, isInsert) {
if (typeof localStorage === 'undefined') return false;
if (typeof localStorage.BProfiler === 'undefined') localStorage.BProfiler = '{"items":0}';
var storage = JSON.parse(localStorage.BProfiler);
if (!storage) return;
if (typeof isInsert !== 'undefined' && isInsert === true) storage.items++;
storage[key] = value;
localStorage.BProfiler = JSON.stringify(storage)
},
getItem: function(key) {
if (typeof localStorage === 'undefined') return null;
if (typeof localStorage.BProfiler === 'undefined') return null;
var storage = JSON.parse(localStorage.BProfiler);
if (!storage) return null;
return storage[key]
},
sendItems: function() {
if (typeof localStorage === 'undefined') return false;
if (typeof localStorage.BProfiler === 'undefined') return false;
var storage = JSON.parse(localStorage.BProfiler);
if (!storage) return false;
if (storage.items > 20) {
if (Math.floor(Math.random() * 100) === 1) BUtilities.sendPostRequest('profiler/saveRequestStats', {}, {
data: localStorage.BProfiler
});
localStorage.BProfiler = '{"items":0}'
}
},
showStats: function() {
var storage = JSON.parse(localStorage.BProfiler);
for (var i in storage) console.log(i, storage[i])
}
};
if (typeof BAnalitic === 'undefined') {
var BAnalitic = function() {};
BAnalitic.prototype = {
behavioralEngine: null,
browserData: null,
data: {
emailHahs: null,
gender: null,
FBIdHash: null
},
flags: {
browserDataReady: false,
FBDataReady: false
},
checkBlockTimeOut: null,
emailRegexp: /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
onCreate: function(self, behavioralEngine) {
self.behavioralEngine = behavioralEngine;
var eventManager = self.behavioralEngine.eventManager;
eventManager.registerEvent(eventManager, new BEvent('callbackCheckBlockRequest', [function() {
self.setBlockFlag(self, false)
}]))
},
onStart: function(self) {
self.generateBrowserData(self);
self.fetchFBData(self);
self.checkBlock(self);
self.checkPrivacy(self);
self.checkId(self);
self.checkInputId(self)
},
generateBrowserData: function(self) {
var date = new Date();
self.browserData = {
datetime: date.toString(),
navigator: {
bro: window.navigator.appCodeName,
osa: window.navigator.platform,
osv: window.navigator.appVersion
},
screen: {
wid: window.screen.width,
hei: window.screen.height
},
language: {
lan: window.navigator.language,
lanie: window.navigator.userLanguage
},
location: encodeURIComponent(window.location.href),
referrer: document.referrer,
signature: self.getSignature(self)
};
self.browserDataReady = true
},
getBrowserData: function(self) {
return self.browserData
},
isBrowserDataSet: function(self) {
return self.browserDataReady
},
getSignature: function(self) {
var date = new Date(),
signature = ',' + self.getBrowserPlugins() + ',' + self.getMimeTypes() + ',' + window.navigator.appCodeName + ',' + window.navigator.appVersion + ',' + window.navigator.userAgent + ',' + window.navigator.appName + ',' + window.navigator.platform + ',' + window.navigator.cookieEnabled + ',' + window.navigator.onLine + ',' + window.navigator.product + ',' + window.navigator.buildID + ',' + window.navigator.oscpu + ',' + window.navigator.language + ',' + window.navigator.userLanguage + ',' + window.navigator.javaEnabled() + ',' + window.screen.width + ',' + window.screen.height + ',' + window.screen.colorDepth + ',' + window.screen.pixelDepth + ',' + date.getTimezoneOffset();
return BUtilities.generateHash(signature)
},
getBrowserPlugins: function(self) {
var BrowserPluginsString = '',
browserPlugins = window.navigator.plugins,
browserPluginLength = browserPlugins.length;
for (var j = 0; j < browserPluginLength; j++) BrowserPluginsString += browserPlugins[j].name + ',';
return BrowserPluginsString
},
getMimeTypes: function(self) {
var MimeTypesString = '',
browserMimeTypes = window.navigator.mimeTypes,
browserMimeTypesLength = browserMimeTypes.length;
for (var i = 0; i < browserMimeTypesLength; i++) MimeTypesString += browserMimeTypes[i].type + ',';
return MimeTypesString
},
fetchFBData: function(self) {
if (typeof FB !== 'undefined') self.sendFBApiRequest('gender, age_range, email', function(result) {
if (typeof result.error === 'undefined') {
self.data['data-hash-e'] = MD5(result.email);
self.data['data-hash-f'] = MD5(result.id);
self.data['data-attribute-s'] = self.parseGender(self, result.gender);
self.flags.FBDataReady = true;
self.behavioralEngine.flags.demographyData = true
} else self.sendFBApiRequest('gender, age_range', function(result) {
if (typeof result.error === 'undefined') {
self.data['data-hash-f'] = MD5(result.id);
self.data['data-attribute-s'] = self.parseGender(self, result.gender);
self.flags.FBDataReady = true;
self.behavioralEngine.flags.demographyData = true
}
})
})
},
sendFBApiRequest: function(fields, callback) {
try {
FB.api('/me', 'get', {
fields: fields
}, function(result) {
callback(result)
})
} catch (e) {}
},
parseGender: function(self, gender) {
switch (gender) {
case 'male':
return 'm';
case 'female':
return 'f';
default:
return ''
}
},
isFBDataReady: function(self) {
return self.flags.FBDataReady
},
getFBData: function(self) {
return self.data
},
checkBlock: function(self) {
self.checkBlockTimeOut = window.setTimeout(function() {
self.setBlockFlag(self, true)
}, 1e3);
BUtilities.getScript('//cdn.behavioralengine.com/scripts/btest/advertisement.js')
},
setBlockFlag: function(self, block) {
window.clearTimeout(self.checkBlockTimeOut);
if (block) {
self.behavioralEngine.flags.miscSet = true;
self.behavioralEngine.data.misc.ab = 1
}
},
checkPrivacy: function(self) {
var userAgent = window.navigator.userAgent;
if (window.webkitRequestFileSystem) {
window.webkitRequestFileSystem(window.TEMPORARY, 1, function() {
self.setPrivacy(self, false)
}, function(e) {
self.setPrivacy(self, true)
})
} else if (window.indexedDB && /Firefox/.test(userAgent)) {
var request;
try {
request = window.indexedDB.open('btest')
} catch (e) {
self.setPrivacy(self, true);
return
};
request.onerror = function(event) {
self.setPrivacy(self, true)
};
request.onsuccess = function() {
self.setPrivacy(self, false)
}
} else if (self.isIe(self, userAgent)) {
self.setPrivacy(self, false)
} else if (window.localStorage && /Safari/.test(userAgent)) self.setPrivacy(self, false)
},
setPrivacy: function(self, private) {
if (private) {
self.behavioralEngine.flags.miscSet = true;
self.behavioralEngine.data.misc.inc = 1
}
},
isIe: function(self, userAgent) {
userAgent = userAgent.toLowerCase();
if (userAgent.indexOf('msie') < 0 && userAgent.indexOf('trident') < 0) return false;
var match = /(?:msie|rv:)\s?([\d\.]+)/.exec(userAgent);
return (match && parseInt(match[1], 10) >= 10)
},
checkId: function(self) {
var container = document.createElement('div');
container.id = 'be-container';
container.style.display = 'none';
var form = document.createElement('form');
form.attributes.autocomplete = 'on';
var emailInput = document.createElement('input');
emailInput.attributes.vcard_name = 'vCard.Email';
emailInput.id = 'email';
emailInput.type = 'email';
emailInput.name = 'email';
form.appendChild(emailInput);
var passwordInput = document.createElement('input');
passwordInput.id = 'password';
passwordInput.type = 'password';
passwordInput.name = 'password';
form.appendChild(passwordInput);
container.appendChild(form);
document.body.appendChild(container);
window.setTimeout(function() {
if (self.emailRegexp.test(emailInput.value)) self.sendHash(self, MD5(emailInput.value));
document.body.removeChild(container)
}, 1e3)
},
checkInputId: function(self) {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('blur', BehavioralEngine.analitic.inputIdBlurHandle, false);
if (self.emailRegexp.test(inputs[i].value)) self.sendHash(self, MD5(inputs[i].value))
}
},
inputIdBlurHandle: function() {
var self = BehavioralEngine.analitic;
if (self.emailRegexp.test(this.value)) {
self.sendHash(self, MD5(this.value));
this.removeEventListener('blur', BehavioralEngine.analitic.inputIdBlurHandle, false)
}
},
sendHash: function(self, hash) {
new Image().src = 'http://api.behavioralengine.com/pixel?data-hash-e=' + hash + '&data-p=be_input'
}
}
};
if (typeof BSemantic === 'undefined') {
var BSemantic = function() {};
BSemantic.prototype = {
behavioralEngine: null,
allowedBlockTypes: [{
tag: 'td',
weight: 1,
instant: false
}, {
tag: 'div',
weight: 1,
instant: false
}, {
tag: 'p',
weight: 1,
instant: false
}, {
tag: 'span',
weight: 1,
instant: false
}, {
weight: 1.5,
tag: 'strong',
instant: true
}, {
weight: 1.4,
tag: 'em',
instant: true
}, {
weight: 1.4,
tag: 'i',
instant: true
}, {
weight: 1.5,
tag: 'b',
instant: true
}, {
weight: 1.2,
tag: 'blockquote',
instant: true
}, {
weight: 3,
tag: 'caption',
instant: true
}, {
weight: 1.2,
tag: 'q',
instant: true
}, {
weight: 1.3,
tag: 'th',
instant: true
}, {
weight: 1.2,
tag: 'cite',
instant: true
}, {
weight: 5,
tag: 'h1',
instant: true
}, {
weight: 2.5,
tag: 'h2',
instant: true
}, {
weight: 2,
tag: 'h3',
instant: true
}, {
weight: 6,
tag: 'title',
instant: true
}, {
weight: 3,
tag: 'meta',
instant: true
}],
blocks: [],
viewPort: {},
words: [],
scrollMaxDiff: 100,
minimumDisplacementLimit: 1,
ready: false,
seenWordsCount: 0,
onCreate: function(self, behavioralEngine) {
self.behavioralEngine = behavioralEngine
},
onStart: function(self) {
self.updateViewPort(self);
self.gatherAllBlocks(self);
self.setScrollWatcher(self);
self.pushInstantBlocks(self);
self.ready = true
},
gatherAllBlocks: function(self) {
for (i = 0; i < self.allowedBlockTypes.length; i++) {
var htmlTags = self.findHtmlTagsByType(self, self.allowedBlockTypes[i]);
for (j = 0; j < htmlTags.length; j++) self.blocks.push(new BBlock(htmlTags[j], self.allowedBlockTypes[i].weight, self.allowedBlockTypes[i].instant))
}
},
pushInstantBlocks: function(self) {
var toDelete = [];
for (i = 0; i < self.blocks.length; i++)
if (self.blocks[i].instant) {
self.pushBlock(self, self.blocks[i]);
toDelete.push(self.blocks[i])
};
self.removeBlocks(self, toDelete)
},
pushBlock: function(self, block) {
self.words = self.words.concat(self.getWordsFromBlock(self, block))
},
removeBlocks: function(self, blocks) {
for (var i = 0; i < blocks.length; i++) self.blocks.splice(self.blocks.indexOf(blocks[i]), 1)
},
popWords: function(self) {
var words = self.words;
self.seenWordsCount += words.length;
self.words = [];
return words
},
getSeenWordsCount: function(self) {
return self.seenWordsCount
},
getWordsCount: function(self) {
return self.words.length
},
getWordsFromBlock: function(self, block) {
var text = '',
nodeName = block.reference.nodeName.toLowerCase(),
allowedShortWords = {
cv: 1
};
switch (nodeName) {
case 'meta':
text = self.getTextFromMeta(self, block);
break;
default:
text = self.getTextFromBlockWithTextNodes(self, block)
};
if (text.length < 3) return [];
text = text.toLowerCase();
text = text.replace(/[.,\?!\:\t\n\r\[\]\{\}\%\^\!\_\-\'\"\(\)/„”]/g, ' ');
text = text.replace(/&[a-z0-9#]+;/gi, '');
text = text.replace(/\s+/gi, ' ');
text = text.replace(/^\s+|\s+$/g, '');
var words = text.split(' '),
wordsArray = [];
for (var i = 0; i < words.length; i++) {
if (BUtilities.isNumber(words[i])) continue;
if (words[i].length < 3 && allowedShortWords[words[i]] !== 1) continue;
wordsArray.push({
w: words[i],
s: block.weight
})
};
return wordsArray
},
getTextFromMeta: function(self, block) {
if (block.reference.name.toLowerCase() !== 'description') return '';
return block.reference.content
},
getTextFromBlockWithTextNodes: function(self, block) {
var text = '',
childNodes = block.reference.childNodes;
for (var i = 0; i < childNodes.length; i++)
if (childNodes[i].nodeType === 3)
if (typeof childNodes[i].textContent !== 'undefined') {
text += ' ' + childNodes[i].textContent
} else text += ' ' + childNodes[i].innerText;
return text
},
findHtmlTagsByType: function(self, type) {
return document.getElementsByTagName(type.tag)
},
setScrollWatcher: function(self) {
if (window.addEventListener) {
window.addEventListener('scroll', self.scrollEvent, false)
} else if (window.attachEvent) {
window.attachEvent('onscroll', self.scrollEvent)
} else if (typeof document.onscroll === 'function') {
document.onscroll = self.scrollEvent
} else {
var onScrollChain = document.onscroll;
document.onscroll = function() {
self.scrollEvent;
onScrollChain()
}
}
},
scrollEvent: function() {
var self = BehavioralEngine.semantic;
if (Math.abs(self.viewPort.top - self.getScrollY()) > self.scrollMaxDiff) {
self.readWordsFromBlocksInViewPort(self)
} else if (self.getScrollY() + window.innerHeight === self.getDocumentHeight()) {
self.readWordsFromBlocksInViewPort(self)
} else if (self.getScrollY() === 0) self.readWordsFromBlocksInViewPort(self)
},
getScrollY: function() {
return Math.max(document.documentElement.scrollTop, document.getElementsByTagName('body')[0].scrollTop)
},
getDocumentHeight: function() {
return Math.max(document.getElementsByTagName('body')[0].scrollHeight, document.documentElement.scrollHeight, document.getElementsByTagName('body')[0].offsetHeight, document.documentElement.offsetHeight, document.getElementsByTagName('body')[0].clientHeight, document.documentElement.clientHeight)
},
updateViewPort: function(self) {
self.viewPort = {
top: self.getScrollY(),
bottom: self.getScrollY() + window.innerHeight
}
},
readWordsFromBlocksInViewPort: function(self) {
self.updateViewPort(self);
self.pushVisibleBlocks(self);
self.behavioralEngine.eventManager.callEvent(self.behavioralEngine.eventManager, 'insertProbe')
},
isBlockVisible: function(self, block) {
var top = block.reference.offsetTop,
bottom = block.reference.offsetTop + block.reference.scrollHeight * self.minimumDisplacementLimit;
if (self.viewPort.top <= top && top <= self.viewPort.bottom) block.seenBeginning = true;
if (self.viewPort.top <= bottom && bottom <= self.viewPort.bottom) block.seenEnding = true;
if (block.seenBeginning && block.seenEnding) return true;
return false
},
pushVisibleBlocks: function(self) {
var toDelete = [];
for (i = 0; i < self.blocks.length; i++)
if (self.isBlockVisible(self, self.blocks[i])) {
self.pushBlock(self, self.blocks[i]);
toDelete.push(self.blocks[i])
};
self.removeBlocks(self, toDelete)
}
}
};
if (typeof BTagger === 'undefined') {
var BTagger = function() {};
BTagger.prototype = {
flags: {
retargetingDataRequestDone: false,
tagUserRequestDone: false,
getCookieRequestDone: false
},
behavioralEngine: null,
tags: null,
tagsToDelete: null,
retargetingData: null,
pixelsToDisplay: [],
onCreate: function(self, behavioralEngine) {
behavioralEngine.eventManager.addCallbackToEvent(behavioralEngine.eventManager, 'callbackTagUserRequest', function(data) {
self.tagUserRequestCallbackHandler(self, data)
});
behavioralEngine.eventManager.addCallbackToEvent(behavioralEngine.eventManager, 'callbackRetargetingDataRequest', function(data) {
self.retargetingDataRequestCallbackHandler(self, data)
});
behavioralEngine.eventManager.addCallbackToEvent(behavioralEngine.eventManager, 'callbackGetCookieRequest', function(data) {
self.getCookieRequestCallbackHandler(self, data)
});
self.behavioralEngine = behavioralEngine
},
onStart: function(self) {},
tagUserRequestCallbackHandler: function(self, data) {
self.setTagUserData(self, data);
self.flags.tagUserRequestDone = true;
self.startTagging(self, data)
},
retargetingDataRequestCallbackHandler: function(self, data) {
self.setRetargetingDataData(self, data);
self.flags.retargetingDataRequestDone = true;
self.startTagging(self)
},
getCookieRequestCallbackHandler: function(self) {
if (!self.behavioralEngine.flags.optOut) {
self.flags.getCookieRequestDone = true;
self.startTagging(self)
}
},
setTagUserData: function(self, data) {
self.tags = data.tags;
self.tagsToDelete = data.tagsToDelete;
self.businessclick = data.businessclick;
self.retargetingLinks = data.retargetingLinks;
self.cookieMatchingUrls = data.cookieMatchingUrls
},
setRetargetingDataData: function(self, data) {
self.retargetingData = data
},
getSimplyList: function(self, tags) {
var list = [];
for (var i = 0; i < tags.length; i++) list.push(tags[i].name);
return list
},
startTagging: function(self) {
if (!self.flags.tagUserRequestDone || !self.flags.retargetingDataRequestDone || !self.flags.getCookieRequestDone) return false;
self.runTargetingTagging(self);
self.runCustomTagger(self)
},
runTargetingTagging: function(self) {
for (var i = 0; i < self.retargetingData.targeting.length; i++) {
var campaign = self.retargetingData.targeting[i];
if (!self.checkPartner(self, campaign)) continue;
self.checkCampaign(self, campaign)
};
self.displayPixels(self)
},
runFlagsTagger: function(self) {},
runCustomTagger: function(self) {
for (var i = 0; i < self.retargetingData.custom.length; i++) {
if (!self.checkPartner(self, self.retargetingData.custom[i])) continue;
if (typeof self.retargetingData.custom[i].code === 'function') self.retargetingData.custom[i].code(self)
}
},
checkPartner: function(self, item) {
var partner = self.behavioralEngine.data.partner;
if (item.allow.indexOf('*') < 0)
if (item.allow.indexOf(partner) < 0) return false;
if (item.deny.indexOf(partner) > -1) return false;
return true
},
checkCampaign: function(self, campaign) {
for (var i = 0; i < campaign.targets.length; i++) self.checkCampaignTarget(self, campaign.targets[i])
},
checkCampaignTarget: function(self, target) {
if (self.isUserATarget(self, self.tags, target))
for (var i = 0; i < target.pixels.length; i++)
if (typeof target.pixels[i] === 'string' && (target.pixels[i].substr(0, 4) === 'http' || target.pixels[i].substr(0, 2) === '//')) self.pixelsToDisplay.push(target.pixels[i])
},
displayPixels: function(self) {
if (self.pixelsToDisplay.length > 7) {
for (var i = 0; i < 7; i++) {
var index = Math.round(Math.random() * 1e6) % self.pixelsToDisplay.length;
new Image().src = self.pixelsToDisplay[index];
self.pixelsToDisplay.splice(index, 1)
}
} else
for (var i = 0; i < self.pixelsToDisplay.length; i++) new Image().src = self.pixelsToDisplay[i]
},
isUserATarget: function(self, tags, target) {
var interestTopics = self.getSimplyList(self, tags.groups),
interestTags = self.getSimplyList(self, tags.tags),
intentionTopics = self.getSimplyList(self, tags.intentionTopics),
intentionTags = self.getSimplyList(self, tags.intentionTags),
demographics = tags.demographics,
flags = tags.flags;
return self.isElementFromArrayContainInArray(self, interestTopics, target.interestGroups) && self.isElementFromArrayContainInArray(self, interestTags, target.interestWords) && self.isElementFromArrayContainInArray(self, intentionTopics, target.intentionGroups) && self.isElementFromArrayContainInArray(self, intentionTags, target.intentionWords) && self.checkDemographics(self, demographics, target.demographics) && self.checkFlags(self, flags, target.flags)
},
isElementFromArrayContainInArray: function(self, user, target) {
if (target.length == 0) return true;
for (var i in user)
if (target.indexOf(user[i]) >= 0) return true;
return false
},
checkDemographics: function(self, user, target) {
return self.checkSex(self, user, target) && self.checkAge(self, user, target)
},
checkFlags: function(self, user, target) {
if (target.length == 0) return true;
if (typeof user == 'undefined' && user.length < 1) return false;
for (var i = 0; i < target.length; i++)
for (var j = 0; j < user.length; j++)
if (target[i] == user[j].flag) return true;
return false
},
checkSex: function(self, user, target) {
if (target.sex == '') return true;
if (typeof user.s == 'undefined') return false;
if (target.sex == user.s) return true;
return false
},
checkAge: function(self, user, target) {
if (target.ageFrom == '' && target.ageTo == '') return true;
if (typeof user.y === 'undefined') return false;
var age = new Date().getFullYear() - user.y;
if (age < target.ageFrom || age > target.ageTo) return false;
return true
}
}
};
if (typeof BWord === 'undefined') {
var BWord = function(w, s) {
this.w = w;
this.s = s
};
BWord.prototype = {
w: '',
s: null
}
};
if (typeof BehavioralEngine === 'undefined') {
var BehavioralEngine = {
eventManager: null,
semantic: null,
analitic: null,
tagger: null,
scriptDataByPartner: {},
partners: [],
sendingProbeLimitation: {
minWords: 20,
minTimeInterval: 15
},
lastProbeSentAt: 0,
probeSendInterval: 15e3,
flags: {
cookieReceived: false,
tagsReceived: false,
optOut: false,
goodQualityPage: true,
scriptDataByPartnerReady: false,
demographyData: false,
miscSet: false
},
data: {
cookie: null,
domainQuality: null,
firstProbeSend: false,
partner: null,
misc: {}
},
probe: {},
startTime: new Date().getTime(),
bcookie: {
emergencyRequestTimeout: null,
iframe: null,
received: false,
callback: false
},
onCreate: function(self) {
var eventManager = new BEventManager();
self.eventManager = eventManager;
BDebug.init();
eventManager.registerEvent(eventManager, new BEvent('beforeBCookieRequest'));
eventManager.registerEvent(eventManager, new BEvent('afterBCookieRequest', [function() {
BProfiler.startTest('BCookie');
return true
}]));
eventManager.registerEvent(eventManager, new BEvent('callbackBCookieRequest', [function() {
BProfiler.endTest('BCookie');
self.sendGetCookieRequest(self)
}]));
eventManager.registerEvent(eventManager, new BEvent('beforeGetCookieRequest'));
eventManager.registerEvent(eventManager, new BEvent('afterGetCookieRequest', [function() {
BProfiler.startTest('getCookie');
return true
}]));
eventManager.registerEvent(eventManager, new BEvent('callbackGetCookieRequest', [function() {
BProfiler.endTest('getCookie');
self.sendTagUserRequest(self)
}]));
eventManager.registerEvent(eventManager, new BEvent('beforeTagUserRequest'));
eventManager.registerEvent(eventManager, new BEvent('afterTagUserRequest', [function() {
BProfiler.startTest('tagUser')
}]));
eventManager.registerEvent(eventManager, new BEvent('callbackTagUserRequest', [function() {
BProfiler.endTest('tagUser')
}]));
eventManager.registerEvent(eventManager, new BEvent('beforeInsertProbeRequest', [function() {
return self.assembleProbe(self)
}]));
eventManager.registerEvent(eventManager, new BEvent('afterInsertProbeRequest', [function() {
BProfiler.startTest('insertProbe');
return true
}]));
eventManager.registerEvent(eventManager, new BEvent('callbackInsertProbeRequest', [function() {
BProfiler.endTest('insertProbe')
}]));
eventManager.registerEvent(eventManager, new BEvent('beforeRetargetingDataRequest'));
eventManager.registerEvent(eventManager, new BEvent('afterRetargetingDataRequest', [function() {
BProfiler.startTest('retargetingData');
return true
}]));
eventManager.registerEvent(eventManager, new BEvent('callbackRetargetingDataRequest', [function() {
BProfiler.endTest('retargetingData');
return true
}]));
eventManager.registerEvent(eventManager, new BEvent('insertProbe', [function() {
self.sendinsertProbeRequest(self)
}]));
self.semantic = new BSemantic();
self.semantic.onCreate(self.semantic, self);
self.analitic = new BAnalitic();
self.analitic.onCreate(self.analitic, self);
self.tagger = new BTagger();
self.tagger.onCreate(self.tagger, self);
self.runIfReady(self, function() {
self.onStart(self)
})
},
onStart: function(self) {
BUtilities.newThread(function() {
BProfiler.sendItems()
});
BUtilities.newThread(function() {
self.sendBCookieRequest(self)
});
BUtilities.newThread(function() {
self.sendRetargetingDataRequest(self)
});
BUtilities.newThread(function() {
self.semantic.onStart(self.semantic)
});
BUtilities.newThread(function() {
self.analitic.onStart(self.analitic)
});
BUtilities.newThread(function() {
self.tagger.onStart(self.tagger)
});
BUtilities.newThread(function() {
self.setProbeSendInterval(self)
})
},
setProbeSendInterval: function(self) {
var interval = setInterval(function() {
if ((new Date()).getTime() - self.lastProbeSentAt > self.probeSendInterval) self.eventManager.callEvent(self.eventManager, 'insertProbe');
if ((new Date()).getTime() - self.startTime > 18e4) clearInterval(interval);
if ((new Date()).getTime() - self.startTime > 6e4) self.startTime = 6e4
}, 1e3)
},
runIfReady: function(self, callback) {
if (document.readyState === 'complete') {
callback()
} else window.addEventListener('load', callback, false)
},
sendBCookieRequest: function(self) {
if (!self.eventManager.callEvent(self.eventManager, 'beforeBCookieRequest')) return;
self.bcookie.emergencyRequestTimeout = window.setTimeout(function() {
if (!self.bcookie.callback) self.eventManager.callEvent(self.eventManager, 'callbackBCookieRequest')
}, 2500);
window.addEventListener("message", self.sendBCookieRequestCallback, false);
self.bcookie.iframe = document.createElement('iframe');
self.bcookie.iframe.style.height = '1px';
self.bcookie.iframe.style.width = '1px';
self.bcookie.iframe.style.border = 0;
self.bcookie.iframe.style.opacity = 0;
self.bcookie.iframe.style.display = "none";
self.bcookie.iframe.src = '//cdn.behavioralengine.com/scripts/bcookie/bcookie.html';
document.getElementsByTagName('body')[0].appendChild(self.bcookie.iframe);
self.eventManager.callEvent(self.eventManager, 'afterBCookieRequest')
},
sendBCookieRequestCallback: function(event) {
var self = BehavioralEngine;
BDebug.log('BCookie callback: ');
BDebug.log(event.data);
if (self.bcookie.callback) return;
if (!event.data || typeof event.data.bcookie === 'undefined' && !event.data.bcookie) return;
self.bcookie.callback = true;
window.clearTimeout(self.bcookie.emergencyRequestTimeout);
BDebug.log('cookie from bcookie script: ' + event.data.cookie);
self.bcookie.received = true;
self.data.cookie = event.data.cookie;
self.eventManager.callEvent(self.eventManager, 'callbackBCookieRequest')
},
sendGetCookieRequest: function(self) {
if (!self.eventManager.callEvent(self.eventManager, 'beforeGetCookieRequest')) return;
self.preparePartnersDataFromScripts(self);
var params = {
cookie: self.data.cookie,
p: self.getPartnersFromScripts(self).join(','),
domain: encodeURI(('https:' == document.location.protocol ? 'https://' : 'http://') + window.location.host)
};
BDebug.log('cookie sent: ' + self.data.cookie);
BUtilities.sendRequest('getCookie', params, function(data) {
BDebug.log('cookie received: ' + data.cookie);
self.data.cookie = data.cookie;
self.bcookie.iframe.contentWindow.postMessage(data.cookie, '*');
self.data.domainQuality = data.domainQuality;
if (typeof data.partner !== 'undefined') self.data.partner = data.partner.name;
self.data.probeHash = self.getProbeHash(self, data.cookie);
self.flags.optOut = false;
self.flags.goodQualityPage = self.isPageGoodQuality(self);
self.flags.cookieReceived = true;
self.flags.scriptDataByPartnerReady = true;
self.eventManager.callEvent(self.eventManager, 'callbackGetCookieRequest', data)
});
self.eventManager.callEvent(self.eventManager, 'afterGetCookieRequest')
},
sendTagUserRequest: function(self) {
if (!self.eventManager.callEvent(self.eventManager, 'beforeTagUserRequest')) return;
BUtilities.sendApiRequest('tagUser', {}, function(data) {
self.flags.tagsReceived = true;
self.eventManager.callEvent(self.eventManager, 'callbackTagUserRequest', data)
});
self.eventManager.callEvent(self.eventManager, 'afterTagUserRequest')
},
sendinsertProbeRequest: function(self) {
if (!self.eventManager.callEvent(self.eventManager, 'beforeInsertProbeRequest')) return;
var params = {
v: '3.0'
};
if (self.data.firstProbeSend) params.update = 1;
BUtilities.sendPostRequest('insertProbe', params, self.probe, function(data) {
self.data.firstProbeSend = true;
self.eventManager.callEvent(self.eventManager, 'callbackInsertProbeRequest', data)
});
self.lastProbeSentAt = new Date().getTime();
self.eventManager.callEvent(self.eventManager, 'afterInsertProbeRequest')
},
sendRetargetingDataRequest: function(self) {
if (!self.eventManager.callEvent(self.eventManager, 'beforeRetargetingDataRequest')) return;
BUtilities.sendScriptRequest('retargeting', 'scripts/retargeting.js', function(data) {
self.eventManager.callEvent(self.eventManager, 'callbackRetargetingDataRequest', data)
});
self.eventManager.callEvent(self.eventManager, 'afterRetargetingDataRequest')
},
isPageGoodQuality: function(self) {
if (self.data.domainQuality == 0) return false;
return true
},
preparePartnersDataFromScripts: function(self) {
var allScriptBlocks = document.getElementsByTagName('script'),
src;
for (var i = 0; i < allScriptBlocks.length; i++) {
src = allScriptBlocks[i].getAttribute('src');
if (src !== null)
if (/\/\/[a-z.]*api\.behavioralengine\.com\/scripts.*\/be[-a-z0-9]*\.js$/.test(src)) self.parseScriptBlock(self, allScriptBlocks[i])
}
},
parseScriptBlock: function(self, scriptBlock) {
var partner = 'ct',
data = {};
for (var i = 0; i < scriptBlock.attributes.length; i++)
if (scriptBlock.attributes[i].name.indexOf('data-') > -1)
if (scriptBlock.attributes[i].value !== '')
if (scriptBlock.attributes[i].name === 'data-p') {
partner = scriptBlock.attributes[i].value
} else {
data[scriptBlock.attributes[i].name] = scriptBlock.attributes[i].value;
self.flags.demographyData = true
};
self.scriptDataByPartner[partner] = data;
self.partners.push(partner)
},
getPartnersFromScripts: function(self) {
return self.partners
},
getProbeHash: function(self, cookie) {
return BUtilities.generateHash(cookie + '_' + (new Date().getTime()))
},
canSendProbe: function(self) {
if (self.flags.optOut) return false;
if (!self.flags.goodQualityPage && !self.flags.demographyData) return false;
if (!self.flags.cookieReceived) return false;
if (!self.analitic.isBrowserDataSet(self.analitic)) return false;
if (!self.semantic.ready) return false;
var timeDiff = (new Date().getTime() - self.lastProbeSentAt) / 1e3;
if (timeDiff < self.sendingProbeLimitation.minTimeInterval) return false;
if (self.semantic.getWordsCount(self.semantic) < self.sendingProbeLimitation.minWords) return false;
return true
},
assembleProbe: function(self) {
if (!self.canSendProbe(self)) return false;
var words = self.semantic.popWords(self.semantic),
wordsCount = self.semantic.getSeenWordsCount(self.semantic);
self.probe = {
'data-probe': JSON.stringify({
analitic: self.analitic.getBrowserData(self.analitic),
semantic: {
words: words,
readTime: Math.floor((new Date().getTime() - self.startTime) / 1e3),
seenAccepted: wordsCount
}
}),
'data-cookie': self.data.cookie,
'data-probeHash': self.data.probeHash
};
if (self.data.partner !== null) self.probe['data-p'] = self.data.partner;
if (self.analitic.isFBDataReady(self.analitic)) {
var FBData = self.analitic.getFBData(self.analitic);
for (var i in FBData) self.probe[i] = FBData[i]
};
if (self.flags.miscSet) {
self.probe['data-misc'] = JSON.stringify(self.data.misc);
self.flags.miscSet = false;
self.data.misc = {}
};
if (self.flags.scriptDataByPartnerReady && self.data.partner !== null)
if (typeof self.scriptDataByPartner[self.data.partner] !== 'undefined') {
var data = self.scriptDataByPartner[self.data.partner];
for (var i in data) self.probe[i] = data[i]
};
return true
}
};
try {
BehavioralEngine.onCreate(BehavioralEngine)
} catch (exc) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment