Skip to content

Instantly share code, notes, and snippets.

@koesbong
Created May 5, 2011 02:48
Show Gist options
  • Select an option

  • Save koesbong/956454 to your computer and use it in GitHub Desktop.

Select an option

Save koesbong/956454 to your computer and use it in GitHub Desktop.
var ktCode = (function() {
function Kontagent(config) {
this.api = null;
this.img = document.createElement('img');
this.url_path = encodeURIComponent(window.location.pathname);
this.st1 = this.getQueryStrings()['st1'] || '';
this.st2 = this.getQueryStrings()['st2'] || '';
this.st3 = this.getQueryStrings()['st3'] || '';
this.kt_cust_id = this.getQueryStrings()['kt_cust_id'] || 'unknown';
this.fb_ref = this.getQueryStrings()['fb_ref'] || '';
this.sms_ss = this.getQueryStrings()['sms_ss'] || '';
this.fb_comment_id = this.getQueryStrings()['fb_comment_id'] || '';
this.kt_tag_val = this.getQueryStrings()['kt_tag'] || '';
this.kt_uuid = this.getCookie('kont-uuid') || '';
this.fblike_tag = this.randomStr('alphs', 32);
this.kt_type = this.getQueryStrings()['kt_type'] || 'ad';
this.twitid = this.getQueryStrings()['kt_u'] || '';
this.sys_useragent = navigator.userAgent.replace(/[, ]+/g, "");
this.installed_plugins = navigator.plugins;
this.sys_language = navigator.language;
this.sys_platform = navigator.platform;
this.screen_resolution = screen.width + 'x' + screen.height;
this.plugin_version = '';
this.all_plugins = '';
this.trunc_int = '';
this.all_data = {};
this.kt_hash_id = '';
if (/MSIE (\d+\.\d+);/.test(this.sys_useragent)){
installed_plugins = '';
sys_language = navigator.systemLanguage;
}
if(this.installed_plugins !== '') {
for(var x=0, y = this.installed_plugins.length; x < y; x++) {
this.plugin_version = this.installed_plugins[x].version || '';
this.all_plugins += this.installed_plugins[x].name + this.plugin_version;
}
this.all_plugins = this.all_plugins.replace(/[, ]+/g, "");
}
this.all_data.init = this.all_plugins + this.sys_useragent + this.sys_platform +
this.sys_language + this.screen_resolution;
if(navigator.mimeTypes['application/x-shockwave-flash']) {
this.fontScript = document.createElement('object');
// inject swf needed to retrieve installed fonts
this.fontScript.setAttribute('height', '1');
this.fontScript.setAttribute('width', '1');
this.fontScript.setAttribute('data', 'http://localhost:8989/media/integration/FontList.swf');
this.fontScript.setAttribute('name', 'fontListSWF');
this.fontScript.setAttribute('id', 'fontListSWF');
this.fontScript.setAttribute('type', 'application/x-shockwave-flash');
this.fontScript.innerHTML = '<param value="http://localhost:8989/media/integration/FontList.swf" name="movie"><embed width="1" height="1" src="http://localhost:8989/media/integration/FontList.swf">';
document.body.appendChild(this.fontScript);
} else {
this.kt_hash_id = this.sha1hash(this.all_data.init);
this.kt_hash_id = this.kt_hash_id.substring(0, 16);
this.kt_hash_id = parseInt(this.kt_hash_id, 16);
}
if(this.fb_comment_id) {
this.fb_comment_id = this.fb_comment_id.match(/[\#a-zA-Z0-9]+$/).join('').match(/[0-9]+/).join('');
}
this.kt_tag = this.fb_ref || this.sms_ss || this.fb_comment_id || escape(this.kt_tag_val) || '';
this.config = {
apiKey: null,
baseApiUrl: 'http://api.ecommerce.kontagent.net/api/v0/'
};
for (var key in config) {
if (config.hasOwnProperty(key)) {
this.config[key] = config[key];
}
}
if(!this.kt_uuid) {
this.kt_uuid = this.randomStr('nums', 16);
this.setCookie('kont-uuid', this.kt_uuid, 7);
}
if (this.kt_tag) {
this.uccTagNoParams();
} else if (!this.kt_tag && this.st1 && this.st2 && this.st3) {
this.st1 = escape(this.st1);
this.st2 = escape(this.st2);
this.st3 = escape(this.st3);
this.uccParamsNoTag();
} else {
this.uccNoTagNoParams();
}
}
Kontagent.prototype.populateFontList = function(fontArr) {
alert(fontArr);
var allFontsCounter = 0,
allFonts = '',
fontList = '',
hash = '',
truncint = '';
for (var key in fontArr) {
var fontName = fontArr[key];
// trim
fontName = fontName.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
fontList += fontName;
allFontsCounter++;
}
allFonts = fontList.replace(/[, ]+/g, "");
this.kt_hash_id = this.sha1hash(this.all_data.init + allFonts);
this.kt_hash_id = this.kt_hash_id.substring(0, 16);
this.kt_hash_id = parseInt(this.kt_hash_id, 16);
console.log(this.kt_hash_id);
},
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* SHA-1 implementation in JavaScript | (c) Chris Veness 2002-2010 | www.movable-type.co.uk */
/* - see http://csrc.nist.gov/groups/ST/toolkit/secure_hashing.html */
/* http://csrc.nist.gov/groups/ST/toolkit/examples.html */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/**
* Generates SHA-1 hash of string
*
* @param {String} msg String to be hashed
* @param {Boolean} [utf8encode=true] Encode msg as UTF-8 before generating hash
* @returns {String} Hash of msg as hex character string
*/
Kontagent.prototype.sha1hash = function(msg, utf8encode) {
utf8encode = (typeof utf8encode == 'undefined') ? true : utf8encode;
// convert string to UTF-8, as SHA only deals with byte-streams
if (utf8encode) msg = this.utf8encode(msg);
// constants [§4.2.1]
var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
// PREPROCESSING
msg += String.fromCharCode(0x80); // add trailing '1' bit (+ 0's padding) to string [§5.1.1]
// convert string msg into 512-bit/16-integer blocks arrays of ints [§5.2.1]
var l = msg.length/4 + 2; // length (in 32-bit integers) of msg + ‘1’ + appended length
var N = Math.ceil(l/16); // number of 16-integer-blocks required to hold 'l' ints
var M = new Array(N);
for (var i=0; i<N; i++) {
M[i] = new Array(16);
for (var j=0; j<16; j++) { // encode 4 chars per integer, big-endian encoding
M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) |
(msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3));
} // note running off the end of msg is ok 'cos bitwise ops on NaN return 0
}
// add length (in bits) into final pair of 32-bit integers (big-endian) [§5.1.1]
// note: most significant word would be (len-1)*8 >>> 32, but since JS converts
// bitwise-op args to 32 bits, we need to simulate this by arithmetic operators
M[N-1][14] = ((msg.length-1)*8) / Math.pow(2, 32); M[N-1][14] = Math.floor(M[N-1][14]);
M[N-1][15] = ((msg.length-1)*8) & 0xffffffff;
// set initial hash value [§5.3.1]
var H0 = 0x67452301;
var H1 = 0xefcdab89;
var H2 = 0x98badcfe;
var H3 = 0x10325476;
var H4 = 0xc3d2e1f0;
// HASH COMPUTATION [§6.1.2]
var W = new Array(80); var a, b, c, d, e;
for (var i=0; i<N; i++) {
// 1 - prepare message schedule 'W'
for (var t=0; t<16; t++) W[t] = M[i][t];
for (var t=16; t<80; t++) W[t] = this.sha1ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);
// 2 - initialise five working variables a, b, c, d, e with previous hash value
a = H0; b = H1; c = H2; d = H3; e = H4;
// 3 - main loop
for (var t=0; t<80; t++) {
var s = Math.floor(t/20); // seq for blocks of 'f' functions and 'K' constants
var T = (this.sha1ROTL(a,5) + this.sha1f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff;
e = d;
d = c;
c = this.sha1ROTL(b, 30);
b = a;
a = T;
}
// 4 - compute the new intermediate hash value
H0 = (H0+a) & 0xffffffff; // note 'addition modulo 2^32'
H1 = (H1+b) & 0xffffffff;
H2 = (H2+c) & 0xffffffff;
H3 = (H3+d) & 0xffffffff;
H4 = (H4+e) & 0xffffffff;
}
return this.sha1toHexStr(H0) + this.sha1toHexStr(H1) +
this.sha1toHexStr(H2) + this.sha1toHexStr(H3) + this.sha1toHexStr(H4);
},
//
// function 'f' [§4.1.1]
//
Kontagent.prototype.sha1f = function(s, x, y,z) {
switch (s) {
case 0: return (x & y) ^ (~x & z); // Ch()
case 1: return x ^ y ^ z; // Parity()
case 2: return (x & y) ^ (x & z) ^ (y & z); // Maj()
case 3: return x ^ y ^ z; // Parity()
}
},
//
// rotate left (circular left shift) value x by n positions [§3.2.5]
//
Kontagent.prototype.sha1ROTL = function(x, n) {
return (x<<n) | (x>>>(32-n));
},
// hexadecimal representation of a number
// (note toString(16) is implementation-dependant, and
// in IE returns signed numbers when used on full words)
//
Kontagent.prototype.sha1toHexStr = function(n) {
var s="", v;
for (var i=7; i>=0; i--) { v = (n>>>(i*4)) & 0xf; s += v.toString(16); }
return s;
},
/**
* Encode multi-byte Unicode string into utf-8 multiple single-byte characters
* (BMP / basic multilingual plane only)
*
* Chars in range U+0080 - U+07FF are encoded in 2 chars, U+0800 - U+FFFF in 3 chars
*
* @param {String} strUni Unicode string to be encoded as UTF-8
* @returns {String} encoded string
*/
Kontagent.prototype.utf8encode = function(strUni) {
// use regular expressions & String.replace callback function for better efficiency
// than procedural approaches
var strUtf = strUni.replace(
/[\u0080-\u07ff]/g, // U+0080 - U+07FF => 2 bytes 110yyyyy, 10zzzzzz
function(c) {
var cc = c.charCodeAt(0);
return String.fromCharCode(0xc0 | cc>>6, 0x80 | cc&0x3f);
}
);
strUtf = strUtf.replace(
/[\u0800-\uffff]/g, // U+0800 - U+FFFF => 3 bytes 1110xxxx, 10yyyyyy, 10zzzzzz
function(c) {
var cc = c.charCodeAt(0);
return String.fromCharCode(0xe0 | cc>>12, 0x80 | cc>>6&0x3F, 0x80 | cc&0x3f);
}
);
return strUtf;
},
/**
* Decode utf-8 encoded string back into multi-byte Unicode characters
*
* @param {String} strUtf UTF-8 string to be decoded back to Unicode
* @returns {String} decoded string
*/
Kontagent.prototype.utf8decode = function(strUtf) {
// note: decode 3-byte chars first as decoded 2-byte strings could appear to be 3-byte char!
var strUni = strUtf.replace(
/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, // 3-byte chars
function(c) { // (note parentheses for precence)
var cc = ((c.charCodeAt(0)&0x0f)<<12) | ((c.charCodeAt(1)&0x3f)<<6) | ( c.charCodeAt(2)&0x3f);
return String.fromCharCode(cc);
}
);
strUni = strUni.replace(
/[\u00c0-\u00df][\u0080-\u00bf]/g, // 2-byte chars
function(c) { // (note parentheses for precence)
var cc = (c.charCodeAt(0)&0x1f)<<6 | c.charCodeAt(1)&0x3f;
return String.fromCharCode(cc);
}
);
return strUni;
},
/*
* Generate a random string.
*
* USAGE: this.randomStr(type, length, radix)
* type - Alphabets (alphs), Numerics (nums), or Alphanumerics (alphsnums)
* length - the desired number of characters
* radix - the number of allowable values for each character.
*
* EXAMPLES:
* // No arguments - returns RFC4122, version 4 ID
* >>> this.randomStr()
* "92329D396F5C4523ABFCAAB64544E172"
*
* // One argument - returns ID of the specified length
* >>> this.randomStr('alphs', 15) // 15 character ID (default base=62)
* "VcydxgltxrVZSTV"
*
* // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
* >>> this.randomStr('nums', 8, 2) // 8 character ID (base=2)
* "01001010"
* >>> this.randomStr('nums', 8, 10) // 8 character ID (base=10)
* "47473046"
* >>> this.randomStr('alphsnums', 8, 16) // 8 character ID (base=16)
* "098F4D35"
*
*/
Kontagent.prototype.randomStr = function(type, len, radix) {
// Private array of chars to use
var NUMS = '123456789'.split(''),
ALPHS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
ALPHSNUMS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789'.split('');
var chars, uuid = [], rnd = Math.random;
if (type == 'nums') {
chars = NUMS;
} else if (type == 'alphs') {
chars = ALPHS;
} else {
chars = ALPHSNUMS;
}
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | rnd()*radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | rnd()*16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
}
}
}
var ret = uuid.join('');
return ret.substring(0, 32);
};
/*
* Set a cookie
*
* Parameters:
* name - name of cookie
* value - value of cookie
* days - days until cookie expires
*
* Example:
* // Set a cookie called cookieName with the value of cookieValue that expires after 10 days
* >>> this.setCookie("cookieName", "cookieValue", 10);
*
*/
Kontagent.prototype.setCookie = function(name,value,days) {
var expires,
date;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
};
/*
* Get cookie value
*
* Parameters:
* name - name of cookie
*
* Example:
* // Get the value of a cookie called cookieName
* >>> this.getCookie("cookieName");
* "cookieValue"
*
*/
Kontagent.prototype.getCookie = function(name) {
var nameEQ = name + "=",
i;
var ca = document.cookie.split(';');
for(i = 0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
};
/*
* Delete cookie
*
* Parameters:
* name - name of cookie
*
* Example:
* // Delete a cookie called cookieName
* >>> this.deleteCookie("cookieName");
*
*/
Kontagent.prototype.deleteCookie = function (name) {
this.setCookie(name,"",-1);
};
/*
* Get value of URL parameters
*
* Example:
* // Get the value of st1, st2, and st3 from http://someurl.com/?st1=a&st2=b&st3=c
* var st1 = this.getQueryStrings()['st1'], // 'a'
* st2 = this.getQueryStrings()['st2'], // 'b'
* st3 = this.getQueryStrings()['st3']; // 'c'
*
*/
Kontagent.prototype.getQueryStrings = function () {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
value = value.replace('#', '');
vars[key] = value;
});
return vars;
};
/*
* Fire 'psr' call when tag value exists in the URL parameters
* when a user visits the site initially.
*
* An example scenario where this function gets called is when
* a user visits the product site by clicking on a link from
* his/her friend's Facebook Wall post.
*
*/
Kontagent.prototype.uccTagNoParams = function() {
var widget_type = '';
if(this.fb_ref || this.sms_ss || this.fb_comment_id) {
this.kt_type = 'social';
}
if(this.fb_ref) {
widget_type = 'fblike';
} else if(this.sms_ss) {
widget_type = 'addthis_share';
} else if(this.fb_comment_id) {
widget_type = 'fbcomments';
}
this.api = this.config.baseApiUrl + this.config.apiKey + '/psr/' +
'?s=' + this.kt_uuid + '&u=' + this.kt_tag + '&p=' + this.url_path +
'&w=' + widget_type + '&tu=' + this.kt_type + '&cid=' + escape(this.kt_cust_id);
if(this.twitid) {
this.api += '&twid=' + this.twitid;
}
this.apiCall(this.api);
this.userCount();
};
/*
* Fire 'ucc' call when there is no tag value and
* there are source (st1), category (st2), and
* content (st3) values in the URL parameters
* when a user visits the site initially.
*
* An example scenario where this function gets called is when
* a user gets to the product site by clicking on an online ad.
*
*/
Kontagent.prototype.uccParamsNoTag = function() {
this.api = this.config.baseApiUrl + this.config.apiKey + '/ucc/' +
'?s=' + this.kt_uuid + '&tu=' + this.kt_type + '&st1=' + this.st1 +
'&st2=' + this.st2 + '&st3=' + this.st3 + '&cid=' + escape(this.kt_cust_id);
this.apiCall(this.api);
this.userCount();
};
/*
* Fire 'ucc' call when there is no known parameters
* in the URL parameters when a user visits the site initially.
*
* An example scenario where this function gets called is when
* a user visits the product site organically.
*
*/
Kontagent.prototype.uccNoTagNoParams = function() {
this.api = this.config.baseApiUrl + this.config.apiKey + '/ucc/' +
'?s=' + this.kt_uuid + '&tu=unknown' + '&cid=' + escape(this.kt_cust_id);
this.apiCall(this.api);
this.userCount();
};
/*
* Fire 'completedTransaction' call when a purchase has been made.
*
* An example scenario where this function gets called is when
* a user clicks on a button to finalize the purchase of a product.
*
* Parameters:
* price - the price of the product in cents
*
*/
Kontagent.prototype.completedTransaction = function(price, kt_cust_id) {
kt_cust_id = kt_cust_id || '';
this.api = this.config.baseApiUrl + this.config.apiKey + '/mtu/' +
'?s=' + this.kt_uuid + '&p='+ this.url_path + '&v=' + parseInt(price, 10) +
'&cid=' + encodeURIComponent(kt_cust_id);
this.apiCall(this.api);
};
/*
* Fire 'fbLikeClick' call when there is an interaction with
* Facebook widgets (Like, Facepile, etc).
*
* An example scenario where this function gets called is when
* a user clicks on the Like button on the product page. For more
* information on how to catch the Like click event, check out
* http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
*
*/
Kontagent.prototype.widgetClick = function(widget_type, opts) {
var friend_count = 0;
opts = opts || {};
defaults = {
tag: this.fblike_tag,
kt_cust_id: ''
};
for (var key in defaults) {
if (defaults.hasOwnProperty(key) && opts[key] === undefined) {
opts[key] = defaults[key];
}
}
tag = tag || this.fblike_tag;
this.api = this.config.baseApiUrl + this.config.apiKey + '/pst/' +
'?s=' + this.kt_uuid + '&u=' + encodeURIComponent(opts['tag']) +
'&p=' + this.url_path + '&w=' + widget_type + '&n=' + friend_count +
'&kt_cust_id=' + encodeURIComponent(opts['kt_cust_id']);
this.apiCall(this.api);
};
/*
* Method to capture page views
*
*/
Kontagent.prototype.userCount = function() {
this.api = this.config.baseApiUrl + this.config.apiKey + '/pgr/' +
'?s=' + this.kt_uuid + '&g=' + this.url_path + '&cid=' + escape(this.kt_cust_id);
this.apiCall(this.api);
};
/*
* Call fbLikeButton to create the Like button on the page
*
* Required parameters:
* el - id of the element the like button will live in
* likeUrl - URL of the link that shows up on the FB Wall feed
*
* Optional parameters that gets passed in as an object:
* layout - standard (default), button_count, box_count
* show_faces - true (default), false
* width - 450 (default)
* action - like (default), recommend
* font - arial (default), lucinda grande, segoe ui, tahoma, trebuchet ms, verdana
* colorscheme - light (default), dark
*
* Example:
* var kt = ktCode('apikey');
* kt.fbLikeButton('fblike-wrapper', 'http://mysite.com/');
*
* kt.fbLikeButton('fblike-wrapper', 'http://mysite.com/', {layout: 'box_count', width: '600'});
*
*/
Kontagent.prototype.fbLikeButton = function(el, likeUrl, opts) {
var appendEl = document.getElementById(el),
likeScript = document.createElement('fb:like'),
defaults,
like_url = this.shareUrlHelper(likeUrl) || this.shareUrlHelper(window.location.href);
opts = opts || {};
defaults = {
layout: 'standard',
show_faces: 'true',
width: '450',
action: 'like',
font: 'arial',
colorscheme: 'light',
kt_cust_id: ''
};
for (var key in defaults) {
if (defaults.hasOwnProperty(key) && opts[key] === undefined) {
opts[key] = defaults[key];
}
}
like_url += 'kt_cust_id=' + encodeURIComponent(opts['kt_cust_id']);
likeScript.setAttribute('href', like_url);
likeScript.setAttribute('show_faces', opts['show_faces']);
likeScript.setAttribute('layout', opts['layout']);
likeScript.setAttribute('width', opts['width']);
likeScript.setAttribute('action', opts['action']);
likeScript.setAttribute('font', opts['font']);
likeScript.setAttribute('colorscheme', opts['colorscheme']);
likeScript.setAttribute('ref', this.fblike_tag);
appendEl.appendChild(likeScript);
};
Kontagent.prototype.shareUrlHelper = function(link){
var href=((link)?link:document.location.href),
kt_tag=this.randomStr('alphs',32),
url;
url = ((href.search(/\?/)===-1) ? href + '?' : href + '&amp;');
return url;
};
/*
* Method to create a Twitter share button
*
* Required parameters:
* el - id of the element the like button will live in
* shareURL - URL to share
*
*
* Example:
* var kt = ktCode('apikey');
* kt.twitterShareButton('twitter-wrapper', 'http://mysite.com/');
*
* kt.twitterShareButton('twitter-wrapper', 'http://mysite.com/', {text: 'custom tweet text'});
*/
Kontagent.prototype.twitterShareButton = function(el, shareUrl, opts) {
var appendEl = document.getElementById(el),
twitterScript = document.createElement('a'),
share_url,
defaults,
text_length_allowed = 110,
text_length;
opts = opts || {};
defaults = {
text: '',
kt_cust_id: ''
};
for (var key in defaults) {
if (defaults.hasOwnProperty(key) && opts[key] === undefined) {
opts[key] = defaults[key];
}
}
text_length = opts['text'].length;
if(text_length > text_length_allowed) {
custom_text = opts['text'].substring(0, text_length_allowed) + '...';
} else {
custom_text = opts['text'];
}
share_url = this.shareUrlHelper(shareUrl) + 'kt_tag=' + this.fblike_tag + '&kt_type=twitter' +
'&kt_u=' + this.kt_uuid + '&kt_cust_id=' + this.opts['kt_cust_id'];
twitterScript.setAttribute('href', 'http://twitter.com/share?text=' + escape(custom_text) +
'&url=' + encodeURIComponent(share_url) + '&counturl=' + encodeURIComponent(share_url));
twitterScript.setAttribute('class', 'twitter-share-button');
twitterScript.innerHTML = 'tweet';
appendEl.appendChild(twitterScript);
var tweetButton = new twttr.TweetButton(twitterScript);
tweetButton.render();
};
/*
* Call fbComments to create the Comments form on the page
*
* Required parameters:
* el - id of the element the like button will live in
* shareUrl - URL of the link that shows up on the FB Wall feed
*
* Optional parameters that gets passed in as an object:
* xid - The unique identifier for this set of comments
* numposts - The maximum number of posts to display. You can set numposts to 0 to not display any comments. Default value is 10
* width - The width of the Comments Box in pixels. Default value is 550px
* publish_feed - Indicates whether the Post comment to my Facebook profile check box is checked.
* simple - When true, a rounded box does not appear around each post on your site.
*
* Example:
* var kt = ktCode('apikey');
* kt.fbComments('comments-wrapper', 'http://www.yoursite.com/',
* {xid: 'randomstring', numposts: '10', width: '550', publish_feed: 'true'}
* );
*
*/
Kontagent.prototype.fbComments = function(el, shareUrl, opts) {
var appendEl = document.getElementById(el),
commentScript = document.createElement('fb:comments'),
defaults,
share_url = this.shareUrlHelper(shareUrl) || this.shareUrlHelper(window.location.href);
opts = opts || {};
defaults = {
xid: 'random_kt_strings',
numposts: '10',
width: '550',
publish_feed: 'true',
simple: 'false',
kt_cust_id: ''
};
share_url += 'st1=closets&st2=fbcomments&st3=mainpage&kt_type=fbcomments&kt_cust_id=' +
encodeURIComponent(opts['kt_cust_id']);
for (var key in defaults) {
if (defaults.hasOwnProperty(key) && opts[key] === undefined) {
opts[key] = defaults[key];
}
}
commentScript.setAttribute('href', share_url);
commentScript.setAttribute('xid', opts['xid']);
commentScript.setAttribute('numposts', opts['numposts']);
commentScript.setAttribute('width', opts['width']);
commentScript.setAttribute('publish_feed', opts['publish_feed']);
appendEl.appendChild(commentScript);
};
/*
* The actual function that makes the API call.
*
* A 0x0 pixel image is created with the 'src' attribute
* pointing to the API URL and appended to the bottom of
* the page before the closing body tag.
*
*/
Kontagent.prototype.apiCall = function(api_url) {
this.img.setAttribute('height', 0);
this.img.setAttribute('width', 0);
this.img.setAttribute('class', 'api-call');
this.img.setAttribute('src', api_url);
document.body.appendChild(this.img);
};
return function(apiKey, config) {
config = config || {};
config.apiKey = apiKey;
return new Kontagent(config);
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment