asked on
//
// currently wordpress/drupal (un-platformed) works only without OB_userTemplateFile variable. why? bug...
// test variables
//var OB_outbrainKey = "testKey";
//var OB_user_template = ["bottom;general;false;stars firstLine"];
//------------------------------------------------------------------------------------------------------------------------
// one global only
// OB_user_matrix_infos = '{"matrixInfos":{"general":{"matrixSource":"http://widgets.outbrain.com/matrix_14.png","matrixYpositionThanks":"56","matrixYHeight":"28","matrixXlength":"86","matrixAllXlength":"860","matrixAllYlength":"100","starWidth":"17","starHeight":"28","shadowYoffset":"5"}}}';
var OB_voterWidgetObjArray = typeof(OB_voterWidgetObjArray)!='undefined' ? OB_voterWidgetObjArray : new Array();
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain browsers list object - start
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
//var outbrain_browsers_object = (typeof(outbrain_browsers_object) == 'object')? outbrain_browsers_object: function(){
var outbrain_browsers = (typeof(outbrain_browsers) == 'object')? outbrain_browsers: new function(){
this.browserListVersion = "2.0";
this.ready = false;
this.agt = (navigator.userAgent.toLowerCase() );
this.opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1 );
this.avant = (navigator.userAgent.toLowerCase().indexOf("avant") != -1 );
this.ie = (!this.opera && navigator.appName.indexOf("Microsoft") != -1 );
this.safari = (!this.ie && navigator.userAgent.toLowerCase().indexOf("safari") != -1 );
this.mozilla = (!this.opera && !this.ie && !this.safari );
this.is_major = (parseInt(navigator.appVersion) );
this.ie5 = ((this.ie) && (this.is_major == 4) && (this.agt.indexOf("msie 5.")!=-1) );
this.ie55 = ((this.ie) && (this.is_major == 4) && (this.agt.indexOf("msie 5.5")!=-1) );
this.ie6 = ((this.ie) && (this.is_major == 4) && (this.agt.indexOf("msie 6.")!=-1) );
this.ready = true;
}
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain browsers list object - end
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// object of more settings of outbrain - start
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
var outbrain_settings = (typeof(outbrain_settings) == 'object')? outbrain_settings: new function(){
var self = this;
// platforms
this.PLATFORM_TYPE_TYPEPAD = 0;
this.PLATFORM_TYPE_BLOGGER_SIDEBAR = 1;
this.PLATFORM_TYPE_TUMBLR = 2;
this.platformType = null
// versions
this.versions = new function(){
this.rater = "3.3.4";
this.mp = "3.3.3.1";
this.raterFull = "3.3.4.0";
this.css = "3.3.3";
this.whatIs = "3.3.0";
this.language = "3.2.0";
this.odb = "0.6";
}
// demo
this.demoMode = false;
this.globals = new function(){
this.scriptType = "text/javascript";
this.cssType = "text/css";
this.cssRel = "stylesheet";
}
// domains
this.domains = new function(){
this.odb = "odb.outbrain.com/";
this.outbrain = "http://www.outbrain.com/";
this.js = ((!this.demoMode) ? 'http://widgets.outbrain.com/':'http://s3.amazonaws.com/outbraintest.com/');
this.traffic = 'http://$IS_TESTtraffic.outbrain.com/network/redir';
}
// keys and agents, parners and users
this.keys_and_users = new function(){
this.odbKey = "AYQHSUWJ8576";
this.agentId = "blog_JS";
this.partnerName = null;
this.outbrainKey = null;
this.userName = null;
this.partnerKey = this.odbKey;
}
// odb locations
this.odb = new function(){
this.odbRatesRecorder = 'http://$IS_TESTrate.outbrain.com/rate.do'; // uri which records the vote
this.odbGetDataUrlGlobal = 'http://$IS_TEST' + self.domains.odb + 'utils/odb?key=$KEY&method=$METHOD&url=$PERMA_LINK&format=json&callback=outbrain_rater.returnedOdbData(${json},$VOTER_INDEX,$IS_REC)&timeframe=none$SELF_POSTS&lang=$LANGUAGE$ADDITIONAL';
this.odbGetDataUrlRegular = this.odbGetDataUrlGlobal;
this.odbGetDataUrlRec = this.odbGetDataUrlGlobal;
this.odbGetDataUrlRegular = this.odbGetDataUrlRegular.replace (/\$METHOD/g ,'get_score' );
this.odbGetDataUrlRegular = this.odbGetDataUrlRegular.replace (/\$IS_REC/g ,'false' );
this.odbGetDataUrlRegular = this.odbGetDataUrlRegular.replace (/\$SELF_POSTS/g ,'' );
this.odbGetDataUrlRegular = this.odbGetDataUrlRegular.replace (/\$ADDITIONAL/g ,'');
this.odbGetDataUrlRec = this.odbGetDataUrlRec.replace (/\$METHOD/g ,'get_score_rec');
this.odbGetDataUrlRec = this.odbGetDataUrlRec.replace (/\$IS_REC/g ,'true' );
//this.odbGetDataUrlRec = this.odbGetDataUrlRec.replace (/\$SELF_POSTS/g ,((typeof(OB_self_posts) == 'boolean')? "&blog_posts=" + OB_self_posts: ""));
this.odbGetDataUrlRec = this.odbGetDataUrlRec.replace (/\$ADDITIONAL/g ,'&idx=$VOTER_INDEX');
this.MPRequest = 'http://$IS_TEST' + self.domains.odb + 'utils/odb?key=$KEY&method=$METHOD&format=$FORMAT&num=$ITEMS_COUNT&source_url=$SOURCE_URL&callback=$CALLBACK&timeframe=none&min_count=$MIN_COUNT';
// $SOURCE_URL will be replaced later in MP widget
this.MPRequest = this.MPRequest.replace(/\$MIN_COUNT/g,2);
this.MPRequest = this.MPRequest.replace(/\$CALLBACK/g,"outbrain_MP.setData(${json})");
this.MPRequest = this.MPRequest.replace(/\$FORMAT/g,"json");
this.MPRequest = this.MPRequest.replace(/\$METHOD/g,"source_documents");
}
this.blogUtils = new function(){
this.baseUrl = 'http://' + ((this.demoMode)? 'test.' : '') + self.domains.odb + 'blogutils/';
this.getBlogSettings = this.baseUrl + 'BlogSettings.action?apiKey=$USER_KEY&surl=$SOURCE_URL&r=' + Math.random();//&callback=outbrain_customSettings.blogSettingsCB( ${has-settings} )';
this.submitBlogSettings = this.baseUrl + 'submitBlogSettings.action?apiKey=$USER_KEY';
}
// ping
this.ping = new function(){
this.id = "odbPingIframeId";
this.url = "http://odb.outbrain.com/utils/ping.html";
//this.url = "http://$IS_TESTodb.outbrain.com/utils/ping.html";
this.maxTime = 10;
}
// language
this.language = new function(){
this.defaultLangName = "deflang";
this.id = "outbrainLanguageJs";
this.url = self.domains.js + "lang_en.js";
this.retrayMilliSeconds = 100;
this.retrayMaxTimes = 10;
this.retrayGradualTimeout = false;
}
// rater
this.rater = new function(){
this.cssId = "cssLinkID";
this.cssUrl = self.domains.js + "OutbrainRater-"+self.versions.css+".css";
this.globalElementClass = "outbrainGlobalClass";
this.firstRaterPositionElementId = "outbrainCurrentPosition";
this.recommendations = new function(){
this.agentId = null;
this.type = "popular";
this.maxCalls = 10;
this.always = false;
this.showFramePage = true;
}
this.statuses = new function(){
this.RATER_PRE_RATE_MODE = 0;
this.RATER_RATE_MODE = 1;
this.RATER_POST_RATE_MODE = 2;
}
this.odb = new function(){
this.getScoreId = "outbrainPostRankRequestID";
this.getScoreRecId = "outbrainPostRecRankRequestID";
}
}
// most popular
this.MP = new function(){
this.id = "outbrainMPJs";
this.url = self.domains.js + "outbrainMP.js";
this.cssId = "outbrainMPCss";
this.css = self.domains.js + 'outbrainMP.css';
this.ids = new function(){
this.containerDiv = "outbrainMPDiv";
this.requestElement = "outbrainTopPostsDataScript";
this.odbRequest = self.odb.MPRequest;
}
this.classes = new function(){
this.item = "item";
this.itemOver = "item_hover";
this.itemOdd = "item_odd";
this.itemEven = "item_even";
this.itemFirst = "item_first";
this.itemLast = "item_last";
}
this.others = new function(){
this.hideTitle = false;
this.widgetTitle = "MPP";
this.titleMaxChar = 100;
this.titleTagName = "h2";
this.titleClassName = "outbrain_MP_title";
}
}
// what is
this.whatIs = new function(){
this.id = "whatIsOutbrainJs";
this.url = self.domains.js + 'OutbrainWhatIsIt-'+self.versions.whatIs+'.js';
}
this.customSettings = new function(){
this.id = "outbrainCustomSettings";
this.keyTagName = "OBKey";
this.enabled = true;
}
// templates helpers
this.templateOptions = [ "stars", "firstLine", "secondLine", "recommendations" ];
this.templateDefaults = [ false, false, false, false ];
this.defaultTemplateName = "general";
this.defaultTemplate = "bottom;"+this.defaultTemplateName+";false;stars firstLine secondLine;"+this.defaultTemplateName; // when no user template
this.templateGlobalSplit = ";";
this.templateItemsSplit = " ";
this.templateItemsJoin = "-";
this.defaultMatrixInfos = '{"matrixInfos":{"general":{"matrixSource":"http://widgets.outbrain.com/matrix.png","matrixYpositionThanks":"60","matrixYHeight":"30","matrixXlength":"96","matrixAllXlength":"960","matrixAllYlength":"106","starWidth":"19","starHeight":"30","shadowYoffset":"5"}}}';
this.timestampDef = new function(){
this.installTimestamp = null;
this.activeRecTimestamp = 1211454347;
}
}
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// object of more settings of outbrain - end
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// matrix_info_ start
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var outbrain_matrix_info = typeof(outbrain_matrix_info) == "function" ? outbrain_matrix_info : function(){
this.matrixYHeight = 30;
this.matrixYpositionThanks = 60;
this.matrixXlength = 96;
this.matrixAllXlength = 960;
this.matrixAllYlength = 106;
this.starHeight = 30;
this.starWidth = 19;
this.shadowYoffset = 0;
this.matrixSource = outbrain_settings.domains.js + "matrix" + ".png" ;
this.matrixSourceRTL = outbrain_settings.domains.js + "matrix" + "_rtl" +".png" ;
this.init = function(templateMatrixInfo){
if (templateMatrixInfo == null )
return ;
if ((typeof(templateMatrixInfo.matrixSource) != 'undefined') && (templateMatrixInfo.matrixSource != null))
{ this.matrixSource = templateMatrixInfo.matrixSource; }
if ((typeof(templateMatrixInfo.matrixSourceRTL) != 'undefined') && (templateMatrixInfo.matrixSourceRTL != null))
{ this.matrixSourceRTL = templateMatrixInfo.matrixSourceRTL; }
if ((typeof(templateMatrixInfo.matrixYHeight) != 'undefined') && (templateMatrixInfo.matrixYHeight != null))
{ this.matrixYHeight = templateMatrixInfo.matrixYHeight; }
if ((typeof(templateMatrixInfo.matrixYpositionThanks) != 'undefined') && (templateMatrixInfo.matrixYpositionThanks != null))
{ this.matrixYpositionThanks = templateMatrixInfo.matrixYpositionThanks; }
if ((typeof(templateMatrixInfo.matrixXlength) != 'undefined') && (templateMatrixInfo.matrixXlength != null))
{ this.matrixXlength = templateMatrixInfo.matrixXlength; }
if ((typeof(templateMatrixInfo.matrixAllXlength) != 'undefined') && (templateMatrixInfo.matrixAllXlength != null))
{ this.matrixAllXlength = templateMatrixInfo.matrixAllXlength; }
if ((typeof(templateMatrixInfo.matrixAllYlength) != 'undefined') && (templateMatrixInfo.matrixAllYlength != null))
{ this.matrixAllYlength = templateMatrixInfo.matrixAllYlength; }
if ((typeof(templateMatrixInfo.starWidth) != 'undefined') && (templateMatrixInfo.starWidth != null))
{ this.starWidth = templateMatrixInfo.starWidth; }
if ((typeof(templateMatrixInfo.starHeight) != 'undefined') && (templateMatrixInfo.starHeight != null))
{ this.starHeight = templateMatrixInfo.starHeight; }
if ((typeof(templateMatrixInfo.shadowYoffset) != 'undefined') && (templateMatrixInfo.shadowYoffset != null))
{ this.shadowYoffset = templateMatrixInfo.shadowYoffset; }
}
}
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// matrix_info_ end
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// user custom settings object
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var outbrain_customSettings_object = typeof(outbrain_customSettings_object) == "function" ? outbrain_customSettings_object : function(){
var self_custom = this;
this.ready = false;
this.pageLoaded = false;
this.isReadyMP = false;
this.hasSettings = false;
//------------------------------------------------------------------------------------------------------------------------
// insertCustomSettingsScriptIntoDom
//
this.insertCustomSettingsScriptIntoDom = function(scriptElement){
new outbrain_timeout(
function(){
var returnValue = false;
if (OB_odb_life != null){
returnValue = ((OB_odb_life.getStatus()==OB_odb_life.STAT_OK) && (document.getElementsByTagName("head").length > 0));
}
return returnValue;
},
function(){
var heads = document.getElementsByTagName("head");
heads[0].appendChild(scriptElement);
},
null,
null,
100,
15,
false
)
}
//------------------------------------------------------------------------------------------------------------------------
this.waitToOdbLifeSign = function(){
new outbrain_timeout(
function(){
return (OB_odb_life.getStatus()==OB_odb_life.STAT_OK);
},
function(){
self_custom.setUserCustomSettings();
},
null,
null,
100,
15,
false
)
}
//------------------------------------------------------------------------------------------------------------------------
this.loadUserCustomSettings = function(){
var script = document.createElement("script");
script.type = outbrain_settings.globals.scriptType;
script.id = outbrain_settings.customSettings.id;
script.src = outbrain_settings.blogUtils.getBlogSettings;
this.insertCustomSettingsScriptIntoDom(script);
}
//-----------------------------------------------------------------------------------------------------------------------------
this.setMPUserCustomSettings = function(){
var testString = ((outbrain_settings.demoMode)? 'test.':'');
var partnerKey = outbrain_settings.keys_and_users.partnerKey;
outbrain_settings.odb.MPRequest = outbrain_settings.odb.MPRequest.replace (/\$IS_TEST/g,testString);
outbrain_settings.odb.MPRequest = outbrain_settings.odb.MPRequest.replace (/\$KEY/g,partnerKey);
outbrain_settings.odb.MPRequest = outbrain_settings.odb.MPRequest.replace(/\$ITEMS_COUNT/g , (((typeof(OB_MP_itemsCount) == 'number') && (OB_MP_itemsCount>0))? ((OB_MP_itemsCount<=10)? OB_MP_itemsCount:10) : 3));
if (typeof(OB_MP_cssLinkUrl) == 'string'){
outbrain_settings.MP.css = OB_MP_cssLinkUrl;
}
if (typeof(OB_MP_hideTitle) == 'boolean'){
outbrain_settings.MP.others.hideTitle = OB_MP_hideTitle;
}
if (typeof(OB_MP_title) == 'string'){
outbrain_settings.MP.others.widgetTitle = OB_MP_title;
}
if (typeof(OB_MP_postTitleMaxChar) == 'number'){
outbrain_settings.MP.others.titleMaxChar = OB_MP_postTitleMaxChar;
}
if (typeof(OB_MP_titleTagName) == 'string'){
outbrain_settings.MP.others.titleTagName = OB_MP_titleTagName;
}
if (typeof(OB_MP_titleClassName) == 'string'){
outbrain_settings.MP.others.titleClassName = OB_MP_titleClassName;
}
this.isReadyMP = true;
}
//------------------------------------------------------------------------------------------------------------------------
this.blogSettingsCB = function( blogHasSettings ){
self_custom.hasSettings = blogHasSettings;
self_custom.setUserCustomSettings();
}
//------------------------------------------------------------------------------------------------------------------------
this.setUserCustomSettings = function(){
if (typeof(OB_platformType) == 'number'){
outbrain_settings.platformType = OB_platformType;
}
if (typeof(OB_demoMode) == 'boolean'){
outbrain_settings.demoMode = OB_demoMode
}
if (typeof(OB_agentId) == 'string'){
outbrain_settings.keys_and_users.agentId = OB_agentId;
}
if (typeof(OB_partnerName) == 'string'){
outbrain_settings.keys_and_users.partnerName = OB_partnerName;
}
if (typeof(OB_user) == 'string'){
outbrain_settings.keys_and_users.userName = OB_user;
}
if (typeof(OB_partnerKey) == 'string'){
outbrain_settings.keys_and_users.partnerKey = OB_partnerKey;
}
if (typeof(OB_showFramePage) == 'boolean'){
outbrain_settings.rater.recommendations.showFramePage = OB_showFramePage;
}
var testString = ((outbrain_settings.demoMode)? 'test.':'');
outbrain_settings.domains.traffic = outbrain_settings.domains.traffic.replace (/\$IS_TEST/g,testString);
outbrain_settings.odb.odbRatesRecorder = outbrain_settings.odb.odbRatesRecorder.replace (/\$IS_TEST/g,testString);
outbrain_settings.odb.odbGetDataUrlGlobal = outbrain_settings.odb.odbGetDataUrlGlobal.replace (/\$IS_TEST/g,testString);
outbrain_settings.odb.odbGetDataUrlRec = outbrain_settings.odb.odbGetDataUrlRec.replace (/\$IS_TEST/g,testString);
outbrain_settings.odb.odbGetDataUrlRegular = outbrain_settings.odb.odbGetDataUrlRegular.replace (/\$IS_TEST/g,testString);
outbrain_settings.odb.odbGetDataUrlRec = outbrain_settings.odb.odbGetDataUrlRec.replace (/\$SELF_POSTS/g ,((typeof(OB_self_posts) == 'boolean')? "&blog_posts=" + OB_self_posts: ""));
if (outbrain_settings.keys_and_users.userName != null){
outbrain_settings.odb.odbGetDataUrlRegular += "&user="+outbrain_settings.keys_and_users.userName;
}
if (outbrain_settings.keys_and_users.partnerName != null){
outbrain_settings.odb.odbGetDataUrlRegular += "&type=both";
}
if (typeof(OB_langJS) == 'string' && OB_langJS != ''){
outbrain_settings.language.url = OB_langJS;
}
var partnerKey = outbrain_settings.keys_and_users.partnerKey;
outbrain_settings.odb.odbGetDataUrlGlobal = outbrain_settings.odb.odbGetDataUrlGlobal.replace (/\$KEY/g,partnerKey);
outbrain_settings.odb.odbGetDataUrlRegular = outbrain_settings.odb.odbGetDataUrlRegular.replace (/\$KEY/g,partnerKey);
outbrain_settings.odb.odbGetDataUrlRec = outbrain_settings.odb.odbGetDataUrlRec.replace (/\$KEY/g,partnerKey);
outbrain_settings.rater.recommendations.agentId = outbrain_settings.keys_and_users.agentId + "_rec";
this.ready = true;
}
//------------------------------------------------------------------------------------------------------------------------
this.sendInlineCS = function ( OBBSpath ){
var OBBS_SE = document.createElement("script");
OBBS_SE.setAttribute('id','OBBSCall' );
OBBS_SE.setAttribute('type','text/javascript');
OBBS_SE.setAttribute('src', OBBSpath );
var heads = document.getElementsByTagName("head");
if( heads.length > 0 ){
heads[0].insertBefore(OBBS_SE, heads[0].firstChild);
}
}
//------------------------------------------------------------------------------------------------------------------------
this.inlineCSUrlOnLoad = function() {
new outbrain_timeout(
function(){
return self_custom.ready;
},
function(){
var OBBSEpochTime = 1210838298671; //The release time!!!
var OBBSSExpiration = 777600000; //9 days
var OBBStmpDate = new Date();
var OBBSNow = OBBStmpDate.getTime();
OBCTm = typeof(OBCTm) != 'undefined' ? OBCTm : OBBSEpochTime;
if( self_custom.hasSettings != true ){
if ( ( ( OBBSEpochTime < OBCTm) && (OBBSNow - OBCTm < OBBSSExpiration) )
|| ( ( OBBSEpochTime >= OBCTm ) && (OBBSEpochTime + OBBSSExpiration > OBBSNow ) ) ) {
if( outbrain_settings.keys_and_users.outbrainKey == null ){
outbrain_settings.keys_and_users.outbrainKey = self_custom.getOutbrainKey();
}
if( outbrain_settings.keys_and_users.outbrainKey != null ){
var obSettings=new Array();
obSettings[0]= ['OB_isOnHeader',typeof(OB_isOnHeader) != 'undefined' ? OB_isOnHeader : null];
obSettings[1]= ['OB_showRec',typeof(OB_showRec) != 'undefined' ? OB_showRec : null];
obSettings[2]= ['OB_showMP',typeof(OB_showMP) != 'undefined' ? OB_showMP : null];
obSettings[3]= ['OB_extraBRType',typeof(OB_extraBRType) != 'undefined' ? OB_extraBRType : null];
obSettings[4]= ['OB_langJS',typeof(OB_langJS) != 'undefined' ? (OB_langJS != '' ? OB_langJS : null ) : null];
obSettings[5]= ['OB_userClear',typeof(OB_userClear) != 'undefined' ? OB_userClear : null];
obSettings[6]= ['OB_MP_itemsCount',typeof(OB_MP_itemsCount) != 'undefined' ? OB_MP_itemsCount : null];
obSettings[7]= ['OB_self_posts',typeof(OB_self_posts) != 'undefined' ? OB_self_posts : null];
obSettings[8]= ['OB_containerClass',typeof(OB_containerClass) != 'undefined' ? encodeURIComponent(OB_containerClass) : null];
obSettings[9]= ['OB_footerClass',typeof(OB_footerClass) != 'undefined' ? encodeURIComponent(OB_footerClass) : null];
obSettings[10]= ['OB_permaLinkClass',typeof(OB_permaLinkClass) != 'undefined' ? encodeURIComponent(OB_permaLinkClass) : null];
obSettings[11]= ['OB_insertInElement',typeof(OB_insertInElement) != 'undefined' ? OB_insertInElement : null];
obSettings[12]= ['OB_MP_title',typeof(OB_MP_title) != 'undefined' ? encodeURIComponent(OB_MP_title) : null];
obSettings[13]= ['OB_parentsCount',typeof(OB_parentsCount ) != 'undefined' ? encodeURIComponent(OB_parentsCount) : null];
obSettings[14]= ['OB_showFramePage',typeof(OB_showFramePage ) != 'undefined' ? encodeURIComponent(OB_showFramePage) : null];
outbrain_settings.blogUtils.submitBlogSettings = outbrain_settings.blogUtils.submitBlogSettings.replace(/\$USER_KEY/g,outbrain_settings.keys_and_users.outbrainKey);
var OBBSpath = outbrain_settings.blogUtils.submitBlogSettings;
var isDoSubmit = false;
for (i=0;i<obSettings.length;i++) {
if( obSettings[i][1] != null ){
OBBSpath += '&' + obSettings[i][0] + '=' + obSettings[i][1];
isDoSubmit = true;
}
}
if( isDoSubmit )
self_custom.sendInlineCS( OBBSpath );
}
}
}
},
null,
null,
500,
20,// Try only 2 times, after 1 second the OBKey should already be in the DOM!
true
);
}
//------------------------------------------------------------------------------------------------------------------------
this.registerSubmitSettings = function() {
if (window.addEventListener){ //DOM method for binding an event
window.addEventListener("load", function(){ self_custom.inlineCSUrlOnLoad(); } , false)
} else if (window.attachEvent){ //IE exclusive method for binding an event
window.attachEvent("onload", function(){ self_custom.inlineCSUrlOnLoad(); } )
} else if (document.getElementById){ //support older modern browsers
var oldOnLoad = window.onload;
window.onload=function(){oldOnLoad(); self_custom.inlineCSUrlOnLoad();}
}
}
//------------------------------------------------------------------------------------------------------------------------
this.getOutbrainKey = function(){
var key = null;
var keyTags = document.getElementsByName( outbrain_settings.customSettings.keyTagName );
if( keyTags.length > 0 ){
if( keyTags[0].value != null ){
key = keyTags[0].value;
}else
key = keyTags[0].content;
key = encodeURIComponent( key );
}else if( typeof(OB_outbrainKey) == 'string' ){
key = encodeURIComponent( OB_outbrainKey );
}
return key;
}
//------------------------------------------------------------------------------------------------------------------------
this.init = function(){
var apiKey = null;
var feedUrl = null;
new outbrain_timeout(
function(){
var isSuccess = false;
if( outbrain_settings.customSettings.enabled ){
feedUrl = outbrain_dom.extractFeedUrl();
outbrain_settings.keys_and_users.outbrainKey = self_custom.getOutbrainKey();
if( feedUrl != null ){
feedUrl = encodeURIComponent( feedUrl );
isSuccess = true;
}
else{
if( outbrain_settings.keys_and_users.outbrainKey != null ){
apiKey = outbrain_settings.keys_and_users.outbrainKey;
isSuccess = true;
}
}
}
return isSuccess;
},
function(){
outbrain_settings.blogUtils.getBlogSettings = outbrain_settings.blogUtils.getBlogSettings.replace(/\$USER_KEY/g,apiKey != null ? apiKey : '' );
outbrain_settings.blogUtils.getBlogSettings = outbrain_settings.blogUtils.getBlogSettings.replace(/\$SOURCE_URL/g,feedUrl != null ? feedUrl : '' );
self_custom.registerSubmitSettings();
self_custom.loadUserCustomSettings();
},
null,
function(){
self_custom.waitToOdbLifeSign();
},
500,
10,// Try only 2 times, after 1 second the OBKey should already be in the DOM!
true,
function(){
return (self_custom.pageLoaded == true);
}
);
}
this.init();
}
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// user custom settings object - end
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain_timeout - start
// implement re-tries engine with self timeout, function checker and function to be done when the first returns true
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
var outbrain_timeout = function(checkFunction,onSuccess,onFailed,onTotalFailed,milliSeconds,maxTimes,gradualTimeout,isBreak){
// maxTimes = 1000 is no-end
var self = this;
var reTried = 0;
this.start = function (){
reTried++;
if (checkFunction()){
onSuccess();
} else {
if ( ( typeof(isBreak) == 'function' && isBreak() )
|| ( (reTried == maxTimes) && (maxTimes != 1000) ) ){ // timeout
if (typeof(onTotalFailed) == 'function'){
onTotalFailed();
} else {
return;
}
} else {
if (typeof(onFailed) == 'function'){
onFailed();
}
if (gradualTimeout){
setTimeout(function(){self.start()},milliSeconds);
} else {
setTimeout(function(){self.start()},reTried*milliSeconds);
}
}
}
}
this.start();
}
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain_timeout - end
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain's odb life sign object - start
// check if ODB server returns ping
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
var outbrain_odb_life_object = typeof(outbrain_odb_life_object) == 'function' ? outbrain_odb_life_object : function(maxSec,source,id){
this.STAT_OK = 1;
this.STAT_NO_LOAD_EVENT = 2;
this.STAT_TIME_ELAPSED = 3;
this.odbLife = false;
this.frameSrc = source;
this.frameId = id;
this.startTime = null;
this.finishTime = null;
this.timeDiff = null; // sec
this.maxOkTimeDiff = maxSec; // sec
this.responseTimeout = null;
this.noResponseTimeout = null;
var self = this;
// insert odb test element and eventListener.
this.init = function(){
// change location variable
this.addRandomNumber();
// create
var odbIframe = "<iframe id="+this.frameId+" frameBorder='0' name='odbFrame' style='width:0px;height:0px;display:none;'></iframe>";
// insert
this.insert(odbIframe);
this.start();
}
this.addRandomNumber = function(){
var index = this.frameSrc.indexOf("?");
var random = Math.random();
var randomStr = "random=" + random;
if (index > -1){ // there is "?" in the string - there is queryString!
this.frameSrc += "&" + randomStr;
} else {
this.frameSrc += "?" + randomStr;
}
}
// return the iframe element
this.getIframeElement = function(){
return document.getElementById(this.frameId);
}
// write the element to the DOM
this.insert = function(str){
document.write (str);
}
// set the iframe src
this.redirect = function(strLocation){
var odbIframe = self.getIframeElement();
if (odbIframe){
this.startTime = new Date();
window.frames['odbFrame'].location.replace(strLocation);
}
}
// add 'onload' event listener to the element
this.start = function(){
var odbIframe = self.getIframeElement();
if (odbIframe){
// add event listener
if (document.addEventListener) //DOM method for binding an event
odbIframe.addEventListener("load", function(){self.frameReady();}, false);
else if (document.attachEvent) //IE exclusive method for binding an event
odbIframe.attachEvent("onload", function(){self.frameReady();});
else if (document.getElementById) //support older modern browsers
odbIframe.onload=function(){self.frameReady();}
// set the url location
this.redirect( this.frameSrc );
// set timeout for waiting for response
this.noResponseTimeout = setTimeout(function(){self.noResponseAfterMaxTime();},self.maxOkTimeDiff*1000);
} else {
this.responseTimeout = setTimeout(self.start,1000);
}
}
// when the event listener fired
this.frameReady = function(){
this.finishTime = new Date();
clearTimeout(this.noResponseTimeout);
this.getTimeDiff();
//this.removeFrame();
this.odbLife = true;
}
// cancel all if there is no response after this.maxOkTimeDiff seconds
this.noResponseAfterMaxTime = function(){
clearTimeout(this.responseTimeout);
this.removeFrame();
}
// calculate time difference between start (insert) and end (frame loaded)
this.getTimeDiff = function(){
this.timeDiff = ((this.finishTime.getTime() - this.startTime.getTime()) / 1000);
}
// remove the frame from the DOM
this.removeFrame = function(){
var element = this.getIframeElement();
if (element){
window.frames['odbFrame'].location.replace('about:blank');
element.parentNode.removeChild(element);
}
}
// return the ODB status
this.getStatus = function(){
var retStatus = this.STAT_OK;
if (!this.odbLife){
retStatus = this.STAT_NO_LOAD_EVENT;
}
else if (this.timeDiff > this.maxOkTimeDiff){
retStatus = this.STAT_TIME_ELAPSED;
}
return retStatus;
}
// start all
this.init();
}
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain's odb life sign object - end
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain object to play with the DOM - start
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
var outbrain_dom_object = (typeof(outbrain_dom_object) == 'function')? outbrain_dom_object: function(){
//------------------------------------------------------------------------------------------------------------------------
this.$ = function(id){
return document.getElementById(id);
}
//------------------------------------------------------------------------------------------------------------------------
this.elementInsertion = function(mainElement,newElement,top,inside){
if (typeof(newElement)=='string'){
var newElementNode = document.createElement("div");
newElementNode.innerHTML = newElement;
newElement = newElementNode;
}
if (top == true ){
if (inside){
newElement = this.insertBefore( newElement , mainElement.firstChild );
} else {
newElement = this.insertBefore( newElement , mainElement );
}
} else {
if (inside){
newElement = mainElement.appendChild(newElement);
} else {
newElement = this.insertAfter( newElement , mainElement );
}
}
return [newElement,mainElement];
}
//------------------------------------------------------------------------------------------------------------------------
this.insertBefore = function (newNode,beforeNode){
return beforeNode.parentNode.insertBefore( newNode , beforeNode );
}
//------------------------------------------------------------------------------------------------------------------------
this.extractFooter = function (parentDiv,footerClassName){
var footerDiv = null;
if (typeof(parentDiv)=='undefined')
return null;
var divArray = parentDiv.getElementsByTagName("DIV");
for(var i=0; i<divArray.length ; i++)
{
var div = divArray[i];
if ( div.className == footerClassName )
{
footerDiv = div;
}
}
return footerDiv;
}
//------------------------------------------------------------------------------------------------------------------------
this.insertAfter = function (newNode,afterNode){
var newCreatedChild = null;
var OB_pmd = outbrain_rater.pmd;
if ((outbrain_settings.platformType == outbrain_settings.PLATFORM_TYPE_BLOGGER_SIDEBAR) && (outbrain_browsers.ie == true)){
if (OB_pmd.postFooterDivClassname != null){
for( var footerTagIdx = 0 ; footerTagIdx < OB_pmd.postFooterDivClassname.length ; footerTagIdx++ ){
var footerDiv = this.extractFooter( afterNode.parentNode , OB_pmd.postFooterDivClassname[footerTagIdx] );
if( footerDiv != null ){
try{
newCreatedChild = afterNode.parentNode.insertBefore( newNode , afterNode.nextSibling );
}catch( error ){
try{
newCreatedChild = afterNode.nextSibling.parentNode.insertBefore( newNode , afterNode.nextSibling );
}catch( innerError ){
//LOG:: ERROR to insert rater
newCreatedChild = null;
}
}
break;
}
}
}
}
else{
newCreatedChild = afterNode.parentNode.insertBefore( newNode , afterNode.nextSibling );
}
return newCreatedChild;
}
//------------------------------------------------------------------------------------------------------------------------
this.setInnerHTML = function ( currNode , newHTML ){
try{
currNode.innerHTML = newHTML;
}catch( error ){
var clonedNode = currNode.cloneNode(false);
clonedNode.innerHTML = newHTML;
currNode.parentNode.replaceChild( clonedNode , currNode );
}
}
//--------------------------------------------------------------------------------------------------------
this.extractFeedUrl = function(){
if (typeof(OB_MP_feed) == 'string'){
return OB_MP_feed;
}
var head = document.getElementsByTagName("head");
var url = null;
if ((head) && (head.length > 0)){
var linkTags = head[0].getElementsByTagName("link");
var currLink = null;
for (var index=0;( index < linkTags.length && url == null); ++index ){
currLink = linkTags[index];
if ((currLink.type != null) && ((currLink.type == "application/rss+xml") || (currLink.type == "application/atom+xml")) && (currLink.href != null) && (currLink.href != '')){
url = currLink.href;
}
}
}
return url;
}
}
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain object to play with the DOM - end
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain's language object - start
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
var OB_lang_object = function(){
//------------------------------------------------------------------------------------------------------------------------
this.isInit = false;
var self = this;
this.id = "EN";
this.name = "LANGUAGE_NAME";
this.RATE_DESCRIPTION = [
"BAD_STR",
"BORING_STR",
"OK_STR",
"GOOD_STR",
"EXCELLENT_STR"
]; // user rate options
this.PERSONAL_RATE_DESC = [
"DISLIKED_{X.xx}_BY_{Y}_PEOPLE_LIKE_YOU",
"RATED_{X.xx}_BY_{Y}_PEOPLE_LIKE_YOU",
"RECOMMENDED_{X.xx}_BY_{Y}_PEOPLE_LIKE_YOU"
];
this.RATE_POST_RATE = [
"YOU_HATED_STRING",
"DIDNT_LIKE_STRING",
"WAS_OK_STRING",
"LIKED_STRING",
"LOVE_STRING"
];
this.RATE_POST_RATE_FOR_RECOMMENDATIONS = [
"OUR_READERS_ALSO_LIKE:",
"YOU_HATED_THIS_POST_({starsImage}),_YOU_MIGHT_LIKE:",
"YOU_DIDN'T_LIKE_THIS_POST_({starsImage}),_YOU_MIGHT_LIKE:",
"YOU_THOUGHT_THIS_WAS_OK_({starsImage}),_YOU_MIGHT_LIKE:",
"YOU_LIKED_THIS_POST_({starsImage}),_YOU_MIGHT_ALSO_LIKE:",
"YOU_LOVED_THIS_POST_({starsImage}),_YOU_MIGHT_ALSO_LIKE:"
];
this.THANKS_STR = "THANKS...."; // after user rates
this.BE_THE_FIRST_STR = "BE_THE_FIRST_TO_RATE_THIS";
this.UNABLE_TO_SUBMIT_STR = "UNABLE_TO_SUBMIT_YOUR_RATE_PLEASE_CHECK_YOUR_INTERNET_CONNECTION.";
this.RATED_X_BY_Y_PEOPLE = "RATED_{X.xx}_BY_{Y}_PEOPLE";
this.RATED_X_BY_1_PERSON = "RATED_{X.xx}_BY_1_PERSON";
this.AVERAGE_RATING_X_BY_Y_PEOPLE = "AVERAGE_RATING_X.xx_BY_Y_PEOPLE";
this.RATED_X_BY_YOU = "RATED_{X.xx}_BY_Y0U";
this.RATED_X_BY_YOU_AND_1_OTHER = "RATED_{X.xx}_BY_Y0U_AND_1_OTHER";
this.RATED_X_BY_YOU_AND_Y_OTHERS = "RATED_{X.xx}_BY_Y0U_AND_{Y}_OTHERS";
this.HOW = "HOW?"; // used in personalization
this.BY = "BY";
this.WHATS_THIS = "WHATS_THIS"; // currently not in use
// currently following variables is for recommendations only
this.THIS_SITE = "THIS_SITE";
this.MOST_POPULAR = "Most_Popular_Posts";
this.MIGHT_ALSO_LIKE = "YOU_MIGHT_ALSO_LIKE";
this.MORE_RECOMMENDED_SINGLE = "MORE_RECOMMENDED_SINGLE";
this.MORE_RECOMMENDED_PLURAL = "MORE_RECOMMENDED_POSTS";
this.MORE_RECOMMENDED_CLOSE_SINGLE = "HIDE_MORE_RECOMMENDED_POST";
this.MORE_RECOMMENDED_CLOSE_PLURAL = "HIDE_MORE_RECOMMENDED_POSTS";
this.IS_RTL = false;
this.OPTIONAL_ADDONS = new function(){
this.mostPopular = false;
this.recommendations = false;
}
//------------------------------------------------------------------------------------------------------------------------
this.initLang = function (lang){
var i;
if ((typeof(lang.id) != 'undefined') && (lang.id != null)){
this.id = lang.id;
} else {
this.id = "en";
}
if ((typeof(lang.name) != 'undefined') && (lang.name != null)){
this.name = lang.name;
} else {
this.name = "en";
}
for (i=0;i<this.RATE_DESCRIPTION.length;i++){
if (lang.RATE_DESCRIPTION[i] != null){ this.RATE_DESCRIPTION[i] = lang.RATE_DESCRIPTION[i]; }
}
for (i=0;i<this.PERSONAL_RATE_DESC.length;i++){
if (lang.PERSONAL_RATE_DESC[i] != null){ this.PERSONAL_RATE_DESC[i] = lang.PERSONAL_RATE_DESC[i]; }
}
for (i=0;i<this.RATE_POST_RATE.length;i++){
if (lang.RATE_POST_RATE[i] != null){ this.RATE_POST_RATE[i] = lang.RATE_POST_RATE[i]; }
}
if (typeof(lang.RATE_POST_RATE_FOR_RECOMMENDATIONS) != 'undefined'){
for (i=0;i<this.RATE_POST_RATE_FOR_RECOMMENDATIONS.length;i++){
if (lang.RATE_POST_RATE_FOR_RECOMMENDATIONS[i] != null){ this.RATE_POST_RATE_FOR_RECOMMENDATIONS[i] = lang.RATE_POST_RATE_FOR_RECOMMENDATIONS[i]; }
}
}
// thanks
if ((typeof(lang.THANKS_STR) != 'undefined') && (lang.THANKS_STR != null))
{ this.THANKS_STR = lang.THANKS_STR; }
// might also like
if ((typeof(lang.MIGHT_ALSO_LIKE) != 'undefined') && (lang.MIGHT_ALSO_LIKE != null))
{ this.MIGHT_ALSO_LIKE = lang.MIGHT_ALSO_LIKE; }
// more recommended for one recommended link
if ((typeof(lang.MORE_RECOMMENDED_SINGLE) != 'undefined') && (lang.MORE_RECOMMENDED_SINGLE != null))
{ this.MORE_RECOMMENDED_SINGLE = lang.MORE_RECOMMENDED_SINGLE; }
// more recommended for > 1
if ((typeof(lang.MORE_RECOMMENDED_PLURAL) != 'undefined') && (lang.MORE_RECOMMENDED_PLURAL != null))
{ this.MORE_RECOMMENDED_PLURAL = lang.MORE_RECOMMENDED_PLURAL; }
// close more recommended = 1
if ((typeof(lang.MORE_RECOMMENDED_CLOSE_SINGLE) != 'undefined') && (lang.MORE_RECOMMENDED_CLOSE_SINGLE != null))
{ this.MORE_RECOMMENDED_CLOSE_SINGLE = lang.MORE_RECOMMENDED_CLOSE_SINGLE; }
// close more recommended > 1
if ((typeof(lang.MORE_RECOMMENDED_CLOSE_PLURAL) != 'undefined') && (lang.MORE_RECOMMENDED_CLOSE_PLURAL != null))
{ this.MORE_RECOMMENDED_CLOSE_PLURAL = lang.MORE_RECOMMENDED_CLOSE_PLURAL; }
// be the first to rate
if ((typeof(lang.BE_THE_FIRST_STR) != 'undefined') && (lang.BE_THE_FIRST_STR != null))
{ this.BE_THE_FIRST_STR = lang.BE_THE_FIRST_STR; }
// unable to submit
if ((typeof(lang.UNABLE_TO_SUBMIT_STR) != 'undefined') && (lang.UNABLE_TO_SUBMIT_STR != null))
{ this.UNABLE_TO_SUBMIT_STR = lang.UNABLE_TO_SUBMIT_STR; }
// how
if ((typeof(lang.HOW) != 'undefined') && (lang.HOW != null))
{ this.HOW = lang.HOW; }
// whats this
if ((typeof(lang.WHATS_THIS) != 'undefined') && (lang.WHATS_THIS != null))
{ this.WHATS_THIS = lang.WHATS_THIS; }
// by
if ((typeof(lang.BY) != 'undefined') && (lang.BY != null))
{ this.BY = lang.BY; }
// this site
if ((typeof(lang.THIS_SITE) != 'undefined') && (lang.THIS_SITE != null))
{ this.THIS_SITE = lang.THIS_SITE; }
// most popular posts
if ((typeof(lang.MOST_POPULAR) != 'undefined') && (lang.MOST_POPULAR != null))
{ this.MOST_POPULAR = lang.MOST_POPULAR; }
// average rating x by y people
if ((typeof(lang.AVERAGE_RATING_X_BY_Y_PEOPLE) != 'undefined') && (lang.AVERAGE_RATING_X_BY_Y_PEOPLE != null) && (lang.AVERAGE_RATING_X_BY_Y_PEOPLE.indexOf('{X.xx}') > -1) && (lang.AVERAGE_RATING_X_BY_Y_PEOPLE.indexOf('{Y}') > -1))
{
this.AVERAGE_RATING_X_BY_Y_PEOPLE = lang.AVERAGE_RATING_X_BY_Y_PEOPLE;
} else if ((typeof(lang.AVERAGE_RATING_X_BY_Y_PEOPLE) != 'undefined') && (lang.AVERAGE_RATING_X_BY_Y_PEOPLE != null) && (lang.AVERAGE_RATING_X_BY_Y_PEOPLE.indexOf('X.xx') > -1) && (lang.AVERAGE_RATING_X_BY_Y_PEOPLE.indexOf(' Y ') > -1)){
// older versions (2.1.2-)
this.AVERAGE_RATING_X_BY_Y_PEOPLE = lang.AVERAGE_RATING_X_BY_Y_PEOPLE;
}
// rated x by 1 person
if ((typeof(lang.RATED_X_BY_1_PERSON) != 'undefined') && (lang.RATED_X_BY_1_PERSON != null) && (lang.RATED_X_BY_1_PERSON.indexOf('{X.xx}') > -1))
{
this.RATED_X_BY_1_PERSON = lang.RATED_X_BY_1_PERSON;
} else if ((typeof(lang.RATED_X_BY_1_PERSON) != 'undefined') && (lang.RATED_X_BY_1_PERSON != null) && (lang.RATED_X_BY_1_PERSON.indexOf('X.xx') > -1)){
// older
this.RATED_X_BY_1_PERSON = lang.RATED_X_BY_1_PERSON;
}
// rated x by t people
if ((typeof(lang.RATED_X_BY_Y_PEOPLE) != 'undefined') && (lang.RATED_X_BY_Y_PEOPLE != null) && (lang.RATED_X_BY_Y_PEOPLE.indexOf('{X.xx}') > -1) && (lang.RATED_X_BY_Y_PEOPLE.indexOf('{Y}')))
{
this.RATED_X_BY_Y_PEOPLE = lang.RATED_X_BY_Y_PEOPLE;
} else if ((typeof(lang.RATED_X_BY_Y_PEOPLE) != 'undefined') && (lang.RATED_X_BY_Y_PEOPLE != null) && (lang.RATED_X_BY_Y_PEOPLE.indexOf('X.xx') > -1) && (lang.RATED_X_BY_Y_PEOPLE.indexOf(' Y '))){
// older
this.RATED_X_BY_Y_PEOPLE = lang.RATED_X_BY_Y_PEOPLE;
}
// rated x by you and 1 other
if ((typeof(lang.RATED_X_BY_YOU_AND_1_OTHER) != 'undefined') && (lang.RATED_X_BY_YOU_AND_1_OTHER != null) && (lang.RATED_X_BY_YOU_AND_1_OTHER.indexOf('{X.xx}') > -1))
{
this.RATED_X_BY_YOU_AND_1_OTHER = lang.RATED_X_BY_YOU_AND_1_OTHER;
} else if ((typeof(lang.RATED_X_BY_YOU_AND_1_OTHER) != 'undefined') && (lang.RATED_X_BY_YOU_AND_1_OTHER != null) && (lang.RATED_X_BY_YOU_AND_1_OTHER.indexOf('{X.xx}') > -1)){
// older
this.RATED_X_BY_YOU_AND_1_OTHER = lang.RATED_X_BY_YOU_AND_1_OTHER;
}
// rated x by you and y others
if ((typeof(lang.RATED_X_BY_YOU_AND_Y_OTHERS) != 'undefined') && (lang.RATED_X_BY_YOU_AND_Y_OTHERS != null) && (lang.RATED_X_BY_YOU_AND_Y_OTHERS.indexOf('{X.xx}') > -1) && (lang.RATED_X_BY_YOU_AND_Y_OTHERS.indexOf('{Y}') > -1))
{
this.RATED_X_BY_YOU_AND_Y_OTHERS = lang.RATED_X_BY_YOU_AND_Y_OTHERS;
} else if ((typeof(lang.RATED_X_BY_YOU_AND_Y_OTHERS) != 'undefined') && (lang.RATED_X_BY_YOU_AND_Y_OTHERS != null) && (lang.RATED_X_BY_YOU_AND_Y_OTHERS.indexOf('X.xx') > -1) && (lang.RATED_X_BY_YOU_AND_Y_OTHERS.indexOf(' Y ') > -1)){
// older
this.RATED_X_BY_YOU_AND_Y_OTHERS = lang.RATED_X_BY_YOU_AND_Y_OTHERS;
}
// rated x by you
if ((typeof(lang.RATED_X_BY_YOU) != 'undefined') && (lang.RATED_X_BY_YOU != null) && (lang.RATED_X_BY_YOU.indexOf('{X.xx}')))
{
this.RATED_X_BY_YOU = lang.RATED_X_BY_YOU;
} else if ((typeof(lang.RATED_X_BY_YOU) != 'undefined') && (lang.RATED_X_BY_YOU != null) && (lang.RATED_X_BY_YOU.indexOf('X.xx'))){
// older
this.RATED_X_BY_YOU = lang.RATED_X_BY_YOU;
}
// users like you
if ((typeof(lang.USERS_LIKE_YOU) != 'undefined') && (lang.USERS_LIKE_YOU != null))
{ this.USERS_LIKE_YOU = lang.USERS_LIKE_YOU; }
// rtl
if (typeof(lang.IS_RTL) == 'boolean'){
this.IS_RTL = lang.IS_RTL;
}
if (typeof(lang.OPTIONAL_ADDONS) != 'undefined'){
// show most popular widget per language?
if (typeof(lang.OPTIONAL_ADDONS.mostPopular) == 'boolean'){
this.OPTIONAL_ADDONS.mostPopular = lang.OPTIONAL_ADDONS.mostPopular;
}
// show recommendations per language?
if (typeof(lang.OPTIONAL_ADDONS.recommendations) == 'boolean'){
this.OPTIONAL_ADDONS.recommendations = lang.OPTIONAL_ADDONS.recommendations;
}
}
this.isInit = true;
}
};
var outbrain_language_manager_object = function(){
this.languages_list = [];
var language_manager_self = this;
//------------------------------------------------------------------------------------------------------------------------
// addLanguage
// template call for adding a new language file
this.addLanguage = function(name,file){
if (typeof(this.languages_list[name]) == 'object'){
return this.languages_list[name];
} else {
var jsDomain = outbrain_settings.domains.js;
var langJS = file;
var langId = outbrain_settings.language.id;
if (langJS.indexOf(jsDomain) > -1){
langJS = langJS.replace(/.js/g,"-"+ outbrain_settings.versions.language +".js");
}
var langScriptElement = document.createElement('script');
langScriptElement.setAttribute('id',langId + "_" + name);
langScriptElement.setAttribute('type',outbrain_settings.globals.scriptType);
langScriptElement.setAttribute('src', langJS);
var heads = document.getElementsByTagName("head");
if (heads.length > 0){
heads[0].appendChild(langScriptElement);
} else {
document.write('<script id="'+langId+'" src="'+langJS+'" type="'+outbrain_settings.globals.scriptType+'"></script>');
}
}
}
//------------------------------------------------------------------------------------------------------------------------
// initLang
// callback function from language file that init the current language
this.initLang = function(lang){
//this is patch that overrides the id of the lang so any lang gets the default LangName
//if (typeof(lang.id) == 'undefined'){
lang.id = outbrain_settings.language.defaultLangName;
//}
this.languages_list[lang.id] = new OB_lang_object();
this.languages_list[lang.id].initLang(lang);
}
//------------------------------------------------------------------------------------------------------------------------
// isLanguageReady
// returns true if language is ready, otherwise return false. language rady means exists and inited.
this.isLanguageReady = function(lang){
return this.isInit(lang);
}
//------------------------------------------------------------------------------------------------------------------------
// isInit
// returns true if language exists and inited, otherwise - false
this.isInit = function(lang){
return ((typeof(this.languages_list[lang]) != 'undefined') && (typeof(this.languages_list[lang].isInit) != 'undefined') && (this.languages_list[lang].isInit));
}
//------------------------------------------------------------------------------------------------------------------------
// name
// tells the (lang) name
this.getName = function(lang){
return (this.languages_list[lang].name);
}
//------------------------------------------------------------------------------------------------------------------------
// isRtl
// tells if (lang) is right-to-left
this.isRtl = function(lang){
return (this.languages_list[lang].IS_RTL);
}
//------------------------------------------------------------------------------------------------------------------------
// changeX
// change {X.xx} and "X.xx" (prev versions) to bolded rate number
this.changeX = function (str,num){
num = Math.round(num*100)/100;
var num_as_str = num + "";
num_as_str = (num_as_str.length==1) ? num_as_str+".0" : num_as_str;
num = num_as_str;
if (str == null){
return num;
} else {
var finalValue = '';
finalValue = str;
finalValue = finalValue.replace(/{X.xx}/g,'<span class="outbrain-bold" style="font-weight:bold;">' + num + '</span>');
finalValue = finalValue.replace(/X.xx/g,'<span class="outbrain-bold" style="font-weight:bold;">' + num + '</span>');
return finalValue;
}
}
//------------------------------------------------------------------------------------------------------------------------
// changeY
// change {Y} or " Y " (prev versions) to the count of people that rate the post
this.changeY = function (variable,variable2){
var finalValue = '';
finalValue = variable;
if (finalValue.indexOf("{Y}") > -1){
finalValue = finalValue.replace(/{Y}/g,variable2);
} else {
finalValue = finalValue.replace(/ Y /g,' ' + variable2 + ' ');
}
return finalValue;
}
//------------------------------------------------------------------------------------------------------------------------
// rateGetAverageStr
//
this.rateGetAverageStr = function (lang,average,countAll){
var str = '';
str = this.changeX(this.languages_list[lang].AVERAGE_RATING_X_BY_Y_PEOPLE,average);
str = this.changeY(str,countAll);
str = '(' + str + ')';
return str;
}
//------------------------------------------------------------------------------------------------------------------------
// rateGetLikeYou
//
this.rateGetLikeYou = function (msg,rank,countAll){
var str = '';
str = this.changeX(msg,rank);
str = this.changeY(str,' ' + countAll + ' ');
return str;
}
//------------------------------------------------------------------------------------------------------------------------
// rateGetAggregate
//
this.rateGetAggregate = function (lang,rank,countAll,withMe){
var str = '';
if (withMe){ // current user allready voted
if (countAll == 1){
// only current user voted
// use RATED_X_BY_YOU
str = this.changeX(this.languages_list[lang].RATED_X_BY_YOU,rank);
} else if (countAll == 2) {
// current user and one more
// use RATED_X_BY_YOU_AND_1_OTHER
str = this.changeX(this.languages_list[lang].RATED_X_BY_YOU_AND_1_OTHER,rank);
} else {
// use RATED_X_BY_YOU_AND_Y_OTHERS
countAll--; // no current user in this count
str = this.changeX(this.languages_list[lang].RATED_X_BY_YOU_AND_Y_OTHERS,rank);
str = this.changeY(str,countAll);
}
} else {
if (countAll == 1){
// use RATED_X_BY_1_PERSON
str = this.changeX(this.languages_list[lang].RATED_X_BY_1_PERSON,rank);
} else {
// use RATED_X_BY_Y_PEOPLE
str = this.changeX(this.languages_list[lang].RATED_X_BY_Y_PEOPLE,rank);
str = this.changeY(str,countAll);
}
}
return str;
}
//------------------------------------------------------------------------------------------------------------------------
// getRateDescription
// returns rate description (bad, boring, ext.) for lang (lang) and position num
this.getRateDescription = function(lang,num){
return (this.languages_list[lang].RATE_DESCRIPTION[num]);
}
//------------------------------------------------------------------------------------------------------------------------
// getPersonalRateDesc
//
this.getPersonalRateDesc = function(lang,num){
var str = '';
str = this.languages_list[lang].PERSONAL_RATE_DESC[num];
return str;
}
//------------------------------------------------------------------------------------------------------------------------
// getRatePostRate
// returns post rate description ("You hated this post"..."You loved" ext.) strings in language (lang) and position num
this.getRatePostRate = function(lang,num){
return this.languages_list[lang].RATE_POST_RATE[num];
}
//------------------------------------------------------------------------------------------------------------------------
// getRatePostRateForRecommendations
//
this.getRatePostRateForRecommendations = function (lang,rate){
var value;
value = this.languages_list[lang].RATE_POST_RATE_FOR_RECOMMENDATIONS[rate];
return value;
}
//------------------------------------------------------------------------------------------------------------------------
// getThanksString
// returns "thanks" string in language (lang)
this.getThanksString = function(lang){
return (this.languages_list[lang].THANKS_STR);
}
//------------------------------------------------------------------------------------------------------------------------
// getBeTheFirstString
// returns "be the first to rate" string in language (lang)
this.getBeTheFirstString = function(lang){
return (this.languages_list[lang].BE_THE_FIRST_STR);
}
//------------------------------------------------------------------------------------------------------------------------
// getUnableToSubmitString
//
this.getUnableToSubmitString = function(lang){
return (this.languages_list[lang].UNABLE_TO_SUBMIT_STR);
}
//------------------------------------------------------------------------------------------------------------------------
// getHowString
// returns "how" string in language (lang)
this.getHowString = function(lang){
return (this.languages_list[lang].HOW);
}
//------------------------------------------------------------------------------------------------------------------------
// getByString
// returns "by" string in language (lang)
this.getByString = function(lang){
return (this.languages_list[lang].BY);
}
//------------------------------------------------------------------------------------------------------------------------
// getThisSiteString
// returns the "this site" string from language (lang)
this.getThisSiteString = function(lang){
return (this.languages_list[lang].THIS_SITE);
}
//------------------------------------------------------------------------------------------------------------------------
// getThisSiteString
// returns the "this site" string from language (lang)
this.whatsThis = function(lang){
return (this.languages_list[lang].WHATS_THIS);
}
//------------------------------------------------------------------------------------------------------------------------
// getMoreRecommendedLinkText
//
this.getMoreRecommendedLinkText = function (lang,count){
var str = '';
str = this.languages_list[lang].MORE_RECOMMENDED_PLURAL + " »";
str = str.replace(/{N}/g,count);
return str;
}
//------------------------------------------------------------------------------------------------------------------------
// getMoreRecommendedCloseLinkTest
//
this.getMoreRecommendedCloseLinkTest = function (lang,count){
var str = '';
str = "« " +this.languages_list[lang].MORE_RECOMMENDED_CLOSE_PLURAL;
str = str.replace(/{N}/g,count);
return str;
}
//------------------------------------------------------------------------------------------------------------------------
// getThisSiteString
// returns the "this site" string from language (lang)
this.GetMostPopular = function(lang){
return (this.languages_list[lang].MOST_POPULAR);
}
//------------------------------------------------------------------------------------------------------------------------
// isMostPopularAvailable
//
this.isMostPopularAvailable = function(lang){
return (this.languages_list[lang].OPTIONAL_ADDONS.mostPopular);
}
//------------------------------------------------------------------------------------------------------------------------
// isRecommendationsAvailable
//
this.isRecommendationsAvailable = function(lang){
return (this.languages_list[lang].OPTIONAL_ADDONS.recommendations);
}
};
// backwards compatibility
var OB_lang = (typeof(OB_lang) == 'object')? OB_lang: new function(){
this.initLang = function(lang){
outbrain_language_manager.initLang(lang);
}
}
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain's language object - end
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain_template_object start
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
var outbrain_template_object = (typeof(outbrain_template_object) == "function")? outbrain_template_object : function(templateIndex,position,inside,elements,matrixInfoJson){
// this
var self = this;
this.templateIndex = templateIndex;
//------------------------------------------------------------------------------------------------------------------------
// boolean helpers
this.templateArrayInit = false;
this.templateDOMInit = false;
this.templateReplacedOnce = false;
this.templateHaveOdbAndLang = false;
this.languageName = outbrain_settings.language.defaultLangName;
//this.localThanksMode = false;
this.dom = new outbrain_dom_object();
//------------------------------------------------------------------------------------------------------------------------
// all optional template's elements
this.all_optional_elements = outbrain_settings.templateOptions;
// the elements the user selected
this.all_user_elements = [];
//------------------------------------------------------------------------------------------------------------------------
//instance of matrixInfo
this.matrixInfo = new outbrain_matrix_info();
if (matrixInfoJson != null && matrixInfoJson != 'undefined' ) this.matrixInfo.init(matrixInfoJson);
//------------------------------------------------------------------------------------------------------------------------
this.elements = outbrain_settings.templateItemsJoin + elements.split(outbrain_settings.templateItemsSplit).join(outbrain_settings.templateItemsJoin) + outbrain_settings.templateItemsJoin;
this.top = (position=='top');
this.position = (position == "top")? "top":"bottom";
this.inside = ((inside==true) || (inside=='true'));
// the DOM that created
this.templateDOM = null;
this.constants = null;
this.smallImageSufix = 'png';
this.rateYarray = new Array(0,this.matrixInfo.matrixYHeight,0);
this.lastRate = -1 ;
//------------------------------------------------------------------------------------------------------------------------
// local array positions
this.positionsStars = 0;
this.positionFirstLine = 1;
this.positionSecondLine = 2;
this.positionRec = 3;
this.matrixImage = null;
this.isMatrixReady = false;
// timer for smooth apperance
this.mouseOutTimer = null;
//------------------------------------------------------------------------------------------------------------------------
// getElementWithFullName
// returns an element
this.getElementWithFullName = function(ele,index){
return this.dom.$(ele+"_"+index+"_"+this.position)
}
//------------------------------------------------------------------------------------------------------------------------
this.fixPngOnThisBrowser = function(){
return ((outbrain_browsers.ie5) || (outbrain_browsers.ie55) || (outbrain_browsers.ie6));
}
//------------------------------------------------------------------------------------------------------------------------
// isSomeSecondLine
// returns true if there is secondLine or recommendations, otherwise - false
this.isSomeSecondLine = function(){
return ((this.all_user_elements[this.positionSecondLine]) || (this.all_user_elements[this.positionRec]));
}
//------------------------------------------------------------------------------------------------------------------------
// getStarXPosition
// returns matrix x position
this.getStarXPosition = function(itemData){
var tempRank = itemData.rankInfo.vote!=0 ? itemData.rankInfo.getComputedRank(true) : itemData.rankInfo.getComputedRank();
var x = (Math.round(tempRank*2)-1)*this.matrixInfo.matrixXlength;
return x > 0 ? x : 0;
}
//------------------------------------------------------------------------------------------------------------------------
// fixPng
//
this.fixPng = function(index,x,y){
var element = this.getElementWithFullName(this.constants.ratesDivId,index);
if (element){
var filterString = 'DXImageTransform.Microsoft.AlphaImageLoader';
if ((outbrain_language_manager.isLanguageReady(self.languageName)) && (outbrain_language_manager.isRtl(self.languageName))){
var bgSrc = self.matrixInfo.matrixSourceRTL;
} else {
var bgSrc = self.matrixInfo.matrixSource;
}
element.style.left = x + "px";
element.style.top = y + "px";
element.style.filter = 'progid:' + filterString + '(src="' + bgSrc + '",sizingMethod="crop")';
}
}
//------------------------------------------------------------------------------------------------------------------------
this.changeMatrixByXY = function(index,x,y){
var rates = this.getElementWithFullName(this.constants.ratesDivId,index);
var returnValue = false;
if (rates){
if (this.fixPngOnThisBrowser()){
returnValue = this.fixPng(index,(x*(-1)),(y*(-1)));
} else {
if (outbrain_browsers.ie){
rates.style.backgroundPosition = "-"+x+"px -"+y+"px";
} else {
rates.style.backgroundPosition = (x == 0 ? "left " : "-"+x+"px ") + (y == 0 ? "top" : "-"+y+"px");
}
returnValue = true;
}
}
return returnValue;
}
//------------------------------------------------------------------------------------------------------------------------
// changeMatrix
// change the background image position and call other changing methods
this.changeMatrix = function(index,itemData,rateMode){
if (itemData.rankInfo == null){
return false;
}
if (outbrain_rater.lockRater(index)){
return false;
}
var localRateMode = (rateMode != null)? rateMode : itemData.rateMode;
var x=0;
switch(localRateMode){
case outbrain_settings.rater.statuses.RATER_RATE_MODE:
x = (itemData.currentRateValue-1)*this.matrixInfo.matrixXlength;
break;
case outbrain_settings.rater.statuses.RATER_PRE_RATE_MODE:
x = this.getStarXPosition(itemData);
break;
case outbrain_settings.rater.statuses.RATER_POST_RATE_MODE:
x = this.getStarXPosition(itemData);
break;
}
if ( x < 0 ){
return;
}
var y = this.rateYarray[localRateMode];
this.changeMatrixByXY(index,x,y);
}
//------------------------------------------------------------------------------------------------------------------------
// toggleMoreRecommendations
// toggle more recommendations display
this.toggleMoreRecommendations = function(index){
var LinkElement = this.getElementWithFullName(this.constants.recommendationsMoreDivId,index).getElementsByTagName("a")[0];
var ulElement = this.getElementWithFullName(this.constants.recommendationsUlId,index);
var Lis = ulElement.getElementsByTagName("li");
if ((typeof(ulElement.opened) == 'boolean') && (ulElement.opened)){
// hide the TR's from 2nd to end.
for (var i=1;i<Lis.length;i++){ // 1 is the second element.
Lis[i].style.display = "none";
}
ulElement.opened = false;
self.dom.setInnerHTML( LinkElement , outbrain_language_manager.getMoreRecommendedLinkText(self.languageName,Lis.length-1) );
} else {
LinkElement.onclick = function(){self.toggleMoreRecommendations(index);};
// display TR's
for (i=1;i<Lis.length;i++){ // 1 is the second element.
Lis[i].style.display = "";
}
ulElement.opened = true;
self.dom.setInnerHTML( LinkElement , outbrain_language_manager.getMoreRecommendedCloseLinkTest(self.languageName,Lis.length-1) );
}
}
//------------------------------------------------------------------------------------------------------------------------
// getMyRatingImage
// return the image tag of the second line (or first line if there is no second)
this.getMyRatingImage = function(rate,brackets){
if ((rate == 0) || (rate == null)){
return '';
}
var dirStr = '';
if ((typeof(outbrain_language_manager) != 'undefined') && (typeof(outbrain_language_manager.languages_list[self.languageName]) != 'undefined') && (outbrain_language_manager.isLanguageReady(self.languageName)) && (outbrain_language_manager.isRtl(self.languageName))){
dirStr = '_rtl';
} else {
dirStr = '';
}
var src = outbrain_settings.domains.js+'my_rating_'+rate+dirStr+'.'+this.smallImageSufix;
var filterString = 'DXImageTransform.Microsoft.AlphaImageLoader';
var valign = (outbrain_browsers.mozilla)? "sub":"middle";
if (this.fixPngOnThisBrowser()){
img = '<img src="http://widgets.outbrain.com/blank.gif" style="width:60px;height:12px;border:none;float:none;margin:0 0 0 0;padding:0 0 0 0;background:none;display:inline;vertical-align:'+valign+';filter:progid:'+ filterString + '(src=\''+src+'\', sizingMethod=\'scale\');" />';
} else {
img = '<img style="border:none;float:none;margin:0 0 0 0;padding:0 0 0 0;background:none;display:inline;vertical-align:'+valign+';" src="'+src+'" />';
}
return img;
}
//------------------------------------------------------------------------------------------------------------------------
// changeStarsTextToImage
//
this.changeStarsTextToImage = function(title,rate,brackets){
if (typeof(title) != 'string'){
return false;
}
if (rate == null){
title = title.replace("({starsImage})", "");
} else {
title = title.replace("{starsImage}", this.getMyRatingImage(rate,brackets));
}
return title;
}
//------------------------------------------------------------------------------------------------------------------------
// showMoreRecommendations
// render & diplay more recommendations
this.showMoreRecommendations = function(index){
var itemData = outbrain_template_manager.getDataPerPost(this.templateIndex,index);
var jsonObj = itemData.jsonObj;
var title = itemData.recTitle;
var rateMode = itemData.rateMode;
var recommendedUl = this.getElementWithFullName(this.constants.recommendationsUlId,index);
for (var idx = 1;idx < jsonObj.response.documents.doc.length;++idx){ // without first element ([0] position)
this.renderOneRecommendation( index , recommendedUl , jsonObj.response.documents.doc[idx] );
}
recommendedUl.opened = false;
this.toggleMoreRecommendations(index);
}
//------------------------------------------------------------------------------------------------------------------------
// renderOneRecommendation
// display one recommendations per call
this.renderOneRecommendation = function(index,recommendedUl,docRecommendation){
var recommendedLi = document.createElement("li");
var currentRecommendationData = outbrain_template_manager.getRecommendationDataPerDoc(this.templateIndex,index,docRecommendation);
var postLink = currentRecommendationData[0];
var linkText = currentRecommendationData[1];
var sourceName = currentRecommendationData[2];
var authorName = currentRecommendationData[3];
var pubDate = currentRecommendationData[4];
var isSameSource = currentRecommendationData[5];
var target = 'target="_blank"';
if ((postLink == null) || (linkText == null) || (sourceName == null) || (authorName == null) || (isSameSource == null)){
return false;
}
if (recommendedUl){
if (isSameSource){
sourceName = '<span style="font-weight:bold;">' + outbrain_language_manager.getThisSiteString(self.languageName) + '</span>';
target = 'target="_self"';
}
var content = ''+
'<a class="rec-link" '+target+' href="'+ postLink +'">' +
linkText +
'</a>' +
'<span class="rec-src-link"> (@'+ sourceName +')</span>';
recommendedLi.innerHTML = content;
recommendedUl.appendChild(recommendedLi);
} else {
return false;
}
}
//------------------------------------------------------------------------------------------------------------------------
// recommendationsLegendUpdate
// update the recommendations legend tag
this.recommendationsLegendUpdate = function(index,title){
var fieldsetElement = this.getElementWithFullName(this.constants.fieldsetId,index);
if (!fieldsetElement){ // current template don't support recommendations
} else {
var legendElement = fieldsetElement.getElementsByTagName("legend")[0];
if ((legendElement) && (legendElement.innerHTML != title)){
self.dom.setInnerHTML( legendElement , title );
}
}
}
//------------------------------------------------------------------------------------------------------------------------
// recommendationsShowBefore
//
this.recommendationsShowBefore = function(index){
var value = false;
var element = this.getElementWithFullName(this.constants.fieldsetId,index);
if (!element){ // current template do not support recommendations
value = false;
} else {
value = (this.getElementWithFullName(this.constants.fieldsetId,index).style.display != "none");
}
return value;
}
//------------------------------------------------------------------------------------------------------------------------
// show recommendations
//
this.showRecommendations = function(index,itemData,rateMode){
var rate = itemData.rankInfo.vote;
var title = itemData.recTitle;
var jsonObj = itemData.jsonObj;
title = this.changeStarsTextToImage(title,rate,true);
if (!this.all_user_elements[this.positionRec]){ // no recommendations in the template
return false;
}
var currElement = null;
if (!this.recommendationsShowBefore(index)){
var recommendationsUL = this.getElementWithFullName(this.constants.recommendationsUlId,index)
this.recommendationsLegendUpdate(index,title);
if( typeof(jsonObj.response.documents.doc.length) == 'undefined' ){
// one recommendation
this.renderOneRecommendation( index , recommendationsUL , jsonObj.response.documents.doc);
} else if ( jsonObj.response.documents.doc.length == 1 ){
// one recommendation
this.renderOneRecommendation( index , recommendationsUL , jsonObj.response.documents.doc[0]);
} else {
this.renderOneRecommendation( index , recommendationsUL , jsonObj.response.documents.doc[0]);
var moreCount = (jsonObj.response.documents.doc.length-1);
var moreText = outbrain_language_manager.getMoreRecommendedLinkText(self.languageName,moreCount);
currElement = this.getElementWithFullName(this.constants.recommendationsMoreDivId,index);
if (currElement){
self.dom.setInnerHTML( currElement , "<a href='javascript:void(0);' onclick='outbrain_template_manager.templates["+this.templateIndex+"].showMoreRecommendations("+index+");'> " + moreText + "</a>" );
currElement.style.display = "block";
}
}
currElement = this.getElementWithFullName(this.constants.rateStatusInfoTableId,index);
if (currElement){
currElement.style.display = "none";
}
currElement = this.getElementWithFullName(this.constants.rateStatusInfoTdId,index);
if (currElement){
currElement.style.display = "none";
}
currElement = this.getElementWithFullName(this.constants.fieldsetId,index);
if (currElement){
currElement.style.display = "block";
}
currElement = this.getElementWithFullName(this.constants.recommendationsMoreDivId,index);
if (currElement){
currElement.style.display = "block";
}
} else {
this.recommendationsLegendUpdate(index,title);
}
}
//------------------------------------------------------------------------------------------------------------------------
// changeRateInfoSingleLine
//
this.changeRateInfoSingleLine = function(data,rate,rateMode){
if ((rate > 0) && ((rateMode==outbrain_settings.rater.statuses.RATER_PRE_RATE_MODE) || (rateMode==outbrain_settings.rater.statuses.RATER_POST_RATE_MODE))){
var extraWord = '';
if (rate==1){
extraWord = "hated";
} else if (rate==2){
extraWord = "didn't like";
} else if (rate==3){
extraWord = "rated";
} else if (rate==4){
extraWord = "liked";
} else if (rate==5){
extraWord = "loved";
}
data += ' (you ' + extraWord + ' this ' + this.getMyRatingImage(rate,false) + ')';
}
return data;
}
//------------------------------------------------------------------------------------------------------------------------
//
//
this.firstLineTextReplacer = function(itemData,rateMode){
var rateInfo = itemData.rateInfo;
var rate = itemData.rankInfo.vote;
if (typeof(rateMode) != 'number'){
rateMode = itemData.rateMode;
}
if (!this.isSomeSecondLine()){
rateInfo = rateInfo.replace(/RECOMMENDED/g,'<span class="outbrain-bold">RECOMMENDED</span>');
var signIndex = rateInfo.indexOf("[");
if (signIndex > -1){
// will be replace with regexp one day
var endSignIndex = rateInfo.indexOf("]",signIndex);
rateInfo = rateInfo.substr(0,signIndex-1) + rateInfo.substr(endSignIndex+1,rateInfo.length);
}
rateInfo = this.changeRateInfoSingleLine(rateInfo,rate,rateMode);
}
return rateInfo;
}
//------------------------------------------------------------------------------------------------------------------------
//
//
this.setFirstLineInnerHTML = function(index,text){
var rateInfoDiv = this.getElementWithFullName(this.constants.rateInfoDivId,index);
if (rateInfoDiv){
self.dom.setInnerHTML( rateInfoDiv , text );
return true;
}
return false;
}
//------------------------------------------------------------------------------------------------------------------------
// updateRateInfo
// update the 2 regular lines
this.updateRateInfo = function(index,itemData,rateMode,isHover){
var rateInfo = itemData.rateInfo;
var rateStatus = "";
if (! outbrain_rater.lockRater(index)){
if (itemData.rankInfo == null){
rateStatus = this.changeStarsTextToImage(itemData.rateStatus,null);
} else {
rateStatus = this.changeStarsTextToImage(itemData.rateStatus,itemData.rankInfo.vote);
}
var recommendationsTitle = itemData.recTitle;
itemData.rateInfo = rateInfo;
rateInfo = this.firstLineTextReplacer(itemData,rateMode);
var changedText = this.setFirstLineInnerHTML(index,rateInfo); // this variable is only status handler
if (isHover != true ){//if hovering on starts - avoid change bottom text IE improvment
var voterDiv = this.getElementWithFullName(this.constants.voterDivName,index);
if (voterDiv){
voterDiv.style.display = "block";
}
if (this.recommendationsShowBefore(index)){
this.showRecommendations(index,itemData,rateMode);
} else {
if (this.all_user_elements[this.positionSecondLine]){ // no one line
var singleSecondLine = this.getElementWithFullName(this.constants.rateStatusInfoTdId,index);
var updateLine = false;
if (!singleSecondLine){ // current template don't support second single line
} else {
if (outbrain_rater.lastOdbRotationReturnedItem < index){
updateLine = true;
} else if (this.all_user_elements[this.positionRec]){
if (OB_voterWidgetObjArray[index].vote >= 3){
if ((typeof(OB_voterWidgetObjArray[index].jsonObj.response.documents) != 'undefined') && (typeof(OB_voterWidgetObjArray[index].jsonObj.response.documents.total_count) != 'undefined') && ((OB_voterWidgetObjArray[index].jsonObj.response.documents.total_count) > 0)){
updateLine = false;
} else {
updateLine = true;
}
} else {
updateLine = true;
}
} else {
updateLine = true;
}
}
if (updateLine){
self.dom.setInnerHTML( singleSecondLine , rateStatus );
}
}
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------
// changeView
// change the widget view
this.changeView = function(index,itemData,rateMode){
return this.changeMatrix(index,itemData,rateMode);
}
//------------------------------------------------------------------------------------------------------------------------
this.thanksMode = function(index,vote){
var itemData = outbrain_template_manager.getDataPerPost(templateIndex,index);
itemData.frezz = true;
var rateInfo = "<strong>" + outbrain_language_manager.getThanksString(self.languageName) + "</strong>";
itemData.rateInfo = rateInfo;
rateInfo = this.firstLineTextReplacer(itemData);
var changedText = this.setFirstLineInnerHTML(index,rateInfo); // this variable is only status handler
this.changeMatrixByXY(index,((vote-1)*this.matrixInfo.matrixXlength),this.matrixInfo.matrixYpositionThanks);
}
//------------------------------------------------------------------------------------------------------------------------
// endThanksMode
// when thanks mode ends
this.endThanksMode = function(index){
outbrain_template_manager.setStatus(this.templateIndex,index,outbrain_settings.rater.statuses.RATER_POST_RATE_MODE);
}
//------------------------------------------------------------------------------------------------------------------------
// mouseClicked
// when mouse clocked
this.mouseClicked = function(spanObj,index){
// do rate
outbrain_template_manager.setStatus(this.templateIndex,index,outbrain_settings.rater.statuses.RATER_RATE_MODE,spanObj.getAttribute("_vote"));
this.thanksMode(index,spanObj.getAttribute("_vote"));
// post-rate status
setTimeout(function(){self.endThanksMode(index)},1000);
}
//------------------------------------------------------------------------------------------------------------------------
// mouseOverSpan
// matrix span over
this.mouseOverSpan = function(templateIndex,spanObj,index){
var status = outbrain_settings.rater.statuses.RATER_RATE_MODE;
OB_voterWidgetObjArray[index].currentRateValue = spanObj.getAttribute("_vote");
var itemData = outbrain_template_manager.getDataPerPost(templateIndex,index,status);
clearTimeout(this.mouseOutTimer);
this.changeView(index,itemData,status);
this.updateRateInfo(index,itemData,status,true);
}
//------------------------------------------------------------------------------------------------------------------------
// mouseOutSpan
// matrix span out
this.mouseOutSpan = function(templateIndex,index){
// change matrix position, change text
var status = outbrain_settings.rater.statuses.RATER_PRE_RATE_MODE;
OB_voterWidgetObjArray[index].currentRateValue = 0;
var itemData = outbrain_template_manager.getDataPerPost(templateIndex,index,status);
this.mouseOutTimer =
setTimeout( function(){
self.changeView(index,itemData,status);
self.updateRateInfo(index,itemData,status,true);}
,10);
}
//------------------------------------------------------------------------------------------------------------------------
// imagesLoadEvent
//
this.imageLoadEvent = function(){
this.isMatrixReady = true;
}
//------------------------------------------------------------------------------------------------------------------------
// imagesPreload
// pre - load some images
this.imagesPreload = function(){
new outbrain_timeout(
function(){
return ((typeof(outbrain_language_manager[self.languageName]) != 'object') && (outbrain_language_manager.isLanguageReady(self.languageName)));
},
function(){
if (document.images){
var OB_starsImages = [];
this.matrixImage = new Image();
this.matrixImage.onLoad = self.imageLoadEvent();
this.matrixImage.src = ( outbrain_language_manager.isRtl(self.languageName) == true ? self.matrixInfo.matrixSourceRtl : self.matrixInfo.matrixSource) ;
for (i=0;i<5;i++ ){
OB_starsImages[i] = new Image(60,12);
OB_starsImages[i].src = outbrain_settings.domains.js+'my_rating_'+(i+1)+"."+self.smallImageSufix;
}
}
},
null,
null,
500,
1000,
true
);
}
//------------------------------------------------------------------------------------------------------------------------
// initTemplate
// init the template
this.initTemplate = function(){
for (i=0;i<this.all_optional_elements.length;i++){
if (this.elements.indexOf(outbrain_settings.templateItemsJoin+this.all_optional_elements[i]+outbrain_settings.templateItemsJoin) > -1){
this.all_user_elements[i] = true;
} else {
this.all_user_elements[i] = false;
}
}
// no first line and second line without stars
if (!this.all_user_elements[this.positionsStars]){ // stars
this.all_user_elements[this.positionFirstLine] = false; // first line
this.all_user_elements[this.positionSecondLine] = false // second line
}
this.templateArrayInit = true;
}
this.supportRecommendations = function(){
return this.all_user_elements[this.positionRec];
}
//------------------------------------------------------------------------------------------------------------------------
// buildDOMOnce
// each item's DOM
this.buildDOMOnce = function(){
if (this.templateDOMInit){
return this.templateDOM;
}
if (!this.templateArrayInit){
setTimeout(self.buildDOMOnce,1000);
return;
}
this.templateDOM = '';
this.templateDOM += '' +
'<div id="$CONTAINER_DIV_ID_$INDEX_$POSITION" class="$GLOBAL_CLASS" style="$DIV_WRAPPER_STYLE" >' +
'$upperBR' +
'<div class="$VOTER_DIV_CLASS" style="display:none;" id="$VOTER_DIV_NAME_$INDEX_$POSITION" >' ;
if (this.all_user_elements[this.positionsStars]){
this.templateDOM += '' +
'<table class="table-css" cellpadding="0" cellspacing="0" border="0" style="$TABLE_STYLEwidth:100%;">' +
'<tbody style="border:none;width:100%;" class="$TBODY_CLASS">' +
'<tr style="$TABLE_STYLEwidth:100%;vertical-align:middle;">' +
'<td style="$TD_STYLE$WIDTH_STARS_TD;vertical-align:middle;">' +
'';
if (self.fixPngOnThisBrowser()){
this.templateDOM += '<div id="$PNGFIX_HELPER_DIV_ID_$INDEX_$POSITION" style="overflow:hidden;position:relative;height:$STARS_Y_HEIGHTpx;width:$MATRIX_ONE_ITEM_LENGTHpx;margin-bottom:0px;">' +
'<div id="$PNGFIX_DIVS_CONTAINER_$INDEX_$POSITION" style="width:100%;height:100%;">' +
'<div class="$PNGFIX_STARS_DIV_CLASS" style="$PNGFIX_DIV_STYLE" _vote="1" onmouseout="outbrain_template_manager.templates['+this.templateIndex+'].mouseOutSpan('+this.templateIndex+',$INDEX);" onclick="outbrain_template_manager.templates['+this.templateIndex+'].mouseClicked(this,$INDEX);" onmouseover="outbrain_template_manager.templates['+this.templateIndex+'].mouseOverSpan('+this.templateIndex+',this,$INDEX);"> </div>'+
'<div class="$PNGFIX_STARS_DIV_CLASS" style="$PNGFIX_DIV_STYLE" _vote="2" onmouseout="outbrain_template_manager.templates['+this.templateIndex+'].mouseOutSpan('+this.templateIndex+',$INDEX);" onclick="outbrain_template_manager.templates['+this.templateIndex+'].mouseClicked(this,$INDEX);" onmouseover="outbrain_template_manager.templates['+this.templateIndex+'].mouseOverSpan('+this.templateIndex+',this,$INDEX);"> </div>'+
'<div class="$PNGFIX_STARS_DIV_CLASS" style="$PNGFIX_DIV_STYLE" _vote="3" onmouseout="outbrain_template_manager.templates['+this.templateIndex+'].mouseOutSpan('+this.templateIndex+',$INDEX);" onclick="outbrain_template_manager.templates['+this.templateIndex+'].mouseClicked(this,$INDEX);" onmouseover="outbrain_template_manager.templates['+this.templateIndex+'].mouseOverSpan('+this.templateIndex+',this,$INDEX);"> </div>'+
'<div class="$PNGFIX_STARS_DIV_CLASS" style="$PNGFIX_DIV_STYLE" _vote="4" onmouseout="outbrain_template_manager.templates['+this.templateIndex+'].mouseOutSpan('+this.templateIndex+',$INDEX);" onclick="outbrain_template_manager.templates['+this.templateIndex+'].mouseClicked(this,$INDEX);" onmouseover="outbrain_template_manager.templates['+this.templateIndex+'].mouseOverSpan('+this.templateIndex+',this,$INDEX);"> </div>'+
'<div class="$PNGFIX_STARS_DIV_CLASS" style="$PNGFIX_DIV_STYLE" _vote="5" onmouseout="outbrain_template_manager.templates['+this.templateIndex+'].mouseOutSpan('+this.templateIndex+',$INDEX);" onclick="outbrain_template_manager.templates['+this.templateIndex+'].mouseClicked(this,$INDEX);" onmouseover="outbrain_template_manager.templates['+this.templateIndex+'].mouseOverSpan('+this.templateIndex+',this,$INDEX);"> </div>'+
'</div>' +
'<div id="$RATES_DIV_ID_$INDEX_$POSITION" class="$STARS_CLASS" style="width:$MATRIX_All_WIDTHpx;height:$MATRIX_ALL_HEIGHTpx;position:absolute;z-index:-1;vertical-align:absmiddle;">'+
'</div>' +
'</div>';
} else {
this.templateDOM += '<div id="$RATES_DIV_ID_$INDEX_$POSITION" class="$STARS_CLASS" style="margin:0 0 0 0;padding:0 0 0 0;vertical-align:absmiddle;height:$STARS_Y_HEIGHTpx;width:$MATRIX_ONE_ITEM_LENGTHpx;$SOURCE_URL">'+
'<div class="$STARS_SPAN_CLASS" style="$PNGFIX_DIV_STYLE" _vote="1" onmouseout="outbrain_template_manager.templates['+this.templateIndex+'].mouseOutSpan('+this.templateIndex+',$INDEX);" onclick="outbrain_template_manager.templates['+this.templateIndex+'].mouseClicked(this,$INDEX);" onmouseover="outbrain_template_manager.templates['+this.templateIndex+'].mouseOverSpan('+this.templateIndex+',this,$INDEX);"> </div>'+
'<div class="$STARS_SPAN_CLASS" style="$PNGFIX_DIV_STYLE" _vote="2" onmouseout="outbrain_template_manager.templates['+this.templateIndex+'].mouseOutSpan('+this.templateIndex+',$INDEX);" onclick="outbrain_template_manager.templates['+this.templateIndex+'].mouseClicked(this,$INDEX);" onmouseover="outbrain_template_manager.templates['+this.templateIndex+'].mouseOverSpan('+this.templateIndex+',this,$INDEX);"> </div>'+
'<div class="$STARS_SPAN_CLASS" style="$PNGFIX_DIV_STYLE" _vote="3" onmouseout="outbrain_template_manager.templates['+this.templateIndex+'].mouseOutSpan('+this.templateIndex+',$INDEX);" onclick="outbrain_template_manager.templates['+this.templateIndex+'].mouseClicked(this,$INDEX);" onmouseover="outbrain_template_manager.templates['+this.templateIndex+'].mouseOverSpan('+this.templateIndex+',this,$INDEX);"> </div>'+
'<div class="$STARS_SPAN_CLASS" style="$PNGFIX_DIV_STYLE" _vote="4" onmouseout="outbrain_template_manager.templates['+this.templateIndex+'].mouseOutSpan('+this.templateIndex+',$INDEX);" onclick="outbrain_template_manager.templates['+this.templateIndex+'].mouseClicked(this,$INDEX);" onmouseover="outbrain_template_manager.templates['+this.templateIndex+'].mouseOverSpan('+this.templateIndex+',this,$INDEX);"> </div>'+
'<div class="$STARS_SPAN_CLASS" style="$PNGFIX_DIV_STYLE" _vote="5" onmouseout="outbrain_template_manager.templates['+this.templateIndex+'].mouseOutSpan('+this.templateIndex+',$INDEX);" onclick="outbrain_template_manager.templates['+this.templateIndex+'].mouseClicked(this,$INDEX);" onmouseover="outbrain_template_manager.templates['+this.templateIndex+'].mouseOverSpan('+this.templateIndex+',this,$INDEX);"> </div>'+
'</div>' +
'';
}
'</td>' ;
}
// workaround for IE 6 behavier
var heightFix = '';
if ( ! this.all_user_elements[this.positionSecondLine] && outbrain_browsers.ie6){//single line dont need the height - small stars
heightFix = '';//do nothing for IE in case of single line
}else{
heightFix = '';
//height:$STARS_Y_HEIGHTpx;line-height:$STARS_Y_HEIGHTpx;';
}
if (this.all_user_elements[this.positionFirstLine]){
this.templateDOM += '' +
'<td class="$RATE_INFO_TD_CLASS" style="$TABLE_STYLEwidth:auto;vertical-align:middle;">' +
'<div id="$RATE_INFO_DIV_ID_$INDEX_$POSITION" style="$TABLE_STYLE' + heightFix +'vertical-align:absmiddle;">'+
'</div>' +
'</td>' ;
}
if (this.all_user_elements[this.positionsStars]){
this.templateDOM += '' +
'</tr>' +
'</tbody>' +
'</table>' ;
}
if (this.all_user_elements[this.positionSecondLine]){
this.templateDOM += '' +
'<table id="$RATE_STATUS_INFO_TABLE_ID_$INDEX_$POSITION" class="table-css" cellspacing="0" cellpadding="0" border="0" style="$TABLE_STYLEwidth:100%;">'+
'<tbody class="$TBODY_CLASS" style="$TABLE_STYLEwidth:100%;">' +
'<tr style="$TABLE_STYLEwidth:auto;">'+
'<td id="$RATE_STATUS_INFO_TD_ID_$INDEX_$POSITION" style="$TABLE_STYLEwidth:100%;" class="outbrain_my_rating"> </td>'+
'</tr>' +
'</tbody>' +
'</table>' ;
}
if (this.all_user_elements[this.positionRec]){
this.templateDOM += '' +
'<fieldset style="display:none;" id="$FIELDSET_ID_$INDEX_$POSITION" class="$FIELDSET_CLASS">' +
'<legend></legend>' +
'<ul id="$RECOMMENDATIONS_UL_ID_$INDEX_$POSITION" class="$RECOMMENDATIONS_UL_CLASS">' +
'</ul>' +
'</fieldset>' +
'<div id="$RECOMMENDATIONS_MORE_DIV_ID_$INDEX_$POSITION" class="$RECOMMENDATIONS_MORE_LINK_DIV_CLASS" style="display:none;"></div>';
}
this.templateDOM += '' +
'</div>' +
'$lowerBR' +
'</div> ' +
'' ;
this.templateDOMInit = true;
}
//------------------------------------------------------------------------------------------------------------------------
// constants
// template's constants variables
this.constants = new function(){
var constants_self = this;
//------------------------------------------------------------------------------------------------------------------------
//
this.init = function(){
// others
constants_self.upperBR = (typeof(OB_extraBR)!='undefined' || typeof(OB_extraBRType)!='undefined' && (OB_extraBRType==1 || OB_extraBRType==2) ) ? "<br />" : "";
constants_self.lowerBR = (typeof(OB_extraBRType)!='undefined' &&( OB_extraBRType==2 || OB_extraBRType==3)) ? "<br />" : "";
// styles
constants_self.divWrapperStyle = constants_self.divWrapperStyle.replace(/\$CLEAR_STR/g,((typeof(OB_userClear) == 'boolean')? ((OB_userClear)? '':'clear:both;'):'clear:both;'));
if (self.fixPngOnThisBrowser()){
//constants_self.divWrapperStyle = constants_self.divWrapperStyle.replace(/\$COLOR_STR/g,"color:#000;");
constants_self.divWrapperStyle = constants_self.divWrapperStyle.replace(/\$COLOR_STR/g,"");
if (self.isSomeSecondLine()){
//constants_self.divWrapperStyle = constants_self.divWrapperStyle.replace(/\$ONE_LINE/g,"height:100%;background:#FFF;");
constants_self.divWrapperStyle = constants_self.divWrapperStyle.replace(/\$ONE_LINE/g,"height:100%;");
} else {
constants_self.divWrapperStyle = constants_self.divWrapperStyle.replace(/\$ONE_LINE/g,"");
}
} else {
constants_self.divWrapperStyle = constants_self.divWrapperStyle.replace(/\$COLOR_STR/g,"");
constants_self.divWrapperStyle = constants_self.divWrapperStyle.replace(/\$ONE_LINE/g,"");
}
//change Backgroung url to matrix Info url acording to RTL
var backGroundUrl = "background: url(";
if ((outbrain_language_manager.isLanguageReady(self.languageName)) && (outbrain_language_manager.isRtl(self.languageName))){
backGroundUrl += self.matrixInfo.matrixSourceRTL;
} else {
backGroundUrl += self.matrixInfo.matrixSource;
}
backGroundUrl += ");";
constants_self.matrixUrl = backGroundUrl;
// classes
constants_self.recommendationsUlClass = "recommendations_ul" + ((outbrain_browsers.ie)?"_ie":"");
constants_self.starsClassname = (self.fixPngOnThisBrowser())? "ratesIE6" : "rates";
if (!self.isSomeSecondLine()){
constants_self.globalClass = constants_self.globalClass.replace(/\$ONE_LINE/g," outbrain_frame_page");
constants_self.starsClassname = constants_self.starsClassname.replace(/\$ONE_LINE/g," rates_frame_page");
} else {
constants_self.globalClass = constants_self.globalClass.replace(/\$ONE_LINE/g,"");
constants_self.starsClassname = constants_self.starsClassname.replace(/\$ONE_LINE/g,"");
}
var floatValue = "float:";
if ((outbrain_language_manager.isLanguageReady(self.languageName)) && (outbrain_language_manager.isRtl(self.languageName))){
floatValue += "right";
} else {
floatValue += "left";
}
floatValue += ";";
var pngfixDivsSt = "position:static;" + floatValue + "padding:0 0 0 0;margin:0 0 0 0;border:none;border-spacing:0px;font-size:normal;background: none;cursor: pointer;cursor: hand;width:"+ self.matrixInfo.starWidth +"px;height:"+ self.matrixInfo.matrixYHeight +"px;line-height:"+self.matrixInfo.matrixYHeight+"px;";
constants_self.pngfixDivsStyle = pngfixDivsSt;
}
//definitions
this.starsTextDistance = 4;
// styles
this.divWrapperStyle = "$CLEAR_STR";
this.divWrapperStyle += "padding:0 0 0 0;";
this.tableStyle = 'padding:0 0 0 0;margin:0 0 0 0;border:none;background:none;border-spacing:0px;';
this.divWrapperStyle += "$COLOR_STR";
this.divWrapperStyle += "$ONE_LINE";
this.tableStyle = "padding:0 0 0 0;margin:0 0 0 0;border:none;background:none;border-spacing:0px;";
this.tdStyle = "padding:"+ self.matrixInfo.shadowYoffset +"px 0 0 0;margin:0 0 0 0;border:none;background:none;border-spacing:0px;";
this.starDivStyle = "height:"+self.matrixInfo.starHeight+"px;width:"+ self.matrixInfo.starWidth +"px;";
this.widthStarsTd = "width:"+ (parseInt(self.matrixInfo.matrixXlength) + parseInt(this.starsTextDistance))+"px;";
// classes
this.starsClassname = "";
this.fieldsetClass = (outbrain_browsers.ie)?"outbrain-recommendationsFieldset-ie":"outbrain-recommendationsFieldset";
this.globalClass = "div-wrapper";
this.voterDivClass = "voterDiv";
this.tbodyClass = "outbrain-tbody-css";
this.rateInfoTdClass = "rateInfo";
this.recommendationsUlClass = "";
this.recommendationsMoreLinkId = "moreRecommendationsLinkDiv";
this.starsSpanClass = "star-span";
this.globalClass += "$ONE_LINE";
this.starsClassname += "$ONE_LINE";
// others
this.upperBR = "";
this.lowerBR = "";
// ids
this.voterDivName = "OutbrainVoterDiv";
this.containerId = "outbrain_container";
this.ratesDivId = "rates";
this.fieldsetId = "recommendationsFieldset";
this.recommendationsUlId = "recommendationsList";
this.recommendationsMoreDivId = "recommendationsMoreDiv";
this.rateStatusInfoTableId = "rateStatusInfoTable";
this.rateStatusInfoTdId = "rateStatusInfo";
this.rateInfoDivId = "rateInfo";
// png fix ids/classes
this.pngfixRatesHelper = "pngfixRatesMatrixHelper";
this.pngfixMatrix = "pngfixMatrix";
this.pngfixStarsDivClass = "pngfixStarsDivs";
this.pngfixDivsContainer = "pngfixDivs";
}
//------------------------------------------------------------------------------------------------------------------------
// replacerOnce
// one-time-replace for constants
this.replacerOnce = function(){
//DOM in this.templateDOM
this.templateDOM = this.templateDOM.replace(/\$POSITION/g ,this.position);
this.templateDOM = this.templateDOM.replace(/\$DIV_WRAPPER_STYLE/g ,this.constants.divWrapperStyle);
this.templateDOM = this.templateDOM.replace(/\$TABLE_STYLE/g ,this.constants.tableStyle);
this.templateDOM = this.templateDOM.replace(/\$TD_STYLE/g ,this.constants.tdStyle);
this.templateDOM = this.templateDOM.replace(/\$VOTER_DIV_NAME/g ,this.constants.voterDivName);
this.templateDOM = this.templateDOM.replace(/\$VOTER_DIV_CLASS/g ,this.constants.voterDivClass);
this.templateDOM = this.templateDOM.replace(/\$CONTAINER_DIV_ID/g ,this.constants.containerId);
this.templateDOM = this.templateDOM.replace(/\$TBODY_CLASS/g ,this.constants.tbodyClass);
this.templateDOM = this.templateDOM.replace(/\$RATES_DIV_ID/g ,this.constants.ratesDivId);
this.templateDOM = this.templateDOM.replace(/\$STARS_CLASS/g ,this.constants.starsClassname);
this.templateDOM = this.templateDOM.replace(/\$STARS_SPAN_CLASS/g ,this.constants.starsSpanClass);
this.templateDOM = this.templateDOM.replace(/\$STAR_DIV_STYLE/g ,this.constants.starDivStyle);
this.templateDOM = this.templateDOM.replace(/\$RATE_INFO_TD_CLASS/g ,this.constants.rateInfoTdClass);
this.templateDOM = this.templateDOM.replace(/\$RATE_INFO_DIV_ID/g ,this.constants.rateInfoDivId);
this.templateDOM = this.templateDOM.replace(/\$WIDTH_STARS_TD/g ,this.constants.widthStarsTd);
this.templateDOM = this.templateDOM.replace(/\$STARS_Y_HEIGHT/g ,this.matrixInfo.matrixYHeight);
this.templateDOM = this.templateDOM.replace(/\$MATRIX_ONE_ITEM_LENGTH/g ,this.matrixInfo.matrixXlength);
this.templateDOM = this.templateDOM.replace(/\$MATRIX_All_WIDTH/g ,this.matrixInfo.matrixAllXlength);
this.templateDOM = this.templateDOM.replace(/\$MATRIX_ALL_HEIGHT/g ,this.matrixInfo.matrixAllYlength);
this.templateDOM = this.templateDOM.replace(/\$SOURCE_URL/g ,this.constants.matrixUrl);
this.templateDOM = this.templateDOM.replace(/\$upperBR/g ,this.constants.upperBR);
this.templateDOM = this.templateDOM.replace(/\$lowerBR/g ,this.constants.lowerBR);
this.templateDOM = this.templateDOM.replace(/\$FIELDSET_CLASS/g ,this.constants.fieldsetClass);
this.templateDOM = this.templateDOM.replace(/\$FIELDSET_ID/g ,this.constants.fieldsetId);
this.templateDOM = this.templateDOM.replace(/\$RECOMMENDATIONS_UL_ID/g ,this.constants.recommendationsUlId);
this.templateDOM = this.templateDOM.replace(/\$RECOMMENDATIONS_UL_CLASS/g ,this.constants.recommendationsUlClass);
this.templateDOM = this.templateDOM.replace(/\$RECOMMENDATIONS_MORE_DIV_ID/g ,this.constants.recommendationsMoreDivId);
this.templateDOM = this.templateDOM.replace(/\$RECOMMENDATIONS_MORE_LINK_DIV_CLASS/g ,this.constants.recommendationsMoreLinkId);
this.templateDOM = this.templateDOM.replace(/\$RATE_STATUS_INFO_TABLE_ID/g ,this.constants.rateStatusInfoTableId);
this.templateDOM = this.templateDOM.replace(/\$RATE_STATUS_INFO_TD_ID/g ,this.constants.rateStatusInfoTdId);
this.templateDOM = this.templateDOM.replace(/\$GLOBAL_CLASS/g ,this.constants.globalClass);
this.templateDOM = this.templateDOM.replace(/\$PNGFIX_HELPER_DIV_ID/g ,this.constants.pngfixRatesHelper);
this.templateDOM = this.templateDOM.replace(/\$pngfixMatrix/g ,this.constants.pngfixMatrix);
this.templateDOM = this.templateDOM.replace(/\$PNGFIX_STARS_DIV_CLASS/g ,this.constants.pngfixStarsDivClass);
this.templateDOM = this.templateDOM.replace(/\$PNGFIX_DIVS_CONTAINER/g ,this.constants.pngfixDivsContainer);
this.templateDOM = this.templateDOM.replace(/\$PNGFIX_DIV_STYLE/g ,this.constants.pngfixDivsStyle);
this.templateReplacedOnce = true;
}
//------------------------------------------------------------------------------------------------------------------------
// getLanguageId
// returns the language id of the template
this.getLanguageId = function(){
return self.languageName;
}
//------------------------------------------------------------------------------------------------------------------------
// changeContainerClassWhenExists
//
this.changeContainerClassWhenExists = function(index){
var element = this.getElementWithFullName(this.constants.containerId,index);
if (element){
element.className = this.constants.globalClass;
}
}
//------------------------------------------------------------------------------------------------------------------------
// changeContainerClassWhenExists
//
this.changeWhenHaveStars = function(index){
new outbrain_timeout(
function(){
return ((typeof(outbrain_language_manager[self.languageName]) != 'object') && (outbrain_language_manager.isLanguageReady(self.languageName)));
},
function(){
if (! self.fixPngOnThisBrowser()){
var starsElement = self.getElementWithFullName( self.constants.ratesDivId,index);
} else { //old ie
var starsElement = self.getElementWithFullName( self.constants.pngfixDivsContainer,index);
}
if (starsElement){
var divsElements = starsElement.getElementsByTagName("div");
for (var i=0;i<divsElements.length;i++){
if ( ! self.fixPngOnThisBrowser() ){
divsElements[i].style.cssFloat = 'right';
} else{
divsElements[i].style.styleFloat = "right";
}
}
} else {
setTimeout(function(){self.changeWhenHaveStars(index)},100);
}
},
null,
null,
500,
1000,
true
);
}
//------------------------------------------------------------------------------------------------------------------------
// replaceWhenHaveLang
//
this.replaceWhenHaveLang = function(index){
new outbrain_timeout(
function(){
return ((typeof(outbrain_language_manager[self.languageName]) != 'object') && (outbrain_language_manager.isLanguageReady(self.languageName)));
},
function(){
if (outbrain_language_manager.isRtl(self.languageName)){
self.constants.globalClass = self.constants.globalClass.replace("div-wrapper","div-wrapper-right");
self.templateDOM = self.templateDOM.replace('div-wrapper"','div-wrapper-right"');
self.templateDOM = self.templateDOM.replace(self.matrixInfo.matrixSource,self.matrixInfo.matrixSourceRTL);
self.changeContainerClassWhenExists(index); // we can't be sure the dom printed
self.changeWhenHaveStars(index);
}
},
null,
null,
500,
1000,
true
);
}
//------------------------------------------------------------------------------------------------------------------------
// replaceWhenHaveLang
//
this.waitForImages = function(){
new outbrain_timeout(
function(){
return (self.isMatrixReady);
},
function(){return true},
null,
null,
500,
1000,
true
);
}
//------------------------------------------------------------------------------------------------------------------------
// replaceEveryTime
// return the DOM after some changes per item
this.replaceEveryTime = function(index){
// only first time
if (!this.templateHaveOdbAndLang){
this.imagesPreload();
}
// when we print the dom we don't sure we have the language (wp/dp - we need insert in the rendered position!), so we do function that will change the attribute later
this.replaceWhenHaveLang(index);
// every time
var thisRater = this.templateDOM;
thisRater = thisRater.replace(/\$INDEX/g ,index);
thisRater = thisRater.replace(/\$GLOBAL_CLASS/g ,this.constants.globalClass);
// return
return thisRater;
}
//------------------------------------------------------------------------------------------------------------------------
// isTemplateReady
// is this template ready?
this.isTemplateReady = function(){
return this.templateReplacedOnce;
}
//------------------------------------------------------------------------------------------------------------------------
// getDomPerPost
// get the DOM string for [index] post
this.getDomPerPost = function(index){
return this.replaceEveryTime(index);
}
//------------------------------------------------------------------------------------------------------------------------
// insertRaterElement
// insert the rater element
this.insertRaterElement = function(newDom,a){
var returnValue = null;
newDom = newDom.firstChild;//remove the wrapper Div of the rater and return the obj
returnValue = this.dom.elementInsertion(a,newDom,this.top,this.inside);
return returnValue;
}
this.addCssFile = function(){
var cssElement = document.createElement("link");
cssElement.rel = outbrain_settings.globals.cssRel;
cssElement.type = outbrain_settings.globals.cssType;
cssElement.id = outbrain_settings.rater.cssId;
cssElement.href = outbrain_settings.rater.cssUrl;
var heads = document.getElementsByTagName("head");
if( heads.length > 0 ){
heads[0].appendChild(cssElement);
} else {
outbrain_template_manager.addElementToManagerHelper(cssElement);//no head
}
}
//------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
this.startTemplate = function(){
this.addCssFile();
outbrain_language_manager.addLanguage(self.languageName,outbrain_settings.language.url);
this.initTemplate();
this.constants.init();
this.buildDOMOnce();
this.replacerOnce();
this.waitForImages();
}
this.startTemplate();
}
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain_template_object - end
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain_template_manager_object start
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
var outbrain_template_manager_object = function(){ // no unoverride!!
this.ready = false;
//------------------------------------------------------------------------------------------------------------------------
// settings
var self_manager = this;
this.globalElementId = "outbrain_template_element_";
this.helperElementId = "outbrain_manager_helper_div";
this.optionalTemplates = [];
this.userTemplatesFileUrl = "";
this.userTemplatesFileReturned = false;
this.templatesListInit = false;
this.allTemplatesWasReadyBefore = false;
this.templates = [];
this.templateSTR = null;
this.dom = null;
//------------------------------------------------------------------------------------------------------------------------
// templatesLoop
// do loop on all templates and call some function
this.templatesLoop = function(func){
for (var i=0;i<this.templates.length;i++){
func();
}
}
//------------------------------------------------------------------------------------------------------------------------
// itemsLoop
// do loop on all items and call some function
/*
this.itemsLoop = function(func){
var itemsArray = this.getDataAllPosts();
for (i=0;i<itemsArray.length;i++){
func();
}
}
*/
//------------------------------------------------------------------------------------------------------------------------
// getDataAllPosts
// return the data array handler
this.getDataAllPosts = function(){
return OB_voterWidgetObjArray;
}
//------------------------------------------------------------------------------------------------------------------------
// getDataPerPost
// return getDataAllPosts(index)
this.getDataPerPost = function(templateIndex,postIndex,rateMode){
var obj = OB_voterWidgetObjArray[postIndex];
if (typeof(rateMode) != 'number'){
rateMode = obj.rateMode;
}
var moreInfo = self_manager.getRateInfo(templateIndex,postIndex,rateMode);
obj.rateInfo = moreInfo[1];
obj.rateStatus = moreInfo[2];
obj.rateMode = moreInfo[3];
obj.recTitle = moreInfo[4];
return obj;
}
//------------------------------------------------------------------------------------------------------------------------
// getRecommendationDataPerDoc
// return getDataAllPosts(index)
this.getRecommendationDataPerDoc = function(templateIndex,index,doc){
var postLink = null;
if (typeof(doc.content) == 'string'){
var json = this.getDataPerPost(templateIndex,index).jsonObj;
var refDID = (typeof(json.response.request.did) == 'string') ? json.response.request.did : null;
postLink = outbrain_settings.domains.traffic + "?key="+doc.url_hash;
postLink += "&agent=" + outbrain_settings.rater.recommendations.agentId;
postLink += "&version=" + outbrain_settings.versions.rater;
if (refDID != null){
postLink += "&rdid="+refDID;
}
}
var linkText = null;
if (typeof(doc.content) == 'string'){
linkText = doc.content;
}
var sourceName = null;
if (typeof(doc.source_name) == 'string'){
sourceName = doc.source_name;
}
var authorName = null;
if (typeof(doc.author) == 'string'){
authorName = doc.author;
}
var pubDate = null;
if (typeof(doc.pubDate) == 'string'){
pubDate = doc.pubDate;
}
var isSameSource = false;
if (typeof(doc.same_source) == 'string'){
isSameSource = (doc.same_source=="true");
}
var isFramePage = true;
if (typeof(outbrain_settings.rater.recommendations.showFramePage) == 'boolean'){
isFramePage = outbrain_settings.rater.recommendations.showFramePage;
}
if (typeof(OB_showFramePage) == 'boolean'){
if (!OB_showFramePage) isFramePage = false;
}
if (isSameSource || !isFramePage){
postLink += "&fp=false&am=get";
}
var recType = null;
if (typeof(doc.rec_type) == 'string'){
recType = doc.rec_type;
postLink += "&type=" + recType;
}else{
postLink += "&type=" + outbrain_settings.rater.recommendations.type;
}
return [postLink,linkText,sourceName,authorName,pubDate,isSameSource,recType];
}
//------------------------------------------------------------------------------------------------------------------------
// SetStatus
// set the status of [index] widget item and do action acoording to the status type
// extraInt / extraStr are for actions that need some extra variable
this.setStatus = function(templateIndex,index,statusId,extraInt,extraStr){
var itemData = this.getDataPerPost(templateIndex,index);
itemData.rateMode = statusId;
switch (statusId){
case outbrain_settings.rater.statuses.RATER_PRE_RATE_MODE: // before rate
break;
case outbrain_settings.rater.statuses.RATER_RATE_MODE: // on rate action
outbrain_rater.rate(templateIndex,index,extraInt);
break;
case outbrain_settings.rater.statuses.RATER_POST_RATE_MODE: // after rate
itemData.rated = true;
itemData.frezz = false;
itemData.frezzSemaphore = 0;
this.updateAllData(index,statusId);
break;
}
}
//------------------------------------------------------------------------------------------------------------------------
// isThereTemplateWithRecommendations
//
this.isThereTemplateWithRecommendations = function(){
for (i=0;i<this.templates.length;i++){
if (this.templates[i].supportRecommendations()){
return true;
}
}
return false;
}
//------------------------------------------------------------------------------------------------------------------------
// recommendationsStatusPerItem
//
this.recommendationsStatusPerItem = function(templateIndex,index,rateMode){
var currentVoterWidget = this.getDataPerPost(templateIndex,index);
var value = false;
if (this.lastOdbRotationRequestedItem < index){
value = false;
} else if (outbrain_settings.rater.recommendations.always){ // if true, recommendations always activate in all blogs!
value = true;
} else if (this.templates[templateIndex].supportRecommendations()){
if (outbrain_language_manager.isRecommendationsAvailable(outbrain_template_manager.templates[templateIndex].getLanguageId())){
if ((rateMode == outbrain_settings.rater.statuses.RATER_POST_RATE_MODE) && (OB_voterWidgetObjArray[index].rankInfo.vote >= 3)){
value = true;
} else if (currentVoterWidget.isPersonalized){
value = !(currentVoterWidget.rankInfo.getPersonalRateIndex() == 0);//not Dislaike
} else if (currentVoterWidget.rankInfo == null){
value = false;
} else if ((currentVoterWidget.rankInfo.getComputedRank(true) > 2.5 || currentVoterWidget.rankInfo.getComputedRank(true) == 0 ) && (OB_voterWidgetObjArray[index].rankInfo.vote == 0)){
value = true;
} else {
value = false;
}
} else {
value = false;
}
} else { // if (OB_showRec)
value = false;
}
return value;
}
//------------------------------------------------------------------------------------------------------------------------
// recommendationsHaveDataPerItem
//
this.recommendationsHaveDataPerItem = function(index,jsonObj){
var value = (
typeof(jsonObj.response) != 'undefined'
&&
typeof(jsonObj.response.documents) != 'undefined'
&&
typeof(jsonObj.response.documents.total_count) != 'undefined'
&&
jsonObj.response.documents.total_count > 0
);
return value;
}
//------------------------------------------------------------------------------------------------------------------------
// showRecommendationsPerTemplateIsOk
// tells the template to show recommendations
this.showRecommendationsPerTemplateIsOk = function(templateIndex,index,itemData,rateMode){
self_manager.templates[templateIndex].showRecommendations(index,itemData,rateMode);
}
//------------------------------------------------------------------------------------------------------------------------
// showRecommendationsPerTemplate
// tells the template to show recommendations
this.showRecommendationsPerTemplate = function(templateIndex,index,itemData,rateMode){
if (this.recommendationsStatusPerItem(templateIndex,index,rateMode) && this.recommendationsHaveDataPerItem(index,itemData.jsonObj)){
this.showRecommendationsPerTemplateIsOk(templateIndex,index,itemData,rateMode);
}
}
//------------------------------------------------------------------------------------------------------------------------
// showRecommendations
// tells the template to show recommendations
this.showRecommendations = function(templateIndex,index,itemData,rateMode){
var jsonObj = itemData.jsonObj;
if (this.recommendationsStatusPerItem(templateIndex,index,rateMode) && this.recommendationsHaveDataPerItem(index,jsonObj)){
//this.templatesLoop(function(){
for (var templatesLoop=0;templatesLoop<this.templates.length;templatesLoop++){
self_manager.showRecommendationsPerTemplateIsOk(templatesLoop,index,itemData,rateMode);
}
//});
}
}
//------------------------------------------------------------------------------------------------------------------------
// updateRateInfoPerTemplate
// tells the template to show recommendations or update other data
this.updateRateInfoPerTemplate = function(templateIndex,index,itemData,rateMode){
this.templates[templateIndex].updateRateInfo(index,itemData,rateMode);
}
//------------------------------------------------------------------------------------------------------------------------
// updateRateInfo
// tells the template to show recommendations or update other data
this.updateRateInfo = function(index,itemData,rateMode,rateInfo){
//this.templatesLoop(function(){
for (var templatesLoop=0;templatesLoop<this.templates.length;templatesLoop++){
self_manager.updateRateInfoPerTemplate(templatesLoop,index,itemData,rateMode);
}
//});
}
//------------------------------------------------------------------------------------------------------------------------
// changeViewPerTemplate
// tells the template to change visibility
this.changeViewPerTemplate = function(templateIndex,index,itemData,rateMode){
this.templates[templateIndex].changeView(index,itemData,rateMode);
}
//------------------------------------------------------------------------------------------------------------------------
// changeView
// tells the template to change visibility
this.changeView = function(index,itemData,rateMode){
//this.templatesLoop(function(){
for (var templatesLoop=0;templatesLoop<this.templates.length;templatesLoop++){
self_manager.changeViewPerTemplate(templatesLoop,index,itemData,rateMode);
}
//});
}
//------------------------------------------------------------------------------------------------------------------------
// updateAllDataPerTemplate
//
this.updateAllDataPerTemplate = function(templateIndex,index,rateMode){
if (typeof(rateMode) == 'undeifened'){ rateMode = null;}
var itemData = this.getDataPerPost(templateIndex,index,rateMode);
// am...
if (rateMode==null){
rateMode = itemData.rateMode;
}
this.updateRateInfoPerTemplate(templateIndex,index,itemData,rateMode);
this.changeViewPerTemplate(templateIndex,index,itemData,rateMode);
this.showRecommendationsPerTemplate(templateIndex,index,itemData,rateMode);
}
//------------------------------------------------------------------------------------------------------------------------
// updateAllData
// check for recommendations and update the rate info
this.updateAllData = function(index,rateMode){
for (var templatesLoop=0;templatesLoop<this.templates.length;templatesLoop++){
if (typeof(rateMode) == 'undeifened'){
rateMode = null;
}
var itemData = this.getDataPerPost(templatesLoop,index);
if (rateMode == null){ rateMode=itemData.rateMode;}
self_manager.showRecommendationsPerTemplate(templatesLoop,index,itemData,rateMode);
self_manager.changeViewPerTemplate(templatesLoop,index,itemData,rateMode);
self_manager.updateRateInfoPerTemplate(templatesLoop,index,itemData,rateMode);
}
}
//------------------------------------------------------------------------------------------------------------------------
// postDataLoaded
// when data loaded from ODB
this.postDataLoaded = function(index){
this.updateAllData(index,null);
}
//------------------------------------------------------------------------------------------------------------------------
// postDataLoaded
// when the user do rate
this.userRated = function(index){
//var currWidgetObj = this.getDataPerPost(index);
//var rateMode = currWidgetObj.rateMode;
//this.updateAllData(index,rateMode);
}
this.getMatrixInfosData = function()
{
//get Matrix info to insert to every template
this.result = null;
this.defaultMatrixInfosJson = outbrain_settings.defaultMatrixInfos;
this.userMatrixInfos = (typeof(OB_user_matrix_infos)=='undefined')? this.defaultMatrixInfosJson:OB_user_matrix_infos;
if (this.userMatrixInfos == null){
this.userMatrixInfos = this.defaultMatrixInfoJson;
}
if (this.userMatrixInfos != null)
try{
this.result = eval('(' + this.userMatrixInfos + ')');
}
catch(error){
return null;
}
return this.result;
}
//------------------------------------------------------------------------------------------------------------------------
// getTemplateByUserString
// build the templates, insert into templates array
this.getTemplatesByUserString = function(){
this.userMatrixInfos = self_manager.getMatrixInfosData();
this.defaultArr = outbrain_settings.defaultTemplate;
this.userTemplate = (typeof(OB_user_template)=='undefined')? this.defaultArr:OB_user_template;
if (this.userTemplate == null){
this.userTemplate = this.defaultArr;
}
if (this.userTemplate.constructor != Array){
this.userTemplate = [this.userTemplate];
}
for (var i=0;i<this.userTemplate.length;i++){
var currentTemplateString = this.userTemplate[i];
var currentTemplateAsArray = currentTemplateString.split(outbrain_settings.templateGlobalSplit);
if (currentTemplateAsArray.length != 4 && currentTemplateAsArray.length != 5 ){
continue;
}
if ((currentTemplateAsArray[0] != "top") && (currentTemplateAsArray[0] != "bottom")){
continue;
}
if (typeof(self_manager.optionalTemplates[currentTemplateAsArray[1]]) == 'undefined'){
continue;
}
if (typeof(self_manager.optionalTemplates[currentTemplateAsArray[1]].constructor) == 'undefined'){
continue;
}
if (self_manager.optionalTemplates[currentTemplateAsArray[1]].constructor != Function){
continue;
}
if (typeof(currentTemplateAsArray[2]) != "string"){
continue;
} else if ((currentTemplateAsArray[2] != "true") && (currentTemplateAsArray[2] != "false")){
continue;
} else {
currentTemplateAsArray[2] = (currentTemplateAsArray[2]=="true"); // from string to boolean
}
// backwards compatibility
if ((currentTemplateAsArray[1] == outbrain_settings.defaultTemplateName) && (currentTemplateAsArray[0] == "bottom")){
if ((typeof(OB_isOnHeader) == 'boolean') && (OB_isOnHeader)){
currentTemplateAsArray[0] = "top";
}
if (typeof(OB_rater_position) == 'string'){
currentTemplateAsArray[0] = (OB_rater_position == "top")? "top":"boolean";
}
if (typeof(OB_insertInElement) == 'boolean'){
currentTemplateAsArray[2] = OB_insertInElement;
}
if ((typeof(OB_showRec) == 'boolean') && (OB_showRec)){
if (currentTemplateAsArray[3].indexOf("recommendations") == -1){
if (currentTemplateAsArray[3].length > 0){
currentTemplateAsArray[3] += " ";
}
currentTemplateAsArray[3] += "recommendations";
}
}
}
//currentTemplateAsArray[0]
var templateItems = outbrain_settings.templateItemsJoin + currentTemplateAsArray[3].split(outbrain_settings.templateItemsSplit).join(outbrain_settings.templateItemsJoin) + outbrain_settings.templateItemsJoin;
var someTemplateItem = false;
for (var j=0;j<outbrain_settings.templateOptions.length;j++){
if (templateItems.indexOf(outbrain_settings.templateItemsJoin+outbrain_settings.templateOptions[j]+outbrain_settings.templateItemsJoin) > -1){
someTemplateItem = true;
break;
}
}
if (!someTemplateItem){
continue;
}
//init template's matrix info with json node by name of the template
templateName = '';
if (currentTemplateAsArray[4] == null || currentTemplateAsArray[4] == 'undefined'){
templateName = currentTemplateAsArray[1];
}
else{
templateName = currentTemplateAsArray[4];
}
var templateMatrixInfo = null;
try{templateMatrixInfo = self_manager.userMatrixInfos.matrixInfos[templateName];}catch(error){}
//create new template with user params
self_manager.templates[self_manager.templates.length] = new self_manager.optionalTemplates[currentTemplateAsArray[1]]((self_manager.templates.length),currentTemplateAsArray[0],currentTemplateAsArray[2],currentTemplateAsArray[3],templateMatrixInfo);
}
this.ready = true;
self_manager.templatesListInit = true;
}
//------------------------------------------------------------------------------------------------------------------------
// addTemplate
//
this.addTemplate = function(templatesArray){
for (var i=0;i<templatesArray.length;i++){
this.optionalTemplates[templatesArray[i][0]] = templatesArray[i][1];
if (templatesArray[i][0] != outbrain_settings.defaultTemplateName){
self_manager.userTemplatesFileReturned = true;
}
}
}
//------------------------------------------------------------------------------------------------------------------------
//
//
this.templatesLoaded = function(){
this.getTemplatesByUserString();
}
this.userScriptTag = "userTemplateElement";
//------------------------------------------------------------------------------------------------------------------------
// removeTemplateScriptElement
//
this.removeTemplateScriptElement = function(){
var element = outbrain_dom.$(this.userScriptTag);
if (element){
element.src = "about:blank";
var ele = this.removeElementFromManagerHelper(element);
return true;
}
return false;
}
//------------------------------------------------------------------------------------------------------------------------
// addTemplateScriptElement
//
this.addTemplateScriptElement = function(){
var s = document.createElement("script");
s.type = outbrain_settings.globals.scriptType;
s.id = this.userScriptTag;
s.src = this.userTemplatesFileUrl;
this.addElementToManagerHelper(s);
new outbrain_timeout(
function(){return (self_manager.userTemplatesFileReturned);},
function(){self_manager.removeTemplateScriptElement(); self_manager.templatesLoaded();},
null,
function(){self_manager.removeTemplateScriptElement(); self_manager.templatesLoaded();},
1000,
20,
true
);
}
//------------------------------------------------------------------------------------------------------------------------
//
//
this.loadTemplates = function(){
this.addTemplate([[outbrain_settings.defaultTemplateName,outbrain_template_object]]);
if (typeof(OB_userTemplateFile) == 'string'){
this.userTemplatesFileUrl = OB_userTemplateFile;
this.addTemplateScriptElement();
} else {
self_manager.userTemplatesFileReturned = true;
this.templatesLoaded();
}
}
//------------------------------------------------------------------------------------------------------------------------
// initTemplateManager
// first action when object create
this.initTemplateManager = function(){
this.dom = new outbrain_dom_object();
var helper = "<div id='" + this.helperElementId + "' style='display:none;'></div>";
document.write (helper);
}
//------------------------------------------------------------------------------------------------------------------------
//
//
this.getHelperElement = function(){
return this.dom.$(this.helperElementId);
}
//------------------------------------------------------------------------------------------------------------------------
//
//
this.getRateInfo = function(templateIndex,index,rateMode){
var info = outbrain_rater.getRateInfo(this.templates[templateIndex].getLanguageId(),index,rateMode)
if (!info){
return false;
}
return info;
}
//------------------------------------------------------------------------------------------------------------------------
//
//
this.isSingleTemplateReady = function(index){
return this.templates[index].isTemplateReady();
}
//------------------------------------------------------------------------------------------------------------------------
//
//
this.isTemplatesReady = function(){
//this.templatesLoop(function(){
for (var j=0;j<this.templates.length;j++){
if (!self_manager.isSingleTemplateReady(j)){
return false;
}
}
//});
return true;
}
//------------------------------------------------------------------------------------------------------------------------
//
//
this.onDomReady = function(){
var returnedArray = [];
//this.templatesLoop(function(){
for (var j=0;j<this.templates.length;j++){
returnedArray[returnedArray.length] = self_manager.templates[j].domReady(itemsArray[j].rateMode,j);
}
//});
return returnedArray;
}
//------------------------------------------------------------------------------------------------------------------------
//
//
this.insertDomPerPost = function(index,a){
var returnValue = null;
//this.templatesLoop(function(){
for (var j=0;j<this.templates.length;j++){
var newDom = self_manager.templates[j].getDomPerPost(index);
var newElement = document.createElement("div");
newElement.innerHTML = newDom;
//if (outbrain_settings.platformType == null){
//document.write (newDom);
// returnValue = self_manager.templates[j].insertRaterElement(newElement,a);
//} else {
returnValue = self_manager.templates[j].insertRaterElement(newElement,a);
//}
//});
}
return returnValue;
}
//------------------------------------------------------------------------------------------------------------------------
// loadRankDataForPost
//
this.loadRankDataForPost = function(index){
new outbrain_timeout(
function(){ return self_manager.isTemplatesReady(); },
function(){
if (!self_manager.allTemplatesWasReadyBefore){
outbrain_rater.initOnlyWithTemplates();
self_manager.allTemplatesWasReadyBefore = true;
}
outbrain_rater.loadRankData(index);
},
null,
null,
100,
1000,
true
);
}
//------------------------------------------------------------------------------------------------------------------------
// addElementToManagerHelper
//
this.addElementToManagerHelper = function(newElement){
var helperDiv = this.getHelperElement();
if (helperDiv){
var ele = helperDiv.appendChild(newElement);
return ele;
}
return false;
}
//------------------------------------------------------------------------------------------------------------------------
// removeElementFromManagerHelper
//
this.removeElementFromManagerHelper = function(Element){
if (Element){
return Element.parentNode.removeChild(Element);
}
return false;
}
//------------------------------------------------------------------------------------------------------------------------
// do rate
// write the rate element (frame) into DOM, inside manager helper div
this.doRate = function(templatesLoop,index,url){
var currWidgetObj = this.getDataPerPost(templatesLoop,index);
// remove prev rate
if( typeof(currWidgetObj.rankInfo.lastRateId) != 'undefined'
&& OB_voterWidgetObjArray[index].rankInfo.lastRateId != null ){
var rateFrame = this.dom.$(currWidgetObj.rankInfo.lastRateId);
if (rateFrame){
rateFrame.parentNode.removeChild(rateFrame);
}
}
//Create the new IFRAME
var helperDiv = this.getHelperElement();
if (helperDiv){
var tempIFrame = document.createElement('iframe');
var randId = 'RSIFrame' + Math.random();
tempIFrame.setAttribute('id',randId);
tempIFrame.style.border='0px';
tempIFrame.frameborder=0;
tempIFrame.style.width='0px';
tempIFrame.style.height='0px';
tempIFrame.style.display='none';
var IFrameObj = this.addElementToManagerHelper(tempIFrame);
var IFrameDoc = IFrameObj.contentWindow.document;
IFrameDoc.location.replace( url );
OB_voterWidgetObjArray[index].rankInfo.lastRateId = randId;
}
}
//------------------------------------------------------------------------------------------------------------------------
// good luck :-)
this.initTemplateManager();
}
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain_template_manager_object end
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain_whatIsPage_object start
// the 'what is' page opener manager
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
var outbrain_whatIs = typeof(outbrain_whatIs) == "object" ? outbrain_whatIs : new function(){
//------------------------------------------------------------------------------------------------------------------------
this.openedBefore = false;
var self = this;
//------------------------------------------------------------------------------------------------------------------------
this.start = function(index){
new outbrain_timeout(
function(){
return (typeof(outbrain_whatis_create) == 'function');
},
function(){
outbrain_whatis_create(index);
},
null,
null,
500,
100,
true
);
}
//------------------------------------------------------------------------------------------------------------------------
this.loadJs = function(index){
if (!this.openedBefore){
var newScriptElement = document.createElement("script");
newScriptElement.src = outbrain_settings.whatIs.url;
newScriptElement.setAttribute('id',outbrain_settings.whatIs.id );
newScriptElement.setAttribute('type',outbrain_settings.globals.scriptType);
var heads = document.getElementsByTagName("head");
if( heads.length > 0 ){
heads[0].insertBefore(newScriptElement, heads[0].firstChild);
} else {
var managerHelper = outbrain_template_manager.getHelperElement();
if (managerHelper){
voter.parentNode.insertBefore (newScriptElement,voter);
} else {
setTimeout(function(){self.loadJs(index);},1000);
}
}
this.openedBefore = true;
this.start(index);
} else {
outbrain_whatis_click(index);
}
}
}
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain_whatIsPage_object end
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
// outbrain_rater_object start
//--------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------
var outbrain_rater_object = function(){ // no unoverride!!
//------------------------------------------------------------------------------------------------------------------------
var self = this;
this.isRunning = false;
this.supportRecommendations = false;
this.halt = false;
this.pmd = null;
this.startTime = new Date();
this.odbSemafor = false;
this.delay = (outbrain_browsers.mozilla)? 1000:200;
this.odbDynamicCallsArray = [];
this.isLoadDynamicDataOn = false;
this.pageLoaded = false;
//User Post custom tags
// backwards compatibility - user DOM global customize variables
this.userCustomizeContainerDivClass = null;
this.userCustomizePermaLinkClass = null;
this.userCustomizeFooterClass = null;
this.elementToSearch = "div";
this.countInsertedItems = -1;
this.lastOdbRotationRequestedItem = 0;
this.lastOdbRotationReturnedItem = 0;
this.windowName = null;
//------------------------------------------------------------------------------------------------------------------------
// getQSParam
//
this.getQSParam = function(param){
var query = document.location.search.substring(1);
var parms = query.split('&');
var val = null;
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 ) {
var key = parms[i].substring(0,pos);
if( param == key ){
val = parms[i].substring(pos+1);
break;
}
}
}
return val;
}
//------------------------------------------------------------------------------------------------------------------------
// returnedOdbData
// insert data to array
this.returnedOdbData = function(jsonObj,index,isRec){
if ((!isRec) && (OB_voterWidgetObjArray[index].jsonObj != null)){
return;
}
if (isRec){
this.lastOdbRotationReturnedItem = index;
this.odbNextRecReq(index+1,true);
}
OB_voterWidgetObjArray[index].jsonObj = jsonObj;
this.widgetInit(index);
}
//------------------------------------------------------------------------------------------------------------------------
// widgetInit
//
this.widgetInit = function(index){
var currentJsonObj = OB_voterWidgetObjArray[index].jsonObj;
if (currentJsonObj==null){
return;
}
OB_voterWidgetObjArray[index].isPersonalized = currentJsonObj.response.score.preferred=='personal';
OB_voterWidgetObjArray[index].rankInfo = new OB_voterWidgetObjArray[index].rankInfo_object(currentJsonObj.response.score.average.ratings.wsum_ratings,currentJsonObj.response.score.average.ratings.count_users ,currentJsonObj.response.score.average.ratings.wcount_users,outbrain_settings.keys_and_users.userName);
if (typeof(currentJsonObj.response.score.self_rating)!='undefined'){
OB_voterWidgetObjArray[index].rankInfo.vote = currentJsonObj.response.score.self_rating;
OB_voterWidgetObjArray[index].rankInfo.rank = OB_voterWidgetObjArray[index].rankInfo.rank - OB_voterWidgetObjArray[index].rankInfo.vote;
//outbrain_template_manager.setStatus(null,index,outbrain_settings.rater.statuses.RATER_POST_RATE_MODE);
OB_voterWidgetObjArray[index].rateMode = outbrain_settings.rater.statuses.RATER_POST_RATE_MODE;
OB_voterWidgetObjArray[index].rated = true;
OB_voterWidgetObjArray[index].frezz = false;
OB_voterWidgetObjArray[index].frezzSemaphore = 0;
}
if (OB_voterWidgetObjArray[index].isPersonalized){
OB_voterWidgetObjArray[index].rankInfo.personalRatedBy = currentJsonObj.response.score.personal.ratings.count_users;
OB_voterWidgetObjArray[index].rankInfo.personalRank = currentJsonObj.response.score.personal.score;
}
// post data loaded
outbrain_template_manager.postDataLoaded(index);
return true;
}
//------------------------------------------------------------------------------------------------------------------------
// lockRater
//
this.lockRater = function(index){
if ( OB_voterWidgetObjArray[index].frezz && OB_voterWidgetObjArray[index].frezzSemaphore ==0){
OB_voterWidgetObjArray[index].frezzSemaphore++;
return false;
} else if ( OB_voterWidgetObjArray[index].frezz && OB_voterWidgetObjArray[index].frezzSemaphore > 0 ){
return true;
}
}
//------------------------------------------------------------------------------------------------------------------------
// getRateInfo
//
this.getRateInfo = function(language,index,rateMode){
if (this.lockRater(index)){
return false;
}
if (OB_voterWidgetObjArray[index].rankInfo == null){
return false;
}
var currentVoterWidget = OB_voterWidgetObjArray[index];
var localRateMode = (rateMode !=null) ? rateMode : OB_voterWidgetObjArray[index].rateMode;
var rateInfo = "";
var rateStatus = "";
var score = 0;
var rate = "";
var recommendationsTitle = "";
var jsonObj = null;
if (localRateMode == outbrain_settings.rater.statuses.RATER_RATE_MODE){
rateInfo = "<strong>"+outbrain_language_manager.getRateDescription(language,OB_voterWidgetObjArray[index].currentRateValue-1)+"</strong>";
rateStatus = outbrain_language_manager.rateGetAverageStr(language,currentVoterWidget.rankInfo.getComputedRank(true),currentVoterWidget.rankInfo.ratedBy);
} else {
if (!OB_voterWidgetObjArray[index].isPersonalized || currentVoterWidget.rankInfo.vote!=0 ){
if (currentVoterWidget.rankInfo.ratedBy ==0) {
rateInfo = outbrain_language_manager.getBeTheFirstString(language);
} else {
if(!currentVoterWidget.rated){
rateInfo = outbrain_language_manager.rateGetAggregate(language,currentVoterWidget.rankInfo.getComputedRank(true),currentVoterWidget.rankInfo.ratedBy,false);
} else {
rateInfo = outbrain_language_manager.rateGetAggregate(language,currentVoterWidget.rankInfo.getComputedRank(true),currentVoterWidget.rankInfo.ratedBy,true);
}
rateInfo += ' <span id="whatIsSpan">[<a class="outbrain_my_rating" style="font-weight:bold;cursor:pointer;" onclick="outbrain_whatIs.loadJs(' + index + ');">?</a>]</span>';
}
} else {
var personalIndex = currentVoterWidget.rankInfo.getPersonalRateIndex();
var personalLabel = outbrain_language_manager.getPersonalRateDesc(language,personalIndex);
rateInfo = outbrain_language_manager.rateGetLikeYou(personalLabel,currentVoterWidget.rankInfo.getComputedRank(),currentVoterWidget.rankInfo.personalRatedBy);
rateInfo += ' <span id="whatIsSpan">[<a class="outbrain_my_rating" style="font-weight:bold;cursor:pointer;" onclick="outbrain_whatIs.loadJs(' + index + ');">'+outbrain_language_manager.getHowString(language)+'</a>]</span>';
rateStatus = outbrain_language_manager.rateGetAverageStr(language,currentVoterWidget.rankInfo.getComputedRank(true),currentVoterWidget.rankInfo.ratedBy);
}
}
if (!currentVoterWidget.rated){
if (!OB_voterWidgetObjArray[index].isPersonalized){
rateStatus ='';
}
} else {
rateStatus = outbrain_language_manager.getRatePostRate(language,currentVoterWidget.rankInfo.vote-1) +' ({starsImage})';
}
rate = currentVoterWidget.rankInfo.vote;
recommendationsTitle = outbrain_language_manager.getRatePostRateForRecommendations(language,rate);
return [currentVoterWidget,rateInfo,rateStatus,localRateMode,recommendationsTitle];
}
//------------------------------------------------------------------------------------------------------------------------
// createOdbScriptElement
//
this.createOdbScriptElement = function(id,src,defer){
var s = null;
var sig = "";
if (this.windowName == null){
var randomstring = '';
var string_length = 8;
for (var i=0; i<string_length; i++) {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
if ((typeof(window.name) == 'string') && ((window.name == "") || (window.name.indexOf("frame")>-1))){ // safari have a default frame names with the word 'frame'
window.name = randomstring;
this.windowName = window.name;
} else {
if ((typeof(window.name) == 'string') && ((window.name != ""))){
this.windowName = window.name;
} else {
this.windowName = randomstring;
}
}
}
src += "&sig=" + this.windowName;
src += "&rand=" + Math.random();
s = document.createElement("script");
s.setAttribute('id' , id);
s.setAttribute('type' , outbrain_settings.globals.scriptType);
s.setAttribute('src' , src);
s.setAttribute('defer' , defer);
return s;
}
//------------------------------------------------------------------------------------------------------------------------
// odbPathReplacer
//
this.odbPathReplacer = function(path,index){
var permaLink = encodeURIComponent(OB_voterWidgetObjArray[index].permaLink);
path = path.replace(/\$VOTER_INDEX/g,index);
path = path.replace(/\$PERMA_LINK/g,permaLink);
if ((typeof(outbrain_template_manager) != 'undefined') && (outbrain_template_manager.templates.length > 0) && (typeof(outbrain_language_manager.isLanguageReady) == 'function') && (outbrain_language_manager.isLanguageReady(outbrain_template_manager.templates[0].languageName))){
if (outbrain_language_manager.getName(outbrain_template_manager.templates[0].getLanguageId())){
path = path.replace(/\$LANGUAGE/g,outbrain_language_manager.getName(outbrain_template_manager.templates[0].getLanguageId()));
}
} else {
path = path.replace(/\$LANGUAGE/g,"en")
}
path += "&r="+Math.random();
return path;
}
//------------------------------------------------------------------------------------------------------------------------
// odbNextReqReqOnload
//
this.odbNextReqReqOnload = function(index){
new outbrain_timeout(
function(){
return self.pageLoaded;
},
function(){
self.odbNextRecReq(index,false);
},
null,
null,
500,
1000,
true
);
}
//------------------------------------------------------------------------------------------------------------------------
// odbNextRecReq
//
this.odbNextRecReq = function(index,tryOnload){
if (index < OB_voterWidgetObjArray.length){
if (index < outbrain_settings.rater.recommendations.maxCalls){
new outbrain_timeout(
function(){
return ((index == 0) || (OB_voterWidgetObjArray[index].rankInfo != null));
},
function(){
self.lastOdbRotationRequestedItem++;
self.odbDynamicCallsArray[index] = null;
var permaLink = encodeURIComponent(OB_voterWidgetObjArray[index].permaLink);
var requestUrl = null;
requestUrl = outbrain_settings.odb.odbGetDataUrlRec;
requestUrl = self.odbPathReplacer(requestUrl,index);
var scriptTag = self.createOdbScriptElement(outbrain_settings.rater.odb.getScoreRecId + '_' +index,requestUrl,true);
var insertInElement;
if (document.getElementsByTagName("head").length > -1){
insertInElement = document.getElementsByTagName("head")[0];
} else {
insertInElement = outbrain_template_manager.getHelperElement();
}
self.insertOdbRequestIntoDom(insertInElement,scriptTag);
},
null,
null,
100,
1000,
true
);
}
} else {
if (tryOnload){
this.odbNextReqReqOnload(index);
//odbNextRecOnload(index);
}
}
}
//------------------------------------------------------------------------------------------------------------------------
// loadRankData
//
this.loadRankData = function(index){
try{
var requestUrl = "";
var id = outbrain_settings.rater.odb.getScoreId;
if ((this.supportRecommendations) && (index==0)){
self.odbDynamicCallsArray[index] = null;
} else {
requestUrl = outbrain_settings.odb.odbGetDataUrlRegular;
requestUrl = this.odbPathReplacer(requestUrl,index);
var s = this.createOdbScriptElement(id + '_' + index,requestUrl,true);
self.odbDynamicCallsArray[index] = s;
}
self.startTime = new Date();
if (!self.isLoadDynamicDataOn){
self.isLoadDynamicDataOn = true;
setTimeout(function(){self.loadDynamicData();},self.delay);
}
} catch(e){
}
}
//------------------------------------------------------------------------------------------------------------------------
// insertOdbRequestIntoDom
//
this.insertOdbRequestIntoDom = function(oldN,newN){
//if (typeof(oldN.firstChild) != 'undefined'){
// oldN.insertBefore(newN,oldN.firstChild);
//} else {
oldN.appendChild(newN);
//}
}
//------------------------------------------------------------------------------------------------------------------------
// loadDynamicData
//
this.loadDynamicData = function(){
var odbLifeStatus = OB_odb_life.getStatus();
new outbrain_timeout(
function (){
var delta = (new Date().getTime()-self.startTime.getTime());
return ((delta > (self.delay-100)) && (!self.odbSemafor));
},
function(){
self.odbSemafor = true;
var insertInElement;
if (document.getElementsByTagName("head").length > -1){
insertInElement = document.getElementsByTagName("head")[0];
} else {
insertInElement = outbrain_template_manager.getHelperElement();
}
for (var i=0;i<self.odbDynamicCallsArray.length ;i++ ){
if (self.lastOdbRotationRequestedItem > i){
} else {
if (self.odbDynamicCallsArray[i]!=null){
self.insertOdbRequestIntoDom(insertInElement,self.odbDynamicCallsArray[i]);
//self.odbDynamicCallsArray[i]=null;
} else if ((self.supportRecommendations) && (i==0)){
self.odbNextRecReq(i,true);
} else {
var requestUrl,scriptTag;
requestUrl = outbrain_settings.odb.odbGetDataUrlRegular;
requestUrl = self.odbPathReplacer(requestUrl,i);
scriptTag = self.createOdbScriptElement(outbrain_settings.rater.odb.getScoreId + '_' + i,requestUrl,true);
self.insertOdbRequestIntoDom(insertInElement,scriptTag);
}
}
}
self.odbSemafor = false;
self.isLoadDynamicDataOn = false;
},
function (){ self.isLoadDynamicDataOn = false;},
null,
//outbrain_settings.ping.maxTime is the max time the ping run. next variables based on it.
100,
15,
false
);
}
//------------------------------------------------------------------------------------------------------------------------
// extractePermalinkByFooter
// search permalink in blog's footer. footer class can be something the user overrided
this.extractePermalinkByFooter = function(containerDiv){
var retPermalink = null;
var divs = containerDiv.getElementsByTagName("div");
if (self.pmd.postFooterDivClassname != null) {
for (var i=0; i<divs.length && retPermalink == null ; i++){
if (divs[i].parentNode != containerDiv){
continue;
}
var linksArray = divs[i].getElementsByTagName("a");
for (var j=0;j<self.pmd.postFooterDivClassname.length && retPermalink == null ; j++){
var currFooterName = self.pmd.postFooterDivClassname[j];
if (divs[i].className == currFooterName){
for (var k=0; k<linksArray.length; k++){
var a = linksArray[k];
if ((a.title == "permanent link" ) && (a.href != null)) {
if ( a.href != "" ){
self.pmd.postFooterDivClassname = [self.pmd.postFooterDivClassname[j]];
retPermalink = a.href;
break;
}
}
}
}
}
}
}
return retPermalink;
}
//------------------------------------------------------------------------------------------------------------------------
// extractePermalinkByClass
// search permalink by some typical elements class names or by user overrided variable
this.extractePermalinkByClass = function(containerDiv){
var retPermalink = null;
var linksArray = containerDiv.getElementsByTagName("a");
for(var i=0; i<linksArray.length && retPermalink == null ; i++){
var a = linksArray[i];
for (var j=0;j<self.pmd.permaLinkClassName.length;j++){
if ((a.href!=null) && (a.href!="")){
if (a.className == self.pmd.permaLinkClassName[j]){
self.pmd.permaLinkClassName = [self.pmd.permaLinkClassName[j]];
retPermalink = a.href;
break;
}
}
}
}
return retPermalink;
}
//------------------------------------------------------------------------------------------------------------------------
// extractePermalinkByHTag
// search permalink by H tags content (h1..h6);
this.extractePermalinkByHTag = function(containerDiv){
var retPermalink = null;
//Loop over all the possible H tags
var maxHtags = 6;
for (var i=0; i<=maxHtags && retPermalink == null ; i++){
var h = containerDiv.getElementsByTagName("h" + i);
for (var j=0; j<h.length && retPermalink == null; j++){
var linksArray = h[j].getElementsByTagName("a");
for (var k=0;k<linksArray.length; k++){
var a = linksArray[k];
if ((a.href != null) && (a.href != "")){
retPermalink = a.href;
break;
}
}
}
}
return retPermalink;
}
//------------------------------------------------------------------------------------------------------------------------
// extractePermalinkByFirstLink
// get the first link of the post as permalink
this.extractePermalinkByFirstLink = function(containerDiv){
var retPermalink = null;
var linksArray = containerDiv.getElementsByTagName("a");
for (var i=0;i<linksArray.length;i++){
var a = linksArray[i];
if ( (a.href != null) && (a.href != "") ){
retPermalink = a.href;
break;
}
}
return retPermalink;
}
//------------------------------------------------------------------------------------------------------------------------
// outbrainExtractePermalink
// extracte the permalink from containerDiv
this.extractePermalink = function(containerDiv){
if (typeof(containerDiv)=='undefined'){
return null;
}
var returnValue = null;
switch(outbrain_settings.platformType){
case null:
default:
break;
case outbrain_settings.PLATFORM_TYPE_BLOGGER_SIDEBAR:
returnValue = this.extractePermalinkByFooter(containerDiv);
if (returnValue == null){
returnValue = this.extractePermalinkByClass(containerDiv);
if (returnValue == null){
returnValue = this.extractePermalinkByHTag(containerDiv);
if (returnValue == null){
returnValue = this.extractePermalinkByFirstLink(containerDiv);
}
}
}
break;
case outbrain_settings.PLATFORM_TYPE_TYPEPAD:
returnValue = this.extractePermalinkByClass(containerDiv);
break;
case outbrain_settings.PLATFORM_TYPE_TUMBLR:
returnValue = this.extractePermalinkByHTag(containerDiv);
if (returnValue == null){
returnValue = this.extractePermalinkByFirstLink(containerDiv);
}
break;
}
return returnValue;
}
//------------------------------------------------------------------------------------------------------------------------
this.isAllLanguagesPerTemplatesInited = function(){
for (var i=0;i<outbrain_template_manager.templates.length;i++){
var currLang = outbrain_template_manager.templates[i].getLanguageId();
if (!outbrain_language_manager.isLanguageReady(currLang)){
return false;
}
}
return true;
}
//------------------------------------------------------------------------------------------------------------------------
this.createPmd = function(){
var postDivClassname = null;
var permaLinkClassName = null;
var postFooterDivClassname = null;
switch(outbrain_settings.platformType){
case outbrain_settings.PLATFORM_TYPE_BLOGGER_SIDEBAR:
postDivClassname = ["post-body","post-body entry-content","postcontent"];
permaLinkClassName = ["timestamp-link","post-title entry-title"];
postFooterDivClassname = ["post-footer","footer","postfooter"];
break;
case outbrain_settings.PLATFORM_TYPE_TYPEPAD:
postDivClassname = ["entry-more","entry-body"];
permaLinkClassName = ["permalink"];
break;
case outbrain_settings.PLATFORM_TYPE_TUMBLR:
postDivClassname = ["regular"];
// insertInElement here?
break;
case null:
default:
postDivClassname = [outbrain_settings.rater.globalElementClass];
break;
}
if( self.userCustomizeContainerDivClass != null )
postDivClassname = [self.userCustomizeContainerDivClass];
if( self.userCustomizePermaLinkClass != null )
permaLinkClassName = [self.userCustomizePermaLinkClass];
if( self.userCustomizeFooterClass != null )
postFooterDivClassname = [self.userCustomizeFooterClass];
self.pmd = new OB_platformMetaData(postDivClassname,permaLinkClassName,postFooterDivClassname);
}
//------------------------------------------------------------------------------------------------------------------------
this.loadMP = function(){
var userMPFlag = typeof(OB_showMP)=='boolean' ? OB_showMP : false;
if (userMPFlag){
switch(outbrain_settings.platformType){
case outbrain_settings.PLATFORM_TYPE_BLOGGER_SIDEBAR:
case outbrain_settings.PLATFORM_TYPE_TYPEPAD:
case outbrain_settings.PLATFORM_TYPE_TUMBLR:
var MPScript = document.createElement("script");
MPScript.type = outbrain_settings.globals.scriptType;
MPScript.id = outbrain_settings.MP.id;
MPScript.src = outbrain_settings.MP.url;
document.getElementById(outbrain_settings.rater.firstRaterPositionElementId).appendChild(MPScript);
break;
case null:
default:
break;
}
}
}
//------------------------------------------------------------------------------------------------------------------------
// checkNextBrother
// typed can hold two class of content
this.checkNextBrother = function(elementList,elementListIndex,pmdList){
try{
for (p = 0; p < pmdList.postDivClassname.length ; p++ ){
if (elementList[elementListIndex + 1 ].className == pmdList.postDivClassname[p]) return 1;
}
}
catch(e){
return 0;
}
return 0
}
//------------------------------------------------------------------------------------------------------------------------
// dynamicInsertion
// insert the widget dynamic
this.dynamicInsertion = function(){
var elementToSearch = this.elementToSearch;
if (this.halt){
return;
}
new outbrain_timeout(
function(){
return ((outbrain_template_manager != null) && (outbrain_template_manager.templatesListInit) && (self.isAllLanguagesPerTemplatesInited()) && (outbrain_customSettings.ready));
},
function(){
var as = document.getElementsByTagName(elementToSearch);
var isTypepad = ( outbrain_settings.platformType == outbrain_settings.PLATFORM_TYPE_TYPEPAD );
var blockIndex = 0;
for (blockIndex=0;blockIndex<as.length; blockIndex++){
for (var j=0;j<self.pmd.postDivClassname.length ;j++ ){
if(as[blockIndex].className==(self.pmd.postDivClassname[j])){
if ( isTypepad ) {
blockIndex += self.checkNextBrother(as,blockIndex,self.pmd,j);// goto brother when typed involved
}
if (typeof(as[blockIndex].outbrainWidget) == 'boolean') {
break;
}
if (typeof(OB_parentsCount) == 'number'){
try{
postMainDiv = as[blockIndex];
for (var parentsLoop = 0; parentsLoop<OB_parentsCount; parentsLoop++){
postMainDiv = postMainDiv.parentNode;
}
} catch (e){
continue;
}
} else {
var postMainDiv = null;
try {
switch (outbrain_settings.platformType){
case outbrain_settings.PLATFORM_TYPE_TYPEPAD:
postMainDiv = as[blockIndex].parentNode.parentNode;
break;
case outbrain_settings.PLATFORM_TYPE_BLOGGER_SIDEBAR:
postMainDiv = as[blockIndex].parentNode;
break;
case outbrain_settings.PLATFORM_TYPE_TUMBLR:
postMainDiv = as[blockIndex];
break;
default:
postMainDiv = as[blockIndex];
break;
}
} catch (e) {
continue;
}
}
self.countInsertedItems++;
if ((OB_voterWidgetObjArray.length >= self.countInsertedItems) && (typeof(OB_voterWidgetObjArray[self.countInsertedItems]) != 'undefined') && (typeof(OB_voterWidgetObjArray[self.countInsertedItems].permaLink) == 'string')){
var newPosition = self.countInsertedItems;
} else {
var OutbrainPermaLink = self.extractePermalink(postMainDiv);
if (OutbrainPermaLink == null){
self.countInsertedItems--;
continue;
}
//self.countInsertedItems = OB_voterWidgetObjArray.length;
var newPosition = self.countInsertedItems; // the last item is [length-1], so we create the [length] position as the new last position
OB_voterWidgetObjArray[newPosition] = new voterWidgetObj();
OB_voterWidgetObjArray[newPosition].permaLink = OutbrainPermaLink;
}
var widgetBlock = as[blockIndex];
var widgetHTML = outbrain_template_manager.insertDomPerPost(newPosition,widgetBlock);
if (widgetHTML != null){
widgetBlock.outbrainWidget = true;
self.pmd.postDivClassname = [self.pmd.postDivClassname[j]];
outbrain_template_manager.loadRankDataForPost(newPosition);
} else {
self.countInsertedItems--;
}
}
}
}
},
null,
null,
100,
1000,
true
);
if (!this.pageLoaded){
setTimeout(function(){self.dynamicInsertion(elementToSearch);},100);
}
}
//------------------------------------------------------------------------------------------------------------------------
this.reDraw = function(){
/*
if ((typeof(outbrain_rater) == 'undefined') || (typeof(outbrain_rater.userCustomSettingsReady) == 'undefined') || (!outbrain_rater.userCustomSettingsReady())){
setTimeout(function(){self.reDraw()},100);
return;
}
if ((!outbrain_template_manager.templatesListInit) || (!self.isAllLanguagesPerTemplatesInited())){
setTimeout(function(){self.reDraw()},100);
return;
}
for (var i=0;i<OB_voterWidgetObjArray.length;i++ ){
outbrain_template_manager.postDataLoaded(i);
}
*/
}
//------------------------------------------------------------------------------------------------------------------------
// pageLoaded
//
this.pageLoadedEvent = function(draw){
self.pageLoaded = true;
outbrain_customSettings.pageLoaded = true;
if (draw){
this.reDraw();
}
}
//------------------------------------------------------------------------------------------------------------------------
this.waitForCustomSettings = function(){
new outbrain_timeout(
function(){
return (outbrain_customSettings.ready);
},
function(){
self.resetClassNames();
self.createPmd();
outbrain_template_manager.loadTemplates();
self.loadMP();
self.dynamicInsertion();
},
null,
null,
100,
1000,
true
)
}
//------------------------------------------------------------------------------------------------------------------------
// checkInstallationTime
// - check the dates and maybe close open recommandation
this.dateTriggers = function(){
if ( typeof (OBITm) != 'undefined' && typeof (outbrain_settings.timestampDef.activeRecTimestamp) != 'undefined' ){ //is any
if ( !isNaN(parseInt( OBITm ))){
if (parseInt( OBITm ) > outbrain_settings.timestampDef.activeRecTimestamp){
outbrain_settings.timestampDef.installTimestmp = parseInt(OBITm);
OB_showRec = (typeof(OB_showRec) != 'undefined' ) ? OB_showRec : true;
OB_self_posts = (typeof(OB_self_posts) != 'undefined' ) ? OB_self_posts : true;
OB_showMP = (typeof(OB_showMP) != 'undefined' ) ? OB_showMP : true;
}
}
}
}
//------------------------------------------------------------------------------------------------------------------------
// firstRater
// call when the user / the dynamic insertion want to insert the first rater
this.firstRater = function(){
self.dateTriggers();
this.isRunning = true;
var waitForLoad = (typeof(OB_waitForLoad) == 'boolean')? OB_waitForLoad:false;
if (!waitForLoad){
this.reDraw();
}
if (window.addEventListener){ //DOM method for binding an event
window.addEventListener("load", function(){self.pageLoadedEvent(waitForLoad);}, false)
} else if (window.attachEvent){ //IE exclusive method for binding an event
window.attachEvent("onload", function(){self.pageLoadedEvent(waitForLoad);})
} else if (document.getElementById){ //support older modern browsers
window.onload=function(){self.pageLoadedEvent(waitForLoad);}
}
document.write ("<span id='"+outbrain_settings.rater.firstRaterPositionElementId+"'></span>");
// load user custom settings
this.waitForCustomSettings();
}
//------------------------------------------------------------------------------------------------------------------------
// insertGlobalSpan
// logically, this function may be part of the template manager, but it (the template manager) create only when we have custom settings and we need to create this span we no delay, so it is in the rater object
this.insertGlobalSpan = function(index,toReturn){
var globalSpan = '';
var elementName = this.elementToSearch;
if (toReturn){
globalSpan = document.createElement(elementName);
globalSpan.className = outbrain_settings.rater.globalElementClass;
return globalSpan;
} else {
document.write ("<" + elementName + " class='"+outbrain_settings.rater.globalElementClass+"'></" + elementName + ">");
}
}
//------------------------------------------------------------------------------------------------------------------------
// insertRater
//
this.insertRater = function(){
if (!this.halt){
// In cases where the platform should indicate automatic rater insertion, any farther call to insert rater should be discarded
if( (! this.isRunning && typeof(OB_platformType) == 'number')
|| typeof(OB_platformType) != 'number' ){
if ( OB_voterWidgetObjArray.length == 0 ){
this.firstRater();
}
if (typeof(OutbrainPermaLink) == 'string'){
var newPosition = OB_voterWidgetObjArray.length; // the last item is [length-1], so we create the [length] position as the new last position
OB_voterWidgetObjArray[newPosition] = new voterWidgetObj();
OB_voterWidgetObjArray[newPosition].permaLink = OutbrainPermaLink;
//TODO:: What the hell is this span thing?.... check to remove it!!!!
this.elementToSearch = "span";
this.insertGlobalSpan(newPosition,false);
}
//var permalinkGiven = typeof(OutbrainPermaLink) == 'string'
}
}
}
//------------------------------------------------------------------------------------------------------------------------
// rate
//
this.rate = function(templateIndex,index,rateValue){
var widgetObject = OB_voterWidgetObjArray[index];
if (widgetObject.rankInfo == null){
return false;
}
if (this.lockRater(index)){
return;
}
var rate = "?s=" + rateValue;
//var dId = (typeof(widgetObject.jsonObj.response.request.did) == 'string')? widgetObject.jsonObj.response.request.did:null;
var permaLink = "&u=" + encodeURIComponent(OB_voterWidgetObjArray[index].permaLink);
var version = "&v=" + outbrain_settings.versions.odb;
var agent = "";
var partner = "";
var rdid = "";
var user = "";
if (outbrain_settings.keys_and_users.agentId != null){
agent = "&a=" + encodeURIComponent(outbrain_settings.keys_and_users.agentId);
}
if (outbrain_settings.keys_and_users.partnerName != null){
partner = "&p=" + encodeURIComponent(outbrain_settings.keys_and_users.partnerName);
}
if (typeof(OB_rfdid) == 'string'){
rdid = OB_rfdid;
} else if (this.getQSParam("rfdid") != null){
rdid = this.getQSParam("rfdid");
}
if (rdid != ""){
rdid = "&rfdid=" + rdid;
}
if (outbrain_settings.keys_and_users.userName != null){
user = "&e=" + outbrain_settings.keys_and_users.userName;
}
var random = "&r=" + Math.random();
var imgSrc = outbrain_settings.odb.odbRatesRecorder;
imgSrc += rate + permaLink + version + agent + partner + rdid + user + random;
// rate
outbrain_template_manager.doRate(templateIndex,index,imgSrc);
OB_voterWidgetObjArray[index].rankInfo.vote = rateValue;
// update counters
if (!OB_voterWidgetObjArray[index].rated){
OB_voterWidgetObjArray[index].rankInfo.ratedBy++;
OB_voterWidgetObjArray[index].rankInfo.wratedBy++;
}
// user rated
OB_voterWidgetObjArray[index].rated = true;
// callback
outbrain_template_manager.userRated(index);
}
this.initOnlyWithTemplates = function(){
self.supportRecommendations = outbrain_template_manager.isThereTemplateWithRecommendations();
}
this.resetClassNames = function(){
self.userCustomizeContainerDivClass = (typeof(OB_containerClass) == 'string') ? OB_containerClass : null;
self.userCustomizePermaLinkClass = (typeof(OB_permaLinkClass) == 'string') ? OB_permaLinkClass : null;
self.userCustomizeFooterClass = (typeof(OB_footerClass) == 'string') ? OB_footerClass : null;
}
this.init = function(){
self.resetClassNames();
self.halt = ((typeof(OB_Halt)=='boolean')? OB_Halt : false);
}
this.init();
}
//------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
// outbrain_rater_object end
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
var OB_platformMetaData = typeof(OB_platformMetaData) == "function" ? OB_platformMetaData : function(postDivClassname_,permaLinkClassName_,postFooterDivClassname_){
this.postDivClassname = postDivClassname_;
this.permaLinkClassName = permaLinkClassName_;
this.postFooterDivClassname = postFooterDivClassname_;
}
//------------------------------------------------------------------------------------------------------------------------
var voterWidgetObj = typeof(voterWidgetObj) == "object" ? voterWidgetObj : function(){
this.frezz = false;
this.rateMode = outbrain_settings.rater.statuses.RATER_PRE_RATE_MODE;
this.frezzSemaphore = 0;
this.rateScore = 0;
this.ratedBy = 0;
this.wratedBy = 0.0;
this.isPersonalized = false;
this.userName = "";
this.jsonObj = null;
this.mainDiv = null;
this.currentRateValue = 1
this.rankInfo = null;
this.permaLink = null;
this.rated = false;
this.rateInfo = "";
this.rateStatus = "";
this.rateInfo = "";
this.rankInfo_object = function(ranke_,ratedBy_,wratedBy_,user_){
this.user = user_;
this.rank = Number(ranke_);
this.ratedBy = Number(ratedBy_);
this.wratedBy = Number(wratedBy_);
this.vote = 0;
this.personalRank = 0;
this.personalRatedBy = 0;
this.getComputedRank = function(isAvrage){
if (this.ratedBy == 0 ){
return 0;
}
var res = 0;
res = (this.personalRank!=0 && (typeof(isAvrage)=='undefined')) ? this.personalRank : (this.rank+Number(this.vote))/this.wratedBy;
return outbrain_language_manager.changeX(null,res);
}
this.getPersonalRateIndex = function(){
var rank = this.getComputedRank();
var rankAvg = this.getComputedRank(true);
var personalIndex = (rank < 2.5 && rank > 0)? 0 : (rank > 2.5 && rank < 4 ? 1 : 2);
if ((personalIndex == 2) && rankAvg > rank){
personalIndex = 1;
}
return personalIndex;
}
}
}
//------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
// prototypes
//outbrain_template_object.prototype = new outbrain_rater_settings_object();
//outbrain_template_manager_object.prototype = new outbrain_rater_settings_object();
// objects
//var outbrain_browsers = ((typeof(outbrain_browsers) == 'object')? outbrain_browsers : (new outbrain_browsers_object()));
//var outbrain_settings = ((typeof(outbrain_settings) == 'object')? outbrain_settings : (new outbrain_settings_object()));
var outbrain_dom = ((typeof(outbrain_dom) == 'object')? outbrain_dom : (new outbrain_dom_object()));
var outbrain_language_manager = ((typeof(outbrain_language_manager) == 'object')? outbrain_language_manager: (new outbrain_language_manager_object()));
var outbrain_template_manager = ((typeof(outbrain_template_manager) == 'object')? outbrain_template_manager: (new outbrain_template_manager_object())); // create and hand the templates objects
var OB_odb_life = ((typeof(OB_odb_life) == 'object')? OB_odb_life : null);
if (OB_odb_life == null){
OB_odb_life = new outbrain_odb_life_object(outbrain_settings.ping.maxTime,outbrain_settings.ping.url,outbrain_settings.ping.id);
}
var outbrain_customSettings = ((typeof(outbrain_customSettings) == 'object')? outbrain_customSettings : new outbrain_customSettings_object());
var outbrain_rater = ((typeof(outbrain_rater) == 'object')? outbrain_rater : (new outbrain_rater_object()));
//------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
function OutbrainStart(){
outbrain_rater.insertRater();
}
//if ((typeof(OB_dont_call_me_I_call_you) != 'boolean') || (!OB_dont_call_me_I_call_you)){
OutbrainStart();
//}
ASKER
ASKER
JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and in almost every mainstream web browser.
TRUSTED BY