baynote_globals.TagsURLPrefix="/baynote/tags3/";baynote_globals.CustomScript="customScript";baynote_globals.GuideSet="GuideSet";baynote_globals.ScriptWebapp="r";baynote_globals.ScriptResourceId="Custom";baynote_globals.guideContainerId="baynote_guides";baynote_globals.DefaultCookieAge=10*365*24*60*60*1000;baynote_globals.WindowNameDelimBegin="bAyNoTe>-";baynote_globals.WindowNameDelimEnd="-';};BNTag.prototype.getTotalPurchases=function(){if(typeof(bnOrderId)!="undefined"&&bnCommon.isNotEmpty(bnOrderId)) this.attrs.purchaseId=bnOrderId;if(typeof(bnOrderTotal)!="undefined"&&bnCommon.isNotEmpty(bnOrderTotal)) this.attrs.totalPurchases=parseFloat(bnOrderTotal);if(typeof(bnOrderDetails)!="undefined"&&bnCommon.isNotEmpty(bnOrderDetails)) this.attrs.purchaseDetails=bnOrderDetails;};BNCommon=function(){};BNCommon.prototype.stringToBoolean=function(str){if(!str)return false;str=str.toLowerCase();if(str==""||str=="false"||str=="f"||str=="0"||str=="no"||str=="n")return false;return true;};BNCommon.prototype.copyObj=function(obj,props){var newObj=new Object();for(var prop in obj){var child=obj[prop];if(typeof(child)=="undefined"||typeof(child)=="function")continue;if(child!=null)newObj[prop]=child;} return newObj;};BNCommon.prototype.copyProperties=function(src,dst,props){for(var i=0;iMAX_DUMP_DEPTH){return indent+name+": -Maximum Depth Reached-"+ret;} if(typeof obj=="object"){var child=null;var output=name?(indent+name+ret):"";indent+=ind;var numFunctions=0;for(var item in obj){try{child=obj[item];}catch(e){child="-Unable to Evaluate-";} if(child==null)output+=indent+item+": "+ret;else if(typeof child=="function")++numFunctions;else if(typeof child=="object")output+=this.dumpObj(child,item,indent,depth+1,asHTML);else output+=indent+item+": "+child+ret;} if(numFunctions>0)output+=indent+"<"+numFunctions+" function(s)>"+ret;return output;}else return obj;};BNCommon.prototype.dump=function(obj){return this.dumpObj(obj,""," ",5,false);};BNCommon.prototype.dumpHTML=function(obj){return this.dumpObj(obj,""," ",5,true);};BNCommon.prototype.getURLParams=function(url){if(!url)var url=window.location.href;var urlParams=new Object();var tmp=url.split("?");if(tmp.length>1&&tmp[1]!=""){tmp=tmp[1];tmp=tmp.split("#");tmp=tmp[0];var params=tmp.split("&");var nameValuePair;for(var i=0;i=0){baseUrl=url.substring(0,anchorIndex);if(baseUrl=="")return url;baseUrlLength=baseUrl.length;anchor=url.substring(anchorIndex,urlLength);} var lastChar=baseUrl.charAt(baseUrlLength-1);if(lastChar=='?'||lastChar=='&'){insertedChar=null;}else if(baseUrl.indexOf('?')>=0){insertedChar='&';}else{insertedChar='?';} newUrl.append(baseUrl);if(insertedChar)newUrl.append(insertedChar);newUrl.append(paramName);newUrl.append('=');newUrl.append(value);if(anchor)newUrl.append(anchor);return newUrl.toString();};BNCommon.prototype.addURLMetaKeys=function(url,metaKeyList){if(!metaKeyList)return url;var newUrl=url;var metaKeys=metaKeyList.split(",");for(var i=0;itag.bnProxyPrefix.length){return url.substring(tag.bnProxyPrefix.length,url.length);} return url;};BNCommon.prototype.arrayToJSON=function(arr){var a=['['],b,i,l=arr.length,v;function p(s){if(b){a.push(',');} a.push(s);b=true;} for(i=0;i='0'&&ch<='9'){string+=ch;next();} if(ch==='.'){string+='.';while(next()&&ch>='0'&&ch<='9'){string+=ch;}} if(ch==='e'||ch==='E'){string+=ch;next();if(ch==='-'||ch==='+'){string+=ch;next();} while(ch>='0'&&ch<='9'){string+=ch;next();}} number=+string;if(!isFinite(number)){error("Bad number");}else{return number;}},string=function(){var hex,i,string='',uffff;if(ch==='"'){while(next()){if(ch==='"'){next();return string;}else if(ch==='\\'){next();if(ch==='u'){uffff=0;for(i=0;i<4;i+=1){hex=parseInt(next(),16);if(!isFinite(hex)){break;} uffff=uffff*16+hex;} string+=String.fromCharCode(uffff);}else if(typeof escapee[ch]==='string'){string+=escapee[ch];}else{break;}}else{string+=ch;}}} error("Bad string");},white=function(){while(ch&&ch<=' '){next();}},word=function(){switch(ch){case't':next('t');next('r');next('u');next('e');return true;case'f':next('f');next('a');next('l');next('s');next('e');return false;case'n':next('n');next('u');next('l');next('l');return null;} error("Unexpected '"+ch+"'");},value,array=function(){var array=[];if(ch==='['){next('[');white();if(ch===']'){next(']');return array;} while(ch){array.push(value());white();if(ch===']'){next(']');return array;} next(',');white();}} error("Bad array");},object=function(){var key,object={};if(ch==='{'){next('{');white();if(ch==='}'){next('}');return object;} while(ch){key=string();white();next(':');if(Object.hasOwnProperty.call(object,key)){error('Duplicate key "'+key+'"');} object[key]=value();white();if(ch==='}'){next('}');return object;} next(',');white();}} error("Bad object");};value=function(){white();switch(ch){case'{':return object();case'[':return array();case'"':return string();case'-':return number();default:return ch>='0'&&ch<='9'?number():word();}};return function(source,reviver){var result;text=source;at=0;ch=' ';result=value();white();if(ch){error("Syntax error");} return typeof reviver==='function'?(function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}} return reviver.call(holder,key,value);}({'':result},'')):result;};}());BNCommon.prototype.trim=function(str){if(!str)return str;while(str.charAt(0)==" "||str.charAt(0)=="\n"||str.charAt(0)=="\t") str=str.substring(1);while(str.charAt(str.length-1)==" "||str.charAt(str.length-1)=="\n"||str.charAt(str.length-1)=="\t") str=str.substring(0,str.length-1);return str;};BNCommon.prototype.stripExtraQuotes=function(s){var t=s.length;if(s.charAt(0)=='"'){s=s.substring(1,t--);} if(s.charAt(--t)=='"'){s=s.substring(0,t);} return s;};BNCommon.prototype.getInnerText=function(obj){if(obj.innerText)return obj.innerText;else{var text="";switch(obj.nodeType){case 1:for(var i=0;i0)title=metas[0].content;if(!title)title=document.title;} this.title=title?title:"";};BNPageInfo.prototype.checkIf404=function(){this.iAm404=false;var metas=document.getElementsByName(bnConstants.META_PAGE_STATUS);if(metas&&metas.length>0){var status=parseInt(metas[0].content);if(status==404)this.iAm404=true;}};BNPageInfo.prototype.checkWordCount=function(){if(typeof(baynote_globals)!="undefined"&&baynote_globals.skipWordCount){this.wordCount=-1;return;} if(!document.body){this.wordCount=-1;this.linkCount=-1;setTimeout("bnPageInfo.checkWordCount()",200);return;} this.wordCount=null;var bodyTags=document.getElementsByTagName("body");if(bodyTags.length==0)return;var bodyText=bnCommon.getInnerText(bodyTags[0]);var wordCountRE=new RegExp("\\S+","g");var words=bodyText.match(wordCountRE);if(!words)this.wordCount=0;else this.wordCount=words.length;};BNPageInfo.prototype.checkLinkCount=function(){if(typeof(baynote_globals)!="undefined"&&baynote_globals.skipLinkCount){this.linkCount=-1;return;} this.linkCount=null;var linkTags=document.getElementsByTagName("a");if(!linkTags)this.linkCount=0;else this.linkCount=linkTags.length;};BNPageInfo.prototype.getWindowName=function(){return window.name;};BNPageInfo.prototype.getWordCount=function(){return this.wordCount;};BNPageInfo.prototype.getLinkCount=function(){return this.linkCount;};BNPageInfo.prototype.getTitle=function(){return this.title;};BNPageInfo.prototype.is404=function(){return this.iAm404;};BNPageInfo.prototype.cookiesAreEnabled=function(){if(typeof(baynote_globals)!="undefined"&&baynote_globals.cookiesDisabled)return false;else return true;};BNPageInfo.prototype.getURL=function(){return this.url;};BNPageInfo.prototype.getFullURL=function(){return this.fullUrl;};BNPageInfo.prototype.getURLParams=function(){return this.urlParams;};BNPageInfo.prototype.getURLParam=function(paramName){return this.urlParams[paramName];};BNPageInfo.prototype.getBNParams=function(){return this.bnParams;};BNPageInfo.prototype.getBNParam=function(paramName){return this.bnParams[paramName];};BNPageInfo.prototype.getReferrerURL=function(){if(!this.referrer)return null;return this.referrer.url;};BNPageInfo.prototype.isBinary=function(url){if(!url)return false;if(url.match(/^[^?]*\.(pdf|doc|xls|ppt)(\?.*)?$/i))return true;if(url.match(/^.*\/m?getfile\?.*$/i))return true;return false;};bnPageInfo=new BNPageInfo();BNUser=function(){this.userId=null;this.extUserId=null;var extUserId=bnCommon.getCookieValue(baynote_globals.ExternalUserIdCookieName);var userFromURL=this.getUserFromURL();if(userFromURL){this.setUserId(userFromURL);return;} var oldUserId=bnCommon.getCookieValue("_baynote_anon_user");if(oldUserId){this.setUserId(oldUserId);bnCommon.removeCookie("_baynote_anon_user");return;} var userId;if(baynote_globals.UseWindowName){userId=this.readUserCookieFromWindowName();} if(!userId){userId=bnCommon.getCookieValue("bn_u");if(baynote_globals.UseWindowName&&userId){this.writeUserCookieToWindowName(userId);}} if(userId){this.setUserId(userId,true);return;} this.setUserId(bnConstants.UNASSIGNED_USER_ID);userId=bnCommon.getCookieValue("bn_u");if(!userId)this.setUserId(bnConstants.ANONYMOUS_USER_ID,true);};BNUser.prototype.getUserFromURL=function(){var userParam=bnPageInfo.getBNParam("bn_u");var user=null;if(userParam!=null){if(userParam=="")user=bnConstants.UNASSIGNED_USER_ID;else user=userParam;} return user;};BNUser.prototype.getUserId=function(tag){if(tag&&tag.userId)return tag.userId;return this.userId;};BNUser.prototype.getExtUserId=function(){return this.extUserId;};BNUser.prototype.setUserId=function(userId,skipWrite){if(bnPageInfo.cookiesAreEnabled()&&!skipWrite){if(baynote_globals.UseWindowName){this.writeUserCookieToWindowName(userId);} this.writeUserCookie(userId);} this.userId=userId;};BNUser.prototype.setExtUserId=function(extUserId){if(bnPageInfo.cookiesAreEnabled()){this.writeExtUserCookie(extUserId);} this.extUserId=extUserId;};BNUser.prototype.resetExtUserId=function(){if(bnPageInfo.cookiesAreEnabled()){bnCommon.removeCookie(baynote_globals.ExternalUserIdCookieName);} this.extUserId=null;};BNUser.prototype.readUserCookieFromWindowName=function(){var cky;var re=new RegExp(baynote_globals.WindowNameDelimBegin+"({.*})"+ baynote_globals.WindowNameDelimEnd);var m=re.exec(window.name);var custCodeKey=baynote_tag.customerId+'_'+baynote_tag.code;if(m!=null){var mapStr=RegExp.$1;var ckObj=bnCommon.parseJSON(mapStr);var currCkMap=ckObj[custCodeKey];if(currCkMap){cky=currCkMap["bn_u"];}} return cky;};BNUser.prototype.writeUserCookieToWindowName=function(userId){var re=new RegExp(baynote_globals.WindowNameDelimBegin+"({.*})"+ baynote_globals.WindowNameDelimEnd);var m=re.exec(window.name);var custCodeKey=baynote_tag.customerId+'_'+baynote_tag.code;var ckObj,remaining="";if(m!=null){var mapStr=RegExp.$1;ckObj=bnCommon.parseJSON(mapStr);var currCkMap=ckObj[custCodeKey]||{};currCkMap["bn_u"]=userId;ckObj[custCodeKey]=currCkMap;remaining=window.name.replace(re,'');}else{ckObj={};ckObj[custCodeKey]={"bn_u":userId};remaining=window.name;} var newCookieStr=baynote_globals.WindowNameDelimBegin +bnCommon.objectToJSON(ckObj) +baynote_globals.WindowNameDelimEnd;window.name=newCookieStr+remaining;};BNUser.prototype.reWriteUserCookie=function(){this.writeUserCookie(this.userId);};BNUser.prototype.writeUserCookie=function(userId){this.writeCookie("bn_u",userId);};BNUser.prototype.writeExtUserCookie=function(userId){this.writeCookie(baynote_globals.ExternalUserIdCookieName,userId);};BNUser.prototype.writeCookie=function(name,val){var cookieExpires=this.getDefaultCookieExpiry();bnCommon.setCookie(name,val,"/",cookieExpires);};BNUser.prototype.getDefaultCookieExpiry=function(){var age=baynote_globals.DefaultCookieAge;if(typeof bnPolicy!='undefined'){age=parseFloat(bnPolicy.userCookieAge)*1;} var currTimestamp=new Date();var currTime=currTimestamp.getTime();currTimestamp.setTime(currTime+age);return currTimestamp.toGMTString();};bnUser=new BNUser();BNPolicy=function(){this.data=null;this.overrides=null;this.userId=null;this.disableAll=bnPageInfo.getBNParam("bn_disable");this.customScriptPresent=false;this.elementIds=null;this.userCookieAge=null;};BNPolicy.prototype.get=function(pId,param){if(!pId)return this.data;if(!this.data)return null;if(!param)return this.data[pId];if(!this.data[pId])return null;return this.data[pId][param];};BNPolicy.prototype.getCondition=function(tag){var origCondition=this.get("inf","cd");if(tag&&tag.conditionName){return origCondition.replace(/^([0-9]+)[.]([A-Z]+)(.*)/,"$1."+tag.conditionName+"$3");} return origCondition;};BNPolicy.prototype.getOverride=function(pId){if(!pId)return this.overrides;if(!this.overrides)return null;return this.overrides[pId];};BNPolicy.prototype.allowTag=function(tag){if(this.disableAll)return false;var pTag=this.get(tag.type);if(!pTag)return true;if(tag.type==bnConstants.GUIDE_TAG&&BNThor.getInjectPolicy()===BNThor.Constants.THOR_INJECT_POLICY){return false;} if(typeof(pTag.ok)=="undefined")return true;if(!pTag.ok){if(typeof(pTag.load)=="undefined")return false;else return pTag.load;} return pTag.ok;};BNPolicy.prototype.showTag=function(tag){if(this.disableAll)return false;var pTag=this.get(tag.type);if(!pTag)return true;if(typeof(pTag.ok)=="undefined")return true;return pTag.ok;};BNPolicy.prototype.isNew=function(){return this.isNewPolicy;};BNPolicy.prototype.getGuideElementIds=function(){return this.elementIds;};BNPolicy.prototype.load=function(server,custName,custCode,userId,policyFormat){this.userId=userId;var needUserPolicy=true;bnResourceManager.loadResource(bnConstants.POLICY_RESOURCE_ID,this.getPolicyResourceAddress(server,custName,custCode,userId,needUserPolicy,policyFormat));};BNPolicy.prototype.useExternalId=function(externalId,remove){var needUserPolicy=true;var s=baynote_tag.server;var cn=baynote_tag.customerId;var cc=baynote_tag.code;var u=bnUser.getUserId();var extId=remove?null:externalId;bnResourceManager.removeResource(bnConstants.POLICY_RESOURCE_ID);bnResourceManager.loadResource(bnConstants.POLICY_RESOURCE_ID,this.getPolicyAddressForExtUserId(s,cn,cc,u,needUserPolicy,extId));};BNPolicy.prototype.initJsonPolicy=function(jsonPolicy){var policiesObj=bnCommon.parseJSON(jsonPolicy);if(policiesObj){var basePolicy=policiesObj.basePolicyJSON;var userPolicy=policiesObj.userPolicyJSON;this.registerPolicyObjects(basePolicy,userPolicy);}else{this.registerPolicyObjects(new Object(),null);}} BNPolicy.prototype.registerPolicy=function(basePolicyJsonStr,userPolicyJsonStr){var basePolicy=bnCommon.parseJSON(basePolicyJsonStr);var userPolicy=bnCommon.parseJSON(userPolicyJsonStr);this.registerPolicyObjects(basePolicy,userPolicy);} BNPolicy.prototype.registerPolicyObjects=function(basePolicy,userPolicy){this.data=(basePolicy)?basePolicy:new Object();if(userPolicy){for(var category in userPolicy){if(typeof(userPolicy[category])=="function")continue;for(var paramName in userPolicy[category]){if(typeof(userPolicy[category][paramName])=="function")continue;this.setPolicyData(this.data,category,paramName,userPolicy[category][paramName]);}}} this.overrides=this.computeOverrides();this.applyOverrides(this.overrides);this.userCookieAge=this.get(bnConstants.OBSERVER_TAG,"uca");this.applyDirectives();this.customScriptPresent=this.get(baynote_globals.CustomScript,"hn")!=null;this.elementIds=this.get(baynote_globals.GuideSet,"eids");bnResourceManager.registerResource(bnConstants.POLICY_RESOURCE_ID);} BNPolicy.prototype.getPolicyResourceAddress=function(server,custName,custCode,userId,needUserPolicy,policyFormat){var subDomain=(typeof(baynote_globals)!="undefined"&&baynote_globals.cookieSubDomain)?baynote_globals.cookieSubDomain:"";var dataFormat=(policyFormat)?policyFormat:"script";return(server+baynote_globals.TagsURLPrefix+"policy?customerId="+custName+"&code="+custCode +"&subdomain="+subDomain+"&userId="+userId+"&userPolicyRequested="+needUserPolicy +"&dataFormat="+dataFormat);};BNPolicy.prototype.getPolicyAddressForExtUserId=function(server,custName,custCode,userId,needUserPolicy,extUId){var subDomain="";if(typeof(baynote_globals)!="undefined"&&baynote_globals.cookieSubDomain) subDomain=baynote_globals.cookieSubDomain;if(extUId){return(server+baynote_globals.TagsURLPrefix+"policy?customerId=" +custName+"&code="+custCode+"&subdomain="+subDomain +"&userId="+userId +"&extUserId="+extUId +"&ts="+(new Date().getTime()) +"&userPolicyRequested="+needUserPolicy);} return(server+baynote_globals.TagsURLPrefix+"policy?customerId=" +custName+"&code="+custCode+"&subdomain="+subDomain +"&userId="+bnConstants.UNASSIGNED_USER_ID +"&ts="+(new Date().getTime()) +"&userPolicyRequested="+needUserPolicy);};BNPolicy.prototype.importData=function(jsonStr){var data=bnCommon.parseJSON(jsonStr);if(!data)data=new Object();return data;};BNPolicy.prototype.applyOverrides=function(overrideData){if(!overrideData)return;for(var cat in overrideData){if(typeof(overrideData[cat])=="function")continue;for(var key in overrideData[cat]){if(typeof(overrideData[cat][key])=="function")continue;this.setPolicyData(this.data,cat,key,overrideData[cat][key]);}} var testServer=bnSystem.getTestServer();if(testServer){this.setPolicyData(overrideData,"inf","server",testServer);}};BNPolicy.prototype.computeTagOverrides=function(){var tagOverrides=new Object();var bn_ov=typeof(baynote_globals)!="undefined"?baynote_globals.bn_ov:null;if(bn_ov){var categories=bn_ov.split(";");for(var i=0;i0);event.pageX=event.clientX+document.body.scrollLeft;event.pageY=event.clientY+document.body.scrollTop;event.target=event.srcElement;event.time=(new Date).getTime();if(event.type=="mouseout")event.relatedTarget=event.toElement;else if(event.type=="mouseover")event.relatedTarget=event.fromElement;event.preventDefault=function(){this.returnValue=false;} event.stopPropagation=function(){this.cancelBubble=true;} return event;};bnEvent=new BNEvent();BNTrail=function(){this.data=new Array();this.initialized=false;};BNTrail.prototype.initialize=function(maxLength){this.maxLength=maxLength;this.load();this.initialized=true;};BNTrail.prototype.getUrls=function(maxLength){if(!this.initialized)this.initialize(maxLength);return this.data;};BNTrail.prototype.addUrl=function(url,maxLength,sessionOnly){if(!this.initialized)this.initialize(maxLength);var index=this.getIndex(url);if(index!=-1&&this.data.length>0){if(index==(this.data.length-1))return;if(index!=-1)this.data.splice(index,1);} if(typeof baynote_globals.canAddTrailUrl==='function'){if(!baynote_globals.canAddTrailUrl(url)){return;}} this.data.push(url);this.crop();this.save(sessionOnly);};BNTrail.prototype.crop=function(){if(this.data.length>this.maxLength){var numSplice=this.data.length-this.maxLength;this.data.splice(0,numSplice);}};BNTrail.prototype.getIndex=function(url){for(i=0;i '+message;this.localLogCtr+=1;}};BNLogger.prototype.log=function(logLevel,subSystem,message){if(!bnCommon.isString(logLevel)){this.localLog('BNLogger.log(): Given message log level is not a string');return;}else if(!bnCommon.isString(subSystem)){this.localLog('BNLogger.log(): Given message subsystem is not a string');return;}else if(!bnCommon.isString(message)){this.localLog('BNLogger.log(): Given message is not a string');return;} if(!this.logLevelIsSufficientForLogging(logLevel))return;this.getLogQueue().push({logl:logLevel,msg:message,ss:subSystem,t:new Date().getTime()});};BNLogger.prototype.debug=function(subSystem,message){this.log("DEBUG",subSystem,message);};BNLogger.prototype.info=function(subSystem,message){this.log("INFO",subSystem,message);};BNLogger.prototype.warn=function(subSystem,message){this.log("WARN",subSystem,message);};BNLogger.prototype.error=function(subSystem,message){this.log("ERROR",subSystem,message);};BNLogger.prototype.logLevelIsSufficientForLogging=function(logLevel){if(!bnCommon.isString(logLevel)){this.localLog('BNLogger.logLevelIsSufficientForLogging(): Given log level not a String');return false;} logLevel=this.normalizeLogLevelName(logLevel);if(!bnCommon.isNumber(BNLogger.LOG_LEVELS[logLevel])){this.localLog('BNLogger.logLevelIsSufficientForLogging(): Given log level unrecognized');return false;} return(BNLogger.LOG_LEVELS[logLevel]>=BNLogger.LOG_LEVELS[this.getLogLevel()]);};BNLogger.prototype.send=function(){var newIdNum,log,baseUrl,url,logJSON,logQueue;baseUrl=this.getLoggingUrl();logQueue=this.getLogQueue();if((baseUrl===BNLogger.STUB_URL)||(logQueue.length===0)){return;} newIdNum=this.rId++;logJSON={uid:this.getUserId(),d:bnPageInfo.getURL(),msgs:logQueue};log=encodeURIComponent(bnCommon.valueToJSON(logJSON));url=baseUrl+'?customerId='+this.getCustomerName()+'&code='+this.getCustomerCode()+'&logId='+newIdNum+'&len='+log.length+'&log='+log+'&v='+ BNLogger.MESSAGE_FORMAT_VERSION;this.injectMessages(url);this.logQueue=[];};BNLogger.prototype.injectMessages=function(url){var img,ph;if(typeof url!=='string'){this.localLog('BNLogger.injectMessages(): Given url is not a string');} img=document.createElement("IMG");ph=document.getElementsByTagName('body')[0];img.src=url;img.style.display="none";setTimeout(function(){if(ph!=null)ph.appendChild(img);},5);};var bnLogger;bnResourceManager.waitForResource(bnConstants.POLICY_RESOURCE_ID,function(){bnLogger=new BNLogger({loggingUrl:bnPolicy.get('logging','url'),logLevel:bnPolicy.get('logging','logLevel')});});BNThor=(function(){var ERROR_MSG_CODES={UNEXPECTED:"rec.unexpected",NO_WEB_IDS_FOUND:"rec.nowebids",REC_REQUEST_NO_PAGE_TYPES_FOUND:"rec.request.nopagetypes",INVALID_REC_RESPONSE:"rec.response.invalid",REC_RESPONSE_PARSE_FAIL:"rec.response.parsefail",REC_RESPONSE_MISSING_REQUIRED_VALS:"rec.response.missingrequiredvals",REC_SECURITY_CHECK_FAIL:"rec.response.securityfail",REC_AJAX_FAILURE:"rec.ajax.fail",MERCH_RESPONSE_PARSE_FAIL:"merch.response.parsefail",MERCH_AJAX_FAILURE:"merch.ajax.fail",INVALID_MERCH_RESPONSE:"merch.response.invalid",INIT_NOT_PERFORMED:"init.notperformed",INIT_MISSING_REQUIRED_VALS:"init.missingrequiredvals",INIT_MISSING_REQUIRED_LIB:"init.missingrequiredlib",PAGETYPE_UNEXPECTED_WARNING:"pagetype.warning",PAGETYPE_NOT_FOUND:"pagetype.not.found",PAGETYPE_NOT_EXACT:"pagetype.not.exact"};var ThorConstants={PAGE_TEMPLATE_ATTR_NAME:"data-baynote-page-template",REC_INFO_ATTR_NAME:"data-baynote",REC_INFO_WIDGET_ATTR_NAME:"data-baynote-widget",REC_INFO_SLOT_ATTR_NAME:"data-baynote-slot",REC_INFO_PID_ATTR_NAME:"data-baynote-pid"};var customerName="",customerCode="",contextUrl="",isInitialized=false,initError=null,recServerUrlPrefix="",merchServerUrlPrefix="",thor_inject=false,logger=null,trackingData=null,pageType=null,pageTemplate=null,contextConfig,injectPolicy="";var Widget=function(name,placeholderName,displayName,algo,recJsonObj){this.name=name;this.placeholderName=placeholderName;this.displayName=displayName;this.algo=algo;this.recData=recJsonObj;};var RenderingContext=function(config){this.requestFullUrl=config.requestFullUrl||"";this.widgets=config.widgets||[];};RenderingContext.prototype.addWidget=function(widgetObj){if(widgetObj instanceof Widget){this.widgets.push(widgetObj);}else if(BN$.isArray(widgetObj)){this.widgets.push.apply(this.widgets,widgetObj);}};var InitError=function(detailsData){this.detailsData=detailsData||{code:ERROR_MSG_CODES.UNEXPECTED,msg:"No details available"};};InitError.prototype.toString=function(){return basicErrorDetailsToString(this.detailsData);};var ContextRetrievalError=function(detailsData){this.detailsData=detailsData||{code:ERROR_MSG_CODES.UNEXPECTED,msg:"No details available"};} ContextRetrievalError.prototype.toString=function(){return basicErrorDetailsToString(this.detailsData);};var RecResponseStructureError=function(detailsData){this.detailsData=detailsData||{code:ERROR_MSG_CODES.UNEXPECTED,msg:"No details available"};};RecResponseStructureError.prototype.toString=function(){return basicErrorDetailsToString(this.detailsData);};var RecRequestFormationError=function(detailsData){this.detailsData=detailsData||{code:ERROR_MSG_CODES.UNEXPECTED,msg:" No details available"};};RecRequestFormationError.prototype.toString=function(){return basicErrorDetailsToString(this.detailsData);};var RecResponseSecurityError=function(detailsData){this.detailsData=detailsData||{code:ERROR_MSG_CODES.UNEXPECTED,msg:" No details available"};};RecResponseSecurityError.prototype.toString=function(){return basicErrorDetailsToString(this.detailsData);};var PageTypeDeducingWarning=function(detailsData){this.detailsData=detailsData||{code:ERROR_MSG_CODES.PAGETYPE_UNEXPECTED_WARNING,msg:" Page Type deducing error happened. No details available"};if(window.console){console.log("Page Type Warning:");console.log(this.detailsData);} if(moduleLoggerExists()){logger.warn(BNLogger.SUBSYSTEMS.THOR_RECS,this.detailsData.code+' : '+this.detailsData.msg);logger.send();}};PageTypeDeducingWarning.prototype.toString=function(){return basicErrorDetailsToString(this.detailsData);};var basicErrorDetailsToString=function(detailsData){return"["+detailsData.code+":"+detailsData.msg+"]";};var isBNThorError=function(error){return(error instanceof InitError||error instanceof ContextRetrievalError||error instanceof RecResponseStructureError||error instanceof RecRequestFormationError);} var validateRecResponseStructure=function(recResponse){var validatedResult,recResponseValidationErr;var recResponseDefinition={"id":{type:"string",required:true},"widgetResults":{type:"array",required:true}};var widgetDefinition={"id":{type:"string",required:true},"slotResults":{type:"array",required:true},"algoName":{type:"string",required:true}};var slotDefinition={"slot":{type:"string",required:true},"url":{type:"string",required:false},"attrs":{type:"array",required:false}};validatedResult=validateConfigObj(recResponseDefinition,recResponse);if(validatedResult.missingRequiredVals.length>0){recResponseValidationErr=new RecResponseStructureError({code:ERROR_MSG_CODES.REC_RESPONSE_MISSING_REQUIRED_VALS,msg:"Type mismatch or missing required values in rec server response: "+validatedResult.missingRequiredVals.join(),missingVals:validatedResult.missingRequiredVals,responseBody:recResponse});throw recResponseValidationErr;} BN$.each(recResponse.widgetResults,function(key,widget){var validatedWidget=validateConfigObj(widgetDefinition,widget);if(validatedWidget.missingRequiredVals.length>0){recResponseValidationErr=new RecResponseStructureError({code:ERROR_MSG_CODES.REC_RESPONSE_MISSING_REQUIRED_VALS,msg:"Type mismatch or missing required values for widgets in rec server response: "+validatedWidget.missingRequiredVals.join(),missingVals:validatedWidget.missingRequiredVals,responseBody:recResponse});throw recResponseValidationErr;} BN$.each(widget.slotResults,function(key,slot){var validatedSlot=validateConfigObj(slotDefinition,slot);if(validatedSlot.missingRequiredVals.length>0){recResponseValidationErr=new RecResponseStructureError({code:ERROR_MSG_CODES.REC_RESPONSE_MISSING_REQUIRED_VALS,msg:"Type mismatch or missing required values for slots in rec server response: "+validatedSlot.missingRequiredVals.join(),missingVals:validatedSlot.missingRequiredVals,responseBody:recResponse});throw recResponseValidationErr;}});});};var enactSecurityCountermeasures=function(rawRecResponse){var safeString=function(str){var escape={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"};var badChars=/[&<>"'`]/g;var possible=/[&<>"'`]/;return str.replace(badChars,function(chr){return escape[chr];});};var safeRecResponse=BN$.extend(true,{},rawRecResponse);function checkEachElement(obj){for(var key in obj){if(obj.hasOwnProperty(key)){if(typeof obj[key]==="string"){obj["safe:"+key]=safeString(obj[key]);}else{if(obj[key]===null){obj["safe:"+key]=null;}else if(typeof obj[key]==="object"){checkEachElement(obj[key]);}}}}} try{checkEachElement(safeRecResponse);}catch(err){var recResponseSecurityError=new RecResponseSecurityError({code:ERROR_MSG_CODES.REC_SECURITY_CHECK_FAIL,msg:"Failure while enacting security measures. Unable to escape special characters"});throw recResponseSecurityError;} return safeRecResponse;};var getDirectPTRoutingInfo=function(){var pt=BN$("["+ThorConstants.PAGE_TEMPLATE_ATTR_NAME+"]");if(pt.length>0){return pt.attr(ThorConstants.PAGE_TEMPLATE_ATTR_NAME);}};var getRecServerFullUrl=function(sourceUrl,contextUrls){var requestParams="";contextUrls=contextUrls||[contextUrl];if(!BN$.isArray(contextConfig.visitstrail)){contextConfig.visitstrail=[];} if(!BN$.isArray(contextConfig.requestDefinedAttrs)){contextConfig.requestDefinedAttrs=[];} if(!contextConfig.UserId){contextConfig.UserId=bnUser.getUserId();} BN$.each(contextConfig.attrs,function(idx,attr){requestParams+=(idx===0)?"?":"&";requestParams+="attrs="+encodeURIComponent(attr);});if(typeof pageTemplate!=="string"){if(pageType){requestParams+="&pagetype="+encodeURIComponent(pageType);}else if(pageType===null){return null;}else if(typeof pageType==="undefined"){throw new RecRequestFormationError({code:ERROR_MSG_CODES.REC_REQUEST_NO_PAGE_TYPES_FOUND,msg:"No page type found"});}} BN$.each(contextConfig.requestDefinedAttrs,function(idx,attr){var param="&"+attr.entityName+"."+attr.attrName+"="+encodeURIComponent(attr.attrValue);requestParams+=param;});if(typeof pageTemplate==="string"){requestParams+="&pageTemplate="+encodeURIComponent(pageTemplate);} if(sourceUrl&&sourceUrl!==contextUrls[0]){requestParams+="&source="+encodeURIComponent(sourceUrl);} BN$.each(contextUrls,function(idx,url){requestParams+="&url="+encodeURIComponent(url);});BN$.each(contextConfig.visitstrail,function(idx,url){requestParams+="&visitstrail="+encodeURIComponent(url);});if(contextConfig.query){requestParams+="&query="+encodeURIComponent(contextConfig.query);} if(contextConfig.UserId){requestParams+="&UserId="+encodeURIComponent(contextConfig.UserId);} return recServerUrlPrefix+"/"+customerName+"_"+customerCode+requestParams;};var retrieveRecResults=function(recServerFullUrl,successFn,errorFn){logger.info(BNLogger.SUBSYSTEMS.THOR_RECS,"Rec retrieval requested for url: "+recServerFullUrl);BN$.getJSON(recServerFullUrl,{format:"json"}).done(function(recResponse){var recResponseObj;try{if(typeof recResponse==='object'){recResponseObj=recResponse;}else if(typeof recResponse==='string'){try{recResponseObj=BN$.parseJSON(recResponse);}catch(e){errorFn(new ContextRetrievalError({code:ERROR_MSG_CODES.REC_RESPONSE_PARSE_FAIL,msg:"Rec server response could not be parsed.",parseError:e}));return;}}else{errorFn(new ContextRetrievalError({code:ERROR_MSG_CODES.INVALID_REC_RESPONSE,msg:"Rec server response is not a json object or string",recResponse:recResponse}));return;} successFn(recResponseObj,successFn);}catch(e){var finalError=getFinalError(e);if(typeof contextConfig.errorFn==="function"){contextConfig.errorFn(finalError);}else{throw finalError;}}finally{if(moduleLoggerExists()){logger.send();}}}).fail(function(jqXHR,textStatus){try{errorFn(new ContextRetrievalError({code:ERROR_MSG_CODES.REC_AJAX_FAILURE,msg:"Rec server did not complete AJAX request.",jqXHR:jqXHR,textStatus:textStatus}));}catch(e){var finalError=getFinalError(e);if(typeof contextConfig.errorFn==="function"){contextConfig.errorFn(finalError);}else{throw finalError;}}finally{if(moduleLoggerExists()){logger.send();}}});};var getPageType=function(successFn,errorFn){if(window.bnResultsPageType){pageType=window.bnResultsPageType;successFn();}else if(window.bnResultsPageType===null){pageType=null;}else if(typeof window.bnResultsPageType==="undefined"){retrieveAndDeterminePageType(successFn,errorFn);}} var retrieveAndDeterminePageType=function(successFn,errorFn){var url=merchServerUrlPrefix+"/"+customerName+"_"+customerCode+"/production"+"/pageTypes?properties=placeholderNames";BN$.getJSON(url).done(onPageTypesRetrieveSuccess).fail(onPageTypesRetrieveFailure);function onPageTypesRetrieveSuccess(response){var pageTypesResponse,deducedPageType;try{if(typeof response==='object'){pageTypesResponse=response;}else if(typeof response==='string'){try{pageTypesResponse=BN$.parseJSON(response);}catch(e){errorFn(new ContextRetrievalError({code:ERROR_MSG_CODES.MERCH_RESPONSE_PARSE_FAIL,msg:"Merch server response could not be parsed.",parseError:e}));return;}}else{errorFn(new ContextRetrievalError({code:ERROR_MSG_CODES.INVALID_MERCH_RESPONSE,msg:"Merch server response is not a json object or string",merchResponse:pageTypesResponse}));return;} deducedPageType=determinePageType(pageTypesResponse);if(typeof deducedPageType==="string"){pageType=deducedPageType;successFn();}else{errorFn(new RecRequestFormationError({code:ERROR_MSG_CODES.REC_REQUEST_NO_PAGE_TYPES_FOUND,msg:"No page types found"}));}}catch(e){var finalError=getFinalError(e);if(typeof contextConfig.errorFn==="function"){contextConfig.errorFn(finalError);}else{throw finalError;}}finally{if(moduleLoggerExists()){logger.send();}}};function onPageTypesRetrieveFailure(jqXHR,textStatus){try{errorFn(new ContextRetrievalError({code:ERROR_MSG_CODES.MERCH_AJAX_FAILURE,msg:"Merch server did not complete AJAX request.",jqXHR:jqXHR,textStatus:textStatus}));}catch(e){var finalError=getFinalError(e);if(typeof contextConfig.errorFn==="function"){contextConfig.errorFn(finalError);}else{throw finalError;}}finally{if(moduleLoggerExists()){logger.send();}}};} var determinePageType=function(pageTypes){var i,j,phN,pageTypeWithMaxHits=null;for(i in pageTypes){pageTypes[i].hits=0;if(pageTypes[i].placeholders){for(j=0;jpageTypeWithMaxHits.hits){pageTypeWithMaxHits.name=pageTypes[i].name;pageTypeWithMaxHits.hits=pageTypes[i].hits;pageTypeWithMaxHits.placeholderNames=pageTypes[i].placeholders||pageTypes[i].placeholderNames;}} if(pageTypeWithMaxHits.hits!==0){if(pageTypeWithMaxHits.hits0){initError=new InitError({code:ERROR_MSG_CODES.INIT_MISSING_REQUIRED_VALS,msg:"Type mismatch or missing required values: "+missingRequiredVals.join(),missingVals:missingRequiredVals});throw initError;} contextUrl=finalValues.contextUrl;customerCode=finalValues.customerCode;customerName=finalValues.customerName;recServerUrlPrefix=finalValues.recServerUrlPrefix;merchServerUrlPrefix=finalValues.merchServerUrlPrefix;thor_inject=finalValues.thor_inject;jQueryXDomainRequest();isInitialized=true;};var doRetrieveRenderingContext=function(successFn,sourceUrl,contextUrls){if(!isInitialized){return;} var getPageTypeLinkFn=function(chain){pageTemplate=getDirectPTRoutingInfo();if(typeof pageTemplate==="string"){chain.next();}else{getPageType(function(){chain.next();},function(error){chain.error(error);});}} var addRecServerFullUrlLinkFn=function(chain){chain.getContext().requestFullUrl=getRecServerFullUrl(sourceUrl,contextUrls);chain.next();} var recRetrieveLinkFn=function(chain){retrieveRecResults(chain.getContext().requestFullUrl,function(recResponse){chain.getContext().rawResponse=recResponse;chain.next();},function(error){chain.error(error);});};var recResponseStructureValidateLinkFn=function(chain){try{validateRecResponseStructure(chain.getContext().rawResponse);}catch(e){chain.error(e);return;} chain.next();};var securityCounterMeasuresLinkFn=function(chain){var safeRecResponse;try{safeRecResponse=enactSecurityCountermeasures(chain.getContext().rawResponse);}catch(e){chain.error(e);return;} chain.getContext().safeResponse=safeRecResponse;chain.next();};var separateWidgetsLinkFn=function(chain){var context=chain.getContext(),widgets;widgets=makeWidgetListFromServerResponse(context.safeResponse);context.addWidget(widgets);chain.next();};var extractTrackingDataLinkFn=function(chain){trackingData=chain.getContext().rawResponse.trackingData;chain.next();};var renderingContextSuccessPostProcessor=function(renderingContext){logger.info(BNLogger.SUBSYSTEMS.THOR_RECS,"Successful rendering context retrieval.");logger.debug(BNLogger.SUBSYSTEMS.THOR_RECS,"Rendering context retrieved: "+renderingContext.toString());successFn(renderingContext);};var renderingContextErrorProcessor=function(error){logger.error(BNLogger.SUBSYSTEMS.THOR_RECS,"Rec retrieval failed. Error obj: "+error.toString());throw error;};var contextChain=new RenderingContextChain({context:new RenderingContext({}),callbacks:[getPageTypeLinkFn,addRecServerFullUrlLinkFn,recRetrieveLinkFn,recResponseStructureValidateLinkFn,securityCounterMeasuresLinkFn,extractTrackingDataLinkFn,separateWidgetsLinkFn],successPostProcessor:renderingContextSuccessPostProcessor,errorProcessor:renderingContextErrorProcessor});contextChain.next();};var moduleLoggerExists=function(){return(logger!=null&&typeof logger!=="undefined"&&logger instanceof BNLogger)?true:false;};var getFinalError=function(error){var finalError;if(!isBNThorError(error)){finalError=new ContextRetrievalError({code:ERROR_MSG_CODES.UNEXPECTED,msg:"An unexpected error happened.",originalError:error});if(moduleLoggerExists()){logger.error(BNLogger.SUBSYSTEMS.THOR_RECS,"Unknown failure. Error obj: "+finalError.toString());}}else{finalError=error;} return finalError;} var PublicConstants={THOR_INJECT_POLICY:"thor",IC_INJECT_POLICY:"ic"};var init=function(initConfig){var finalError;try{doInit(initConfig);}catch(e){throw getFinalError(e);}};var retrieveRenderingContext=function(config){var finalError;var contextConfigDefinition={successFn:{"type":"function","required":true},errorFn:{"type":"function","required":true},attrs:{"type":"array","required":false,"default":["title","price","thumbUrl"]},visitstrail:{"type":"array","required":false},sourceUrl:{"type":"string","required":false},contextUrls:{"type":"array","required":false},requestDefinedAttrs:{"type":"array","required":false},query:{"type":"string","required":false},UserId:{"type":"string","required":false}};var validateContextConfig=function(contextConfig){var validatedObj,contextInitError;validatedObj=validateConfigObj(contextConfigDefinition,config);if(validatedObj.missingRequiredVals.length>0){contextInitError=new InitError({code:ERROR_MSG_CODES.INIT_MISSING_REQUIRED_VALS,msg:"Type mismatch or missing required values while initializing rendering context: "+validatedObj.missingRequiredVals.join(),missingVals:validatedObj.missingRequiredVals});throw contextInitError;} return validatedObj.finalValues;};try{if(!isInitialized){if(!(initError instanceof InitError)){initError=new InitError({code:ERROR_MSG_CODES.INIT_NOT_PERFORMED,msg:"Initialization has not been performed."});} logger.error(BNLogger.SUBSYSTEMS.THOR_RECS,"Rec retrieval failed. Error obj: "+initError.toString());throw initError;} contextConfig=validateContextConfig(config);doRetrieveRenderingContext(config.successFn,config.sourceUrl,config.contextUrls);}catch(e){finalError=getFinalError(e);if(typeof config.errorFn==="function"){config.errorFn(finalError);}else{throw finalError;}}finally{if(moduleLoggerExists()){logger.send();}}};var getTrackingData=function(){if(typeof BNData==="string"){return BNData;}else{return trackingData;}};var getTrackingDataByWidgetName=function(widgetName){if(typeof window.BNData==="object"&&typeof window.BNData.widget==="object"){return window.BNData.widget[widgetName];} else if(typeof window.BNData==="string"){return window.BNData;} else{return trackingData;}};var getElementInfo=function(element){var jqEl,info,baynoteAttrValue,baynoteWidgetAttrValue,baynoteSlotAttrValue,infoValues;info={widgetName:null,slotNo:null};if(typeof element==="undefined"&&!element){return info;} if(typeof BN$!=="function"){return info;} jqEl=element.jquery?element:BN$(element);baynoteWidgetAttrValue=BN$.trim(jqEl.attr(ThorConstants.REC_INFO_WIDGET_ATTR_NAME));baynoteSlotAttrValue=BN$.trim(jqEl.attr(ThorConstants.REC_INFO_SLOT_ATTR_NAME));baynotePIDValue=BN$.trim(jqEl.attr(ThorConstants.REC_INFO_PID_ATTR_NAME));baynoteAttrValue=BN$.trim(jqEl.attr(ThorConstants.REC_INFO_ATTR_NAME));if(baynoteWidgetAttrValue!==""&&baynoteSlotAttrValue!==""){info.widgetName=baynoteWidgetAttrValue||null;info.slotNo=baynoteSlotAttrValue||null;} else{infoValues=/(.*)_(\d+)$/.exec(baynoteAttrValue);if(BN$.isArray(infoValues)){info.widgetName=infoValues[1]||null;info.slotNo=infoValues[2]||null;}} if(baynotePIDValue){info.productId=baynotePIDValue;} return info;};var setInjectPolicy=function(policy){injectPolicy=policy.toLowerCase();};var getInjectPolicy=function(){var thorInjectPolicyVal=thor_inject;if(injectPolicy!==""){return injectPolicy;} if(thorInjectPolicyVal===true||thorInjectPolicyVal==="true"){return PublicConstants.THOR_INJECT_POLICY;}else{return PublicConstants.IC_INJECT_POLICY;}};return{"init":init,"retrieveRenderingContext":retrieveRenderingContext,"getTrackingData":getTrackingData,"getTrackingDataByWidgetName":getTrackingDataByWidgetName,"getElementInfo":getElementInfo,"setInjectPolicy":setInjectPolicy,"getInjectPolicy":getInjectPolicy,"Constants":PublicConstants};}());bnResourceManager.waitForResource(bnConstants.POLICY_RESOURCE_ID,function(){var thor_inject=bnPolicy.get("guide","thor_inject"),isLoadJQuery=bnPolicy.get("guide","load_jquery"),jQueryLoadError=function(){this.name=this.message='jQuery load error: jQuery was not found on current page and was not requested from policy';};if(isLoadJQuery){loadScript(baynote_tag.server+baynote_globals.jQueryPath,function(){initBNThor(thor_inject);});}else if(window.jQuery||(window.$&&$.fn&&$.fn.jquery)){BN$=window.jQuery||window.$;initBNThor(thor_inject);}else if(thor_inject===true){bnLogger.error('init.missingrequiredlib',"jQuery was not found on current page and was not requested from policy");bnLogger.send();try{throw new Error('init.missingrequiredlib. jQuery was not found on current page and was not requested from policy');}catch(e){if(window.console){console.log(e);}}}});function loadScript(url,callback){var script=document.createElement("script");script.type="text/javascript";if(script.readyState){script.onreadystatechange=function(){if(script.readyState=="loaded"||script.readyState=="complete"){script.onreadystatechange=null;callback();}};}else{script.onload=function(){callback();};} script.src=url;(document.getElementsByTagName("head")[0]||document.getElementsByTagName('body')[0]).appendChild(script);} function initBNThor(thor_inject){try{BNThor.init({contextUrl:bnPageInfo.getURL(),customerName:baynote_tag.customerId,customerCode:baynote_tag.code,recServerUrlPrefix:bnPolicy.get("guide","thor_rec_url_pfx"),merchServerUrlPrefix:bnPolicy.get("guide","thor_merch_url_pfx"),thor_inject:thor_inject,logger:bnLogger});}catch(e){if(thor_inject===true){bnLogger.error(BNLogger.SUBSYSTEMS.THOR_RECS,"Initialization of the BNThor module failed. Error obj: "+e.toString());bnLogger.send();}}};function jQueryXDomainRequest(){if(BN$.support.cors||!BN$.ajaxTransport||!window.XDomainRequest){return BN$;} var httpRegEx=/^(https?:)?\/\//i;var getOrPostRegEx=/^get|post$/i;var sameSchemeRegEx=new RegExp('^(\/\/|'+location.protocol+')','i');BN$.ajaxTransport('* text html xml json',function(options,userOptions,jqXHR){if(!options.crossDomain||!options.async||!getOrPostRegEx.test(options.type)||!httpRegEx.test(options.url)||!sameSchemeRegEx.test(options.url)){return;} var xdr=null;return{send:function(headers,complete){var postData='';var userType=(userOptions.dataType||'').toLowerCase();xdr=new XDomainRequest();if(/^\d+$/.test(userOptions.timeout)){xdr.timeout=userOptions.timeout;} xdr.ontimeout=function(){complete(500,'timeout');};xdr.onload=function(){var allResponseHeaders='Content-Length: '+xdr.responseText.length+'\r\nContent-Type: '+xdr.contentType;var status={code:200,message:'success'};var responses={text:xdr.responseText};try{if(userType==='html'||/text\/html/i.test(xdr.contentType)){responses.html=xdr.responseText;}else if(userType==='json'||(userType!=='text'&&/\/json/i.test(xdr.contentType))){try{responses.json=BN$.parseJSON(xdr.responseText);}catch(e){status.code=500;status.message='parseerror';}}else if(userType==='xml'||(userType!=='text'&&/\/xml/i.test(xdr.contentType))){var doc=new ActiveXObject('Microsoft.XMLDOM');doc.async=false;try{doc.loadXML(xdr.responseText);}catch(e){doc=undefined;} if(!doc||!doc.documentElement||doc.getElementsByTagName('parsererror').length){status.code=500;status.message='parseerror';throw'Invalid XML: '+xdr.responseText;} responses.xml=doc;}}catch(parseMessage){throw parseMessage;}finally{complete(status.code,status.message,responses,allResponseHeaders);}};xdr.onprogress=function(){};xdr.onerror=function(){complete(500,'error',{text:xdr.responseText});};if(userOptions.data){postData=(BN$.type(userOptions.data)==='string')?userOptions.data:BN$.param(userOptions.data);} xdr.open(options.type,options.url);xdr.send(postData);},abort:function(){if(xdr){xdr.abort();}}};});} if(bnResourceManager.removeResource===undefined){BNResourceManager.prototype.removeResource=bnResourceManager.removeResource=function(rId){this.resources[rId]=null;delete(this.resources[rId]);}};BaynoteAPI.getWindowName=function(){return bnPageInfo.getWindowName();};BaynoteAPI.getWordCount=function(){return bnPageInfo.getWordCount();};BaynoteAPI.getLinkCount=function(){return bnPageInfo.getLinkCount();};BaynoteAPI.getTitle=function(){return bnPageInfo.getTitle();};BaynoteAPI.is404=function(){return bnPageInfo.is404();};BaynoteAPI.cookiesAreEnabled=function(){return bnPageInfo.cookiesAreEnabled();};BaynoteAPI.getURL=function(){return bnPageInfo.getURL();};BaynoteAPI.getFullURL=function(){return bnPageInfo.getFullURL();};BaynoteAPI.getURLParams=function(){return bnPageInfo.getURLParams();};BaynoteAPI.getURLParam=function(paramName){return bnPageInfo.getURLParam(paramName);};BaynoteAPI.getBNParams=function(){return bnPageInfo.getBNParams();};BaynoteAPI.getBNParam=function(paramName){return bnPageInfo.getBNParam(paramName);};BaynoteAPI.getReferrerURL=function(){return bnPageInfo.getReferrerURL();};BaynoteAPI.isBinary=function(url){return bnPageInfo.isBinary(url);};BaynoteAPI.getWindowHeight=function(){return bnPageInfo.windowHeight;};BaynoteAPI.getWindowWidth=function(){return bnPageInfo.windowWidth;};BaynoteAPI.stringToBoolean=function(str){return bnCommon.stringToBoolean(str);};BaynoteAPI.copyObj=function(obj,props){return bnCommon.copyObj(obj,props);};BaynoteAPI.copyProperties=function(src,dst,props){return bnCommon.copyProperties(src,dst,props);};BaynoteAPI.dumpObj=function(obj,name,indent,depth,asHTML){return bnCommon.dumpObj(obj,name,indent,depth,asHTML);};BaynoteAPI.dump=function(obj){return bnCommon.dump(obj);};BaynoteAPI.dumpHTML=function(obj){return bnCommon.dumpHTML(obj);};BaynoteAPI.getURLParams=function(url){return bnCommon.getURLParams(url);};BaynoteAPI.addURLParam=function(url,paramName,value){return bnCommon.addURLParam(url,paramName,value);};BaynoteAPI.addURLMetaKeys=function(url,metaKeyList){return bnCommon.addURLMetaKeys(url,metaKeyList);};BaynoteAPI.getCookieValue=function(cookieName){return bnCommon.getCookieValue(cookieName);};BaynoteAPI.setCookie=function(cookieName,cookieValue,cookiePath,cookieExpires,cookieDomain,cookieSubDomain){return bnSystem.setCookie(cookieName,cookieValue,cookiePath,cookieExpires,cookieDomain,cookieSubDomain);};BaynoteAPI.removeCookie=function(cookieName){return bnCommon.removeCookie(cookieName);};BaynoteAPI.normalizeUrl=function(tag,url){return bnCommon.normalizeUrl(tag,url);};BaynoteAPI.arrayToJSON=function(arr){return bnCommon.arrayToJSON(arr);};BaynoteAPI.booleanToJSON=function(bool){return bnCommon.booleanToJSON(bool);};BaynoteAPI.numberToJSON=function(num){return bnCommon.numberToJSON(num);};BaynoteAPI.objectToJSON=function(obj){return bnCommon.objectToJSON(obj);};BaynoteAPI.stringToJSON=function(str){return bnCommon.stringToJSON(str);};BaynoteAPI.valueToJSON=function(val){return bnCommon.valueToJSON(val);};BaynoteAPI.parseJSON=function(str){return bnCommon.parseJSON(str);};BaynoteAPI.trim=function(str){return bnCommon.trim(str);};BaynoteAPI.getInnerText=function(obj){return bnCommon.getInnerText(obj);};BaynoteAPI.hasAnyProperty=function(obj){return bnCommon.hasAnyProperty(obj);};BaynoteAPI.getURL=function(fullUrl,urlParams,bnParams){return bnCommon.getURL(fullUrl,urlParams,bnParams);};BaynoteAPI.isGuideContainerPresent=function(){return bnCommon.isGuideContainerPresent();};BaynoteAPI.isNotEmpty=function(name){return bnCommon.isNotEmpty(name);};BaynoteAPI.lookupMeta=function(name){return bnCommon.lookupMeta(name);};BaynoteAPI.lookupMetaAttrib=function(name,attrib){return bnCommon.lookupMetaAttrib(name,attrib);};BaynoteAPI.isCustomScriptPresent=function(){return bnPolicy.customScriptPresent;};BaynoteAPI.policyOverrides=function(){return bnPolicy.overrides;};BaynoteAPI.userId=function(){return bnPolicy.userId;};BaynoteAPI.getPolicy=function(cat,key){return bnPolicy.get(cat,key);};BaynoteAPI.getCondition=function(tag){return bnPolicy.getCondition(tag);};BaynoteAPI.isSpecialUser=function(){return bnPolicy.isSpecialUser();};BaynoteAPI.getGuideElementIds=function(){return bnPolicy.getGuideElementIds();};BaynoteAPI.getAjaxTag=function(){return bnAjaxHandler;};BaynoteAPI.getTotalPurchases=function(){return baynote_tag.getTotalPurchases();};BaynoteAPI.sendVisitEvent=function(param){if(typeof param!='undefined'){param.action="visit";BaynoteAPI.call("observer","actionOccurred",[param],"bnObserver");}};BaynoteAPI.sendExitEvent=function(param){if(typeof param!='undefined'){param.action="exit";BaynoteAPI.call("observer","actionOccurred",[param],"bnObserver");}};BaynoteAPI.sendPageEvent=function(param){if(typeof param!='undefined'){param.action="page";if(bnObserver&&bnObserver.name=="defaultHandler"){bnObserver.pageAction(param);}else{BaynoteAPI.call("observer","actionOccurred",[param],"bnObserver");}}};BaynoteAPI.setUserId=function(userId,skipWrite){bnUser.setUserId(userId,skipWrite);};BaynoteAPI.writeUserCookieToWindowName=function(userId){bnUser.writeUserCookieToWindowName(userId);};BaynoteAPI.readUserCookieFromWindowName=function(){return bnUser.readUserCookieFromWindowName();};BaynoteAPI.canItFit=function(msg){return bnMessenger.canItFit(msg);};BaynoteAPI.sendRecImpression=function(flag){if(!bnObserver)return;bnObserver.sendRecImpression=flag;};BaynoteAPI.cancelLinger=function(){if(!bnObserver)return;bnObserver.cancelLinger();};BaynoteAPI.clearObserverAttributes=function(attrsList){if(!bnObserver)return;bnObserver.clearObserverAttributes(attrsList);};BaynoteAPI.implicitQueryOccured=function(query,profileUrl,isSpecial){if(!bnObserver)return;bnObserver.isSpecial=isSpecial;bnObserver.queryExitOccurred(query,profileUrl);if(isSpecial) bnObserver.isSpecial=false;};BaynoteAPI.isArray=function(obj){return bnCommon.isArray(obj);};BaynoteAPI.checkType=function(obj,type){return bnCommon.checkType(obj,type);};BaynoteAPI.useExternalId=function(externalId){var remove=false;bnPolicy.useExternalId(externalId,remove);};BaynoteAPI.detachExternalId=function(externalId){var remove=true;bnPolicy.useExternalId(externalId,remove);};BaynoteAPI.getTrailURLs=function(){if(bnTrail)return bnTrail.data;return null;};BaynoteAPI.persistTrailURLs=function(){if(bnTrail){bnTrail.save(bnPolicy.get("trail","so"));return true;} return false;};bnResourceManager.registerResource(baynote_tag.getCommonResourceId()); function BNMessenger(){this.server=null;this.messageNum=0;this.msgLimit=50000;this.eventDetailsLimit=49500;this.initialized=false;this.debug=false;} BNMessenger.prototype.initialize=function(serverAddr,customer,code,key,debug){this.url=serverAddr+"/listener2";this.customer=customer;this.code=code;this.key=key;this.debug=debug;this.initialized=true;} BNMessenger.prototype.sendMessage=function(msg){var debugArg=(this.debug)?"&debug=true":"";var msgPrefix=this.url+"?customerId="+this.customer+"&code="+this.code;if(this.key)msgPrefix+="&key="+this.key;msgPrefix+="&msgId="+this.messageNum+debugArg+"&fmt=1&len="+msg.length+"&msg=";var fullMsg=msgPrefix+encodeURIComponent(msg);var spaceLeft=this.msgLimit-fullMsg.length;if(spaceLeft>=0){this.resultResourceId="Message"+this.messageNum;bnResourceManager.loadResource(this.resultResourceId,fullMsg,"img");this.messageNum++;bnTagManager.invokeCallBack(this.resultResourceId,this.myTag);} return spaceLeft;} BNMessenger.prototype.canItFit=function(msg){var msgStr=bnCommon.valueToJSON(msg);var msgStrTobeSent=encodeURIComponent(msgStr);return this.eventDetailsLimit-msgStrTobeSent.length>=0;} var bnMessenger=new BNMessenger();function BNBehavior(){this.numSamples=0;this.numMouseMoves=0;this.numScrolls=0;this.lastMousePos=new Object();this.lastMousePos.x=this.lastMousePos.y=0;this.curMousePos=new Object();this.curMousePos.x=this.curMousePos.y=0;this.lastScroll=new Object();this.lastScroll.x=this.lastScroll.y=0;this.curScroll=new Object();this.curScroll.x=this.curScroll.y=0;this.maxScrollPercent=0;} BNBehavior.prototype.activityCheck=function(){this.numSamples++;if((this.lastMousePos.x&&this.lastMousePos.x!=this.curMousePos.x)||(this.lastMousePos.y&&this.lastMousePos.y!=this.curMousePos.y)){this.numMouseMoves++;} this.lastMousePos.x=this.curMousePos.x;this.lastMousePos.y=this.curMousePos.y;this.curScroll.y=(bnIsIE)?document.body.scrollTop:window.pageYOffset;if(this.lastScroll.y&&this.lastScroll.y!=this.curScroll.y)this.numScrolls++;this.lastScroll.y=this.curScroll.y;var curScrollPercent=this.getScrollScope();if(curScrollPercent>this.maxScrollPercent){this.maxScrollPercent=curScrollPercent;} setTimeout("bnBehavior.activityCheck()",500);} BNBehavior.prototype.getScrollTop=function(){if(document.documentElement&&document.documentElement.scrollTop) return document.documentElement.scrollTop;if(document.body) return document.body.scrollTop;return window.pageYOffset;} BNBehavior.prototype.getScrollHeight=function(){if(document.documentElement&&document.documentElement.scrollHeight) return Math.max(document.documentElement.offsetHeight,document.documentElement.scrollHeight,document.body.scrollHeight);return document.body.scrollHeight;} BNBehavior.prototype.getClientHeight=function(){if(typeof(window.innerWidth)=='number') return window.innerHeight;if(document.documentElement&&(document.documentElement.clientWidth||document.documentElement.clientHeight)) return document.documentElement.clientHeight;if(document.body&&(document.body.clientWidth||document.body.clientHeight)) return document.body.clientHeight;} BNBehavior.prototype.getScrollScope=function(){return Math.round((this.getScrollTop()+this.getClientHeight())*100/this.getScrollHeight());} BNBehavior.prototype.mouseHandler=function(e){this.curMousePos.x=e.pageX;this.curMousePos.y=e.pageY;} var bnBehavior=new BNBehavior();function BNObserver(){this.lingerCancelled=false;this.sendRecImpression=false;this.name="defaultHandler";this.myType="baynoteObserver";this.myTag=null;this.startTime=new Date().getTime();this.networkInfo=null;this.pageEvent=true;this.sendVisitEvent=true;this.sendExitEvent=true;} BNObserver.prototype.createSearchBox=function(){var actionUrl=this.myTag.server+"/search/query2";var searchButtonHTML;var searchButtonImg=this.myTag.getParam("searchButtonImg",null);if(searchButtonImg){searchButtonHTML='';searchImgParam='';}else{searchButtonHTML='';searchImgParam='';} var key=this.myTag.key?this.myTag.key:"";var searchboxHtml='' +'' +'' +'' +'
' +'
' +'' +'' +'' +'' +'' +searchImgParam+'' +searchButtonHTML+'
' +'
';var searchboxDiv=document.createElement("div");searchboxDiv.innerHTML=searchboxHtml;return searchboxDiv;} BNObserver.prototype.shouldSendEvent=function(){if(this.soEnabled)return true;if(this.stEnabled&&this.isSpecial)return true;if(this.isSpecialUser)return true;return false;} BNObserver.prototype.sendEvent=function(evJSON,force){if(!this.shouldSendEvent()&&(typeof(force)=="undefined"||!force))return;if(!bnMessenger.initialized){setTimeout(function(){bnObserver.sendEvent(evJSON,force);},100);return;} var result=bnMessenger.sendMessage(evJSON);while(result<0){var newEv=bnCommon.parseJSON(evJSON);if(newEv.de){delete newEv.de;evJSON=bnCommon.valueToJSON(newEv);result=bnMessenger.sendMessage(evJSON);}else if(newEv.at&&newEv.at.rt){delete newEv.at.rt;evJSON=bnCommon.valueToJSON(newEv);result=bnMessenger.sendMessage(evJSON);}else{if(typeof baynote_globals.messageDropped=='function'){baynote_globals.messageDropped({result:result,msg:evJSON});} result=0;}}} BNObserver.prototype.makeEvent=function(action){var ev=new Object();ev.a=action;if(typeof(bnPolicy.getCondition)!="undefined"){ev.c=bnPolicy.getCondition(this.myTag);}else{ev.c=bnPolicy.get("inf","cd");} ev.d=this.url;if(!ev.d){ev.d=bnPageInfo.getURL();} if(this.myTag.iFrame){ev.r=parent.document.referrer;ev.p=parent.location.href.split("#")[0];ev.p=bnCommon.getURL(ev.p);}else{ev.r=document.referrer;} if(this.myTag.referrer){ev.r=this.myTag.referrer;} ev.t=new Date().getTime();ev.u=bnUser.getUserId(this.myTag);if(bnCommon.hasAnyProperty(this.myTag.attrs))ev.at=this.myTag.attrs;this.checkForSpecialTarget(ev);if(!this.soEnabled&&this.stEnabled&&this.isSpecial){ev.at=ev.at||{};ev.at.st="true";} if(this.isSpecialUser){ev.at=ev.at||{};ev.at.su="true";} if(typeof(this.networkInfo)!="undefined"&&this.networkInfo&&!this.networkInfo.userIds.isEmpty()){ev.at.networkUserIds=this.networkInfo.userIds.toString();if(!this.networkInfo.groupIds.isEmpty()){ev.at.networkGroupIds=this.networkInfo.groupIds.toString();}} if(action=='c'||action=='C'){if(baynote_globals.RecImpressionList&&baynote_globals.RecImpressionList.length>0&&this.sendRecImpression){ev.at=ev.at||{};ev.at.rt=baynote_globals.RecImpressionList;}} var extUid=bnUser.getExtUserId();if(extUid){ev.at=ev.at||{};ev.at.extUid=extUid;} if(typeof baynote_globals.verifyEvent==='function'){baynote_globals.verifyEvent(ev);} if(BNThor){var trackingData=BNThor.getTrackingData();if(typeof trackingData!=="undefined"&&trackingData){ev.trackingData=trackingData;}} return ev;} BNObserver.prototype.makeDetails=function(){var de=new Object();if(bnPolicy.get("baynoteObserver","cds")){var summary=this.myTag.getParam("summary",null);if(summary&&summary.length>0)de.su=summary;} if(bnPolicy.get("baynoteObserver","cdt")){var title=this.myTag.getParam("title",bnPageInfo.getTitle());if(title&&title.length>0)de.ti=title;} de.nw=bnPageInfo.getWordCount();de.nl=bnPageInfo.getLinkCount();return de;} BNObserver.prototype.makeBehavior=function(){var bi=null;if(typeof(bnBehavior)=="object"){bi=new Object();bi.ps=bnBehavior.maxScrollPercent;bi.ma=bnBehavior.numMouseMoves;bi.sa=bnBehavior.numScrolls;} return bi;} BNObserver.prototype.networkLogin=function(networkInfo){this.networkInfo=networkInfo;} BNObserver.prototype.networkLogout=function(networkInfo){this.networkInfo=networkInfo;} BNObserver.prototype.cancelLinger=function(){this.lingerCancelled=true;} BNObserver.prototype.clickOccurred=function(clicked){var exitInfo=new Object();var result=false;if(typeof(this.myTag.exitConfirmation)=="function"){result=this.myTag.exitConfirmation(clicked,exitInfo);}else{result=this.defaultExitConfirmation(clicked,exitInfo);} if(result)this.exitOccurred(exitInfo);} BNObserver.prototype.defaultExitConfirmation=function(clicked,exitInfo){var target=clicked;while(target){if(target.tagName=="A")break;target=target.parentNode;} if(!target)return false;exitInfo.dest=target.href;var gt=target.getAttribute("baynote_guide");if(typeof(gt)!="undefined"&>)exitInfo.baynote_guide=gt;var gr=target.getAttribute("baynote_req");if(typeof(gr)!="undefined"&&gr)exitInfo.baynote_req=gr;var bn=target.getAttribute("baynote_bnrank");if(typeof(bn)!="undefined"&&bn)exitInfo.baynote_bnrank=bn;var ir=target.getAttribute("baynote_irrank");if(typeof(ir)!="undefined"&&ir)exitInfo.baynote_irrank=ir;var lt=bnCommon.getInnerText(target);if(!lt&&bnPolicy.get("baynoteObserver","alt")&&clicked&&clicked.tagName=="IMG"){lt=clicked.getAttribute("ALT");var src=clicked.getAttribute("SRC");if(lt&&(src.indexOf(lt)==(src.length-lt.length))){lt=null;}} if(lt)exitInfo.link=lt;var attrs=this.myTag.attrs;if(typeof(attrs)=="object"&&bnCommon.hasAnyProperty(attrs)){exitInfo.attrs=bnCommon.copyObj(attrs);} var elementInfo;elementInfo=BNThor.getElementInfo(target);if(typeof elementInfo.widgetName!=="undefined"&&elementInfo.widgetName){exitInfo.baynote_req=elementInfo.widgetName;exitInfo.baynote_guide="DUMMY";} if(typeof elementInfo.slotNo!=="undefined"&&elementInfo.slotNo){exitInfo.baynote_bnrank=elementInfo.slotNo;} if(elementInfo.productId){exitInfo.attrs=exitInfo.attrs||{};exitInfo.attrs.prodId=elementInfo.productId;} return true;} BNObserver.prototype.exitOccurred=function(exitInfo){if(!this.sendExitEvent){bnLog.log('WARN: Exit Observervation is turned off');return;} var ev=this.makeEvent("c");if(typeof ev.trackingData!=="string"){ev.trackingData=BNThor.getTrackingDataByWidgetName(exitInfo.baynote_req);} var dd=exitInfo.dest;if(typeof(dd)!="undefined"&&dd)ev.dd=dd;else ev.dd="bn_ignore=t";var lt=exitInfo.link;if(typeof(lt)!="undefined"&<)ev.l=lt;var ea=exitInfo.attrs;if(typeof(ea)=="object"){ev.at=ea;} var gt=exitInfo.baynote_guide;if(typeof(gt)!="undefined"&>)ev.gt=gt;var gr=exitInfo.baynote_req;if(typeof(gr)!="undefined"&&gr)ev.gr=gr;var bn=exitInfo.baynote_bnrank;if(typeof(bn)!="undefined"&&bn){ev.rb=bn;if(!this.soEnabled&&this.stEnabled){this.isSpecial=true;if(!ev.at)ev.at=new Object();ev.at.st="true";} if(this.isSpecialUser){if(!ev.at)ev.at=new Object();ev.at.su="true";}} var ir=exitInfo.baynote_irrank;if(typeof(ir)!="undefined"&&ir)ev.ri=ir;var gat=exitInfo.baynote_guide_target;if(typeof(gat)!="undefined"&&gat)ev.gat=gat;var iq=exitInfo.implicitQuery;if(typeof(iq)!="undefined"&&iq){if(!ev.at)ev.at=new Object();ev.at.implicitQuery=iq;} if(!this.myTag.iFrame){var details=this.makeDetails();if(details!=null)ev.de=details;} if(bnPolicy.get("baynoteObserver","ub")){var bi=this.makeBehavior();if(bi!=null)ev.bi=bi;} if(!this.shouldSendEvent())return;var u=bnCommon.getCookieValue("bn_u");var sEvt=bnCommon.valueToJSON(ev);var fCookie=false;if(bnPolicy.get("baynoteObserver","ec")&&(typeof(u)!="undefined"&&u)&&bnPageInfo.cookiesAreEnabled){var msgStrTobeSet=encodeURIComponent(sEvt);var lenDiff=bnMessenger.eventDetailsLimit-msgStrTobeSet.length;if(lenDiff>=0){bnCommon.setCookie("bn_ec",sEvt,"/","SESSION");fCookie=true;}else{if(typeof baynote_globals.messageDropped=='function'){baynote_globals.messageDropped({result:lenDiff,msg:sEvt});}}} if(!fCookie||(bnPolicy.get("baynoteObserver","eec"))){this.sendEvent(sEvt);this.exitPause();}} BNObserver.prototype.lingerOccurred=function(ds){if(!this.shouldFireLinger())return;var ev=this.makeEvent("l");ev.du=ds;if(bnPolicy.get("baynoteObserver","sdl")){var details=this.makeDetails();if(details!=null)ev.de=details;} this.sendEvent(bnCommon.valueToJSON(ev));if(bnTrail&&bnPolicy.get("trail","ok")){bnTrail.addUrl(this.url,bnPolicy.get("trail","tl"),bnPolicy.get("trail","so"));}} BNObserver.prototype.visitOccurred=function(){if(bnPolicy.get("baynoteObserver","ec")){var sEvt=bnCommon.getCookieValue("bn_ec");if(typeof(sEvt)!="undefined"&&sEvt&&sEvt.length>0){this.sendEvent(sEvt,true);}} bnCommon.removeCookie("bn_ec");if(!this.shouldFireVisit())return;var ev=this.makeEvent("v");this.sendEvent(bnCommon.valueToJSON(ev));} BNObserver.prototype.getBnTags=function(targetWidgetName){var polGuideAttr="ign",guideAttr=bnPolicy.get(this.myType,polGuideAttr)||'baynote_req';var i,currTag,aTags=document.getElementsByTagName('a'),aTagsLen=aTags.length,bnTagsList=[];for(i=0;i0){this.sendImpression(bnTags,window.BNData);} else if((typeof window.BNData==='string'||!needBNData)&&bnTags.length===0){waitForBNTags=setInterval(function(){var bnTagsList=self.getBnTags();if(bnTagsList.length>0){clearInterval(waitForBNTags);self.sendImpression(bnTagsList,window.BNData);}},intervalGap);return;} else if(typeof window.BNData==='undefined'&&needBNData){waitForBNData=setInterval(function(){if(typeof window.BNData!=='undefined'){clearInterval(waitForBNData);self.impressionOccurred();}},intervalGap);return;} else if(typeof window.BNData==='object'){trackingDataList=[];impressionsFiredCount=0;bnDataCount=window.BNData.widgetCount;waitForMultipleBNData=setInterval(function(){var i,currItem,bnTagsList,unsentList=[];if(typeof bnDataCount==='undefined'||impressionsFiredCount0){self.sendImpression(bnTagsList,currItem.trackingData);currItem.isSent=true;impressionsFiredCount++;}}} else{clearInterval(waitForMultipleBNData);}},intervalGap);return;} function addNewTrackingDataToList(){var widgetName,trackingData;for(widgetName in window.BNData.widget){if(window.BNData.widget.hasOwnProperty(widgetName)){trackingData=window.BNData.widget[widgetName];if(!isWidgetNameInList(widgetName)){trackingDataList.push({widgetName:widgetName,trackingData:trackingData,isSent:false});}}}} function isWidgetNameInList(widgetName){var i,currItem,isPresent=false;for(i=0;i1){prefixLen=-1;for(urlIdx=0;urlIdx0){prefix=urls[0].substring(0,prefixLen);for(urlIdx=0,urlCount=urls.length;urlIdxmaxIter)break;}} BNObserver.prototype.actionOccurred=function(obj){} BNObserver.prototype.instrumentLinks=function(){bnEvent.addHandler(document.body,"click",function(){var evt=bnEvent.getEvent();if(evt.target)bnObserver.clickOccurred(evt.target);});bnLog.log("onclick handler installed");} BNObserver.prototype.instrumentBehavior=function(){if(typeof(bnBehavior)=="object"&&bnBehavior!=null){bnEvent.addHandler(document,"mousemove",function(){var evt=bnEvent.getEvent();bnBehavior.mouseHandler(evt);});setTimeout("bnBehavior.activityCheck()",500);}} BNObserver.prototype.captureValue=function(cap){var result;if(cap.st=="dp"){if(cap.sn.indexOf(bnConstants.BN_PARAM_PREFIX)==0)result=bnPageInfo.getBNParam(cap.sn);else result=bnPageInfo.getURLParam(cap.sn);}else if(cap.st=="mt"){var metas=document.getElementsByName(cap.sn);if(metas){for(var i=0;i0) return;this.myTag.attrs[cap.dn]=value;}else if(cap.dt=="da"){if(!this.myTag.docAttrs) this.myTag.docAttrs={};else if(this.myTag.docAttrs[cap.dn]&&this.myTag.docAttrs[cap.dn].length>0) return;this.myTag.docAttrs[cap.dn]=value;}else if(this.debug){alert("Invalid capture destination type "+cap.dt);}} BNObserver.prototype.usePolicyValues=function(obsTag){this.myTag=obsTag;this.debug=bnPolicy.get(this.myType,"debug");this.soEnabled=bnPolicy.get(this.myType,"so");this.stEnabled=bnPolicy.get(this.myType,"st");this.updateTag(obsTag);this.isPolicyValuesAssigned=true;} BNObserver.prototype.updateTag=function(obsTag){this.myTag=obsTag;this.url=this.myTag.getParam("url",bnPageInfo.getURL());this.url=bnCommon.addURLMetaKeys(this.url,this.myTag.metaKeys);var oldPS=this.myTag.getParam("page_status");if(!oldPS&&bnPageInfo.is404())oldPS=404;var oldTP=this.myTag.getParam("totalPurchases");var oldQ=this.myTag.getParam("query");if(oldTP||oldQ||oldPS){if(!this.myTag.attrs)this.myTag.attrs=new Object();if(!this.myTag.attrs.totalPurchases&&oldTP)this.myTag.attrs.totalPurchases=oldTP;if(!this.myTag.attrs.query&&oldQ)this.myTag.attrs.query=oldQ;if(!this.myTag.attrs.pageStatus&&oldPS)this.myTag.attrs.pageStatus=oldPS;} var caps=bnPolicy.get(this.myType,"cap");if(caps!=null&&caps instanceof Array){for(var i=0;i=1){this.storeCapturedValue(cap,value);}}} if(bnCommon.hasAnyProperty(this.myTag.docAttrs)){if(!this.myTag.attrs)this.myTag.attrs=new Object();this.myTag.attrs.docAttrs=bnCommon.objectToJSON(this.myTag.docAttrs);} this.isSpecial=!!((typeof(this.myTag.specialTarget)!="undefined"&&this.myTag.specialTarget)||(this.myTag.attrs&&this.myTag.attrs.totalPurchases));this.isSpecialUser=false;if(typeof(bnPolicy.isSpecialUser)=="function"){this.isSpecialUser=bnPolicy.isSpecialUser();} if(this.isSpecialUser){this.isSpecial=true;}} BNObserver.prototype.show=function(obsTag){this.lingerCancelled=false;this.myTag=obsTag;if(!this.isPolicyValuesAssigned){this.usePolicyValues(obsTag);} this.updateTag(obsTag);if(this.myTag.searchbox){var ph=document.getElementById(this.myTag.placeHolderId);if(bnPolicy.get("search","ok")){ph.appendChild(this.createSearchBox());}else if(this.myTag.noload){ph.innerHTML=this.myTag.noload;}} var urlPrefix=bnPolicy.get(obsTag.type,"ec_url");if(urlPrefix&&typeof urlPrefix=='string'){bnMessenger.initialize(urlPrefix,this.myTag.customerId,this.myTag.code,this.myTag.key,this.debug);}else{var obsHandler="/baynote/tags3/baynoteObserver";bnMessenger.initialize(this.myTag.server+obsHandler,this.myTag.customerId,this.myTag.code,this.myTag.key,this.debug);} this.visitOccurred();var dwellTime=bnPolicy.get(this.myType,"dt");var dlThreshold=bnPolicy.get(this.myType,"ddt");if(this.myTag.attrs&&this.myTag.attrs.expectedDuration&&typeof(dlThreshold)!='undefined'&&dlThreshold>0){dwellTime=this.myTag.attrs.expectedDuration*dlThreshold;} var dwellMSec=dwellTime*1000;setTimeout("bnObserver.lingerOccurred("+dwellTime+")",dwellMSec);var imprOptIn=bnPolicy.get(this.myType,"ioi");var imprTimer=bnPolicy.get(this.myType,"it")||2;var imprMSec=imprTimer*1000;var usesThorInject=BNThor.getInjectPolicy()===BNThor.Constants.THOR_INJECT_POLICY;if(usesThorInject){bnLogger.info(BNLogger.SUBSYSTEMS.IMPRESSIONS,"Auto-impressions logic will not be executed, due to the customer being "+"'Thor Injection' customer. Impressions will be fired manually in custom script");} if(imprOptIn&&!usesThorInject){setTimeout("bnObserver.impressionOccurred()",imprMSec);} this.instrumentLinks();if(bnPolicy.get("baynoteObserver","ub")){this.instrumentBehavior();} if(bnPolicy.get("baynoteObserver","bpe"))this.pageEvent=false;bnResourceManager.registerAndAddResource(this.myType,bnObserver);return true;} BNObserver.prototype.pageAction=function(param){if(typeof param=='undefined')return;if(this.debug)bnLog.log("pageAction invoked with param:\n"+bnCommon.dump(param));var attrs=param.attrs;if(typeof(attrs)=="undefined"||!attrs){if(this.debug)bnLog.log("No attribute 'attrs' was specified");return;} var evType=attrs.evType;if(typeof(evType)=="undefined"||!evType){if(this.debug)bnLog.log("No event type 'evType' was specified in 'attrs'");return;} var evTarget=attrs.evTarget;if(typeof(evTarget)=="undefined"||!evTarget){if(this.debug)bnLog.log("No event target 'evTarget' was specified in 'attrs'");return;} var doc=param.d;if(typeof(doc)=="undefined"||!doc){if(this.debug)bnLog.log("No document was specified");return;} var ev=this.makeEvent("p");this.checkIsSpecial(param);this.setEventAttrs(ev,param);ev.d=doc;this.firePageEvent(ev);} BNObserver.prototype.firePageEvent=function(ev){if(this.pageEvent){this.sendEvent(bnCommon.valueToJSON(ev));}} BNObserver.prototype.checkIsSpecial=function(param){var specialTarget=param.specialTarget;if(typeof(specialTarget)!="undefined"&&specialTarget){this.isSpecial=true;delete param.specialTarget;}else{this.isSpecial=false;}} BNObserver.prototype.setEventAttrs=function(ev,param){if(param==null||!bnCommon.hasAnyProperty(param.attrs))return;if(!ev.at)ev.at={};for(var prop in param.attrs){var child=param.attrs[prop];if(typeof(child)!="undefined"&&typeof(child)!="function"&&child!=null){ev.at[prop]=child;}}} BNObserver.prototype.clearObserverAttributes=function(attrList){if(!this.myTag||!this.myTag.attrs)return;for(var i in attrList){var theEvtAttr=attrList[i];if(typeof this.myTag.attrs[theEvtAttr]!='undefined'){delete this.myTag.attrs[theEvtAttr];}}};BNObserver.prototype.checkForSpecialTarget=function(ev){this.setSpecialTarget(baynote_globals.ReferrerPatterns,ev.r);this.setSpecialTarget(baynote_globals.DocumentPatterns,ev.d);this.setSpecialTarget(baynote_globals.DocDestinationPatterns,ev.dd);};BNObserver.prototype.setSpecialTarget=function(arrayOfPatterns,url){if(!url||!bnCommon.isNotEmpty(url)||!arrayOfPatterns||!bnCommon.isArray(arrayOfPatterns)){return;} for(var i in arrayOfPatterns){var rxPattern=arrayOfPatterns[i];if(bnCommon.checkType(rxPattern,'RegExp')&&rxPattern.test(url)){this.isSpecial=true;return;}}};var bnObserver=new BNObserver();BaynoteAPI.enableVisitEvent=function(flag){bnObserver.sendVisitEvent=flag;};BaynoteAPI.enableLingerEvent=function(flag){bnObserver.lingerCancelled=!flag;};BaynoteAPI.enableExitEvent=function(flag){bnObserver.sendExitEvent=flag;};bnTagManager.registerTagHandler(bnObserver.myType,bnObserver); function BNGuideLiteHandler(){this.myType="guide";this.myTag=null;this.guide=null;this.socialGuide=null;this.socialShow=false;this.socialLoggedIn=false;this.networkInfo=null;} bnConstants.GUIDE_RESULTS_RESOURCE_PREFIX="GLResults";bnConstants.GUIDE_SOCIAL_SHOW_LOGIN="showLogin";bnConstants.GUIDE_SOCIAL_HIDE_LOGIN="hideLogin";bnConstants.GUIDE_SOCIAL_SHOW_GUIDE="showGuide";BNGuideLiteHandler.prototype.gotoPage=function(tagId,guideRank,gotoURL){with(this){if(typeof(bnTrailMgr)!="undefined"&&bnTrailMgr){var guideType=bnTagManager.getTag(tagId).guide;bnTrailMgr.guideResultClick(guideType,guideRank,gotoURL);}if(gotoURL){if(bnIsIE){window.event.returnValue=false;} window.location.href=gotoURL;}}};BNGuideLiteHandler.prototype.getResultsHandlerAddress=function(guideTag){var resultsFormat=guideTag.getParam("format",bnPolicy.get(this.myType,"fmt"));if(!resultsFormat){resultsFormat="results-xsl";} var srcPreamble=guideTag.server+baynote_globals.TagsURLPrefix+this.myType+"/"+ resultsFormat+"/"+guideTag.customerId+"-"+guideTag.code;var guideScriptSrc="";guideScriptSrc+=srcPreamble;guideScriptSrc+="?userId="+bnUser.getUserId(guideTag);guideScriptSrc+="&customerId="+guideTag.customerId;guideScriptSrc+="&code="+guideTag.code;if(guideTag.key){guideScriptSrc+="&key="+guideTag.key;} guideScriptSrc+="&id="+guideTag.id;if(this.socialShow&&this.socialGuide){guideScriptSrc+="&guide="+encodeURIComponent(this.socialGuide);} if(guideTag.listSize){guideScriptSrc+="&resultsPerPage="+guideTag.listSize;} if(guideTag.startingDocNum){guideScriptSrc+="&startingDocNum="+guideTag.startingDocNum;} var query=bnPageInfo.getBNParams()["bn_q"];if(!query)query=guideTag.query;if(query){guideScriptSrc+="&query="+encodeURIComponent(query);guideTag.query=query;}else{guideTag.referrer=bnPageInfo.getReferrerURL();} if(guideTag.referrer){guideScriptSrc+="&referrer="+encodeURIComponent(guideTag.referrer);} guideTag.isFallback=false;if(guideTag.fallback){guideScriptSrc+="&fallback="+encodeURIComponent(guideTag.fallback);} var pageURL=guideTag.getParam("url",bnPageInfo.getURL());var listUrls=guideTag.getParam("listUrls",null);if(listUrls&&listUrls.length>0){for(var ixUrl=0;ixUrl0){for(var ixTrail=listUrls.length-1;ixTrail>=0;ixTrail--){if(listUrls[ixTrail]!=pageURL){guideScriptSrc+="&url="+encodeURIComponent(listUrls[ixTrail]);}}}}else{pageURL=bnCommon.addURLMetaKeys(pageURL,guideTag.metaKeys);guideScriptSrc+="&url="+encodeURIComponent(pageURL);} guideScriptSrc+="&appendParams="+encodeURIComponent(guideTag.getParam("appendParams",""));guideScriptSrc+="&rankParam="+encodeURIComponent(guideTag.getParam("rankParam",""));if(guideTag.urlFilter)guideScriptSrc+="&urlFilter="+encodeURIComponent(guideTag.urlFilter);if(guideTag.attrFilter)guideScriptSrc+="&attrFilter="+encodeURIComponent(guideTag.attrFilter);if(guideTag.ctxAttrList)guideScriptSrc+="&ctxAttrList="+encodeURIComponent(guideTag.ctxAttrList);if(guideTag.attrSort)guideScriptSrc+="&attrSort="+encodeURIComponent(guideTag.attrSort);if(guideTag.sortSize)guideScriptSrc+="&sortSize="+guideTag.sortSize;if(guideTag.days)guideScriptSrc+="&days="+guideTag.days;if(guideTag.oe)guideScriptSrc+="&oe="+guideTag.oe;if(bnCommon.hasAnyProperty(guideTag.attrs)){guideScriptSrc+="&contextAttrs="+bnCommon.objectToJSON(guideTag.attrs);} var cond=bnPolicy.get("inf","cd");if(cond)guideScriptSrc+="&condition="+encodeURIComponent(cond);if(this.socialGuide){guideScriptSrc+="&social=";if(this.socialShow){if(this.socialLoggedIn){guideScriptSrc+=bnConstants.GUIDE_SOCIAL_SHOW_GUIDE;}else{guideScriptSrc+=bnConstants.GUIDE_SOCIAL_SHOW_LOGIN;}}else{guideScriptSrc+=bnConstants.GUIDE_SOCIAL_HIDE_LOGIN;}} if(this.socialShow&&this.networkInfo){networkInfo=this.networkInfo;var limit,value;if(networkInfo.groupIds&&!networkInfo.groupIds.isEmpty()){limit=bnConstants.MAX_URL_LENGTH-guideScriptSrc.length-10-4;if(limit<0)limit=0;value=networkInfo.groupIds.toString(limit);if(value&&value!=""){guideScriptSrc+="&groupIds="+value;}} if(networkInfo.friendIds&&!networkInfo.friendIds.isEmpty()){limit=bnConstants.MAX_URL_LENGTH-guideScriptSrc.length-11-4;if(limit<0)limit=0;value=networkInfo.friendIds.toString(limit);if(value&&value!=""){guideScriptSrc+="&friendIds="+value;}}} var eids=bnCommon.getAllGuideContainersPresent();if(eids.length>0){var eidstr='';for(var i=0;i0){if(rtObj.bnURL.substr(l-6)!=bnConstants.AJAX_URL){bnURL+=bnConstants.AJAX_URL;}} bnURL+="?reqID="+this.ajaxResourceId;bnURL+="&userId="+bnUser.getUserId(this.myTag);bnURL+="&customerId="+this.myTag.customerId;bnURL+="&code="+this.myTag.code;var referrer=bnPageInfo.getReferrerURL();if(referrer)bnURL+="&referrer="+encodeURIComponent(referrer);var cond=bnPolicy.get("inf","cd");if(cond)bnURL+="&condition="+encodeURIComponent(cond);for(var attr in rtObj.params){bnURL+="&"+attr+"="+encodeURIComponent(rtObj.params[attr]);} bnURL+="&v=1";return bnURL;} BNAjaxHandler.prototype.show=function(theTag){this.myTag=theTag;this.myRegistry=new Object();this.initialized=true;} BNAjaxHandler.prototype.send=function(rtObj){if(!this.initialized){bnLog.log("WARN: ajax handler is not initialized - call execute on it");return;} this.lastReqId++;this.ajaxResourceId=bnConstants.AJAX_RESOURCE_PREFIX+this.lastReqId;this.myRegistry[this.ajaxResourceId]=rtObj;var thisAjaxResourceId=this.ajaxResourceId;var resultsAreInProxyFn=function(){bnAjaxHandler.resultsAreIn(thisAjaxResourceId);};bnResourceManager.waitForResource(this.ajaxResourceId,resultsAreInProxyFn,this.getHandlerAddress(rtObj));bnTagManager.invokeCallBack(this.ajaxResourceId,this.myTag);} BNAjaxHandler.prototype.resultsAreIn=function(reqId){var rtObj=this.getRTObject(reqId);if(!rtObj){bnLog.log('AJAX RESULTS HANDLER - empty runtime object');return;} if(rtObj.isSuccess){rtObj.onSuccess(rtObj.responseText);}else{rtObj.onFailure(rtObj.responseText);}} BNAjaxHandler.prototype.getRTObject=function(reqId){return this.myRegistry[reqId];} var bnAjaxHandler=new BNAjaxHandler();bnTagManager.registerTagHandler(bnAjaxHandler.myType,bnAjaxHandler);