(function( blueConic, undefined ) {var ps='https://plugins.blueconic.net/';var pf='/gallery/';(function(){var a=false,b=/xyz/.test(function(){xyz})?/\b_super\b/:/.*/;this.BCClass=function(){};BCClass.extend=function(g){var f=this.prototype;a=true;var e=new this();a=false;for(var d in g){e[d]=typeof g[d]=="function"&&typeof f[d]=="function"&&b.test(g[d])?(function(h,i){return function(){var k=this._super;this._super=f[h];var j=i.apply(this,arguments);this._super=k;return j}})(d,g[d]):g[d]}function c(){if(!a&&this.init){this.init.apply(this,arguments)}}c.prototype=e;c.constructor=c;c.extend=arguments.callee;return c}})();var InteractionType=BCClass.extend({init:function(a){},getPreloadProperties:function(){return[]},getContent:function(){},onEvent:function(){},importLibraries:function(c){var e=[];var a=[];if(!c||c.length===0){return}for(var b=0;b<c.length;b++){var d=c[b];if(d&&d.sharing==="none"){e.push(d.url)}else{a.push(d.url)}}blueConic.fn.importLibraries.call(this,e);blueConic.fn.importAndCacheLibraries.call(this,a)}});(function(){ var InteractionTypeImpl=InteractionType.extend({
    init: function(a,b){
        const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);

        if(urlParams.get('converted') === "1"){
            //fire event
            chartbeat('trackConversion'); 
            console.log("[BC Log] Chartbeat conversion thrown");
        }
        console.log("[BC Log] Chartbeat conversion checking");
    }
});var a = [];var i='chartbeat_conversion';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/chartbeat_conversion/ts_e4abdf3c8da37b3ed15b8b38dc22696b/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.context=b,this.profile=this.context.getProfile();var c=this.context.getParameters();this.storeId=c.storeId&&c.storeId[0]?c.storeId[0]:null,this.metadata=c.metadata&&c.metadata[0]?c.metadata[0]:null,this.requiredOptionSet=c.requiredOptionSet&&c.requiredOptionSet[0]&&'true'===c.requiredOptionSet[0]},onLoad:function(){if(this.storeId){var a=this.metadata?this.blueConicClient.json.parse(this.metadata):null,b=new window.BlueConicMetaDataService(this.jQuery,a,'article');b.blueConicClient=this.blueConicClient;var c=b.getItemData(a),d='article'===c.pageType&&(c.publicationDate||this._getPublicationDate());if(d&&this.requiredOptionSet)for(var e=['id','url','type'],f=0;f<a.length;f++)a[f].required&&-1===e.indexOf(a[f].fieldId)&&(d=!!b.getFieldValue(a[f])&&d);if(d&&/\.(sfchronicle|houstonchronicle|expressnews)\.com/.test(document.location.href)&&(d=this._isPremium()),d&&/\.(sfgate|chron)\.com/.test(document.location.href)&&/[?&]t=/.test(document.location.search)&&(d=this._isPremium()),c.url&&c.itemId&&d){var g=this._makeMetaDataHash(b,a);this._handleView(c.itemId,c.url,g,b)}this._check404Page(c.itemId,window.location.toString())}},_makeMetaDataHash:function(a,b){var c=a.getMetaDataValues(b);return this.md5(this.blueConicClient.json.stringify(c))},_handleView:function(a,b,c,d){this.referrer=document.referrer;var e=this.referrer.replace(/http[s]?:\/\/(.*?)(:|\?|\/|$).*/,'$1'),f=window.location.hostname,g={storeId:this.storeId,action:'view',itemId:a,url:b,profileId:this.profile.getId(),isEntrypage:e!==f,hash:c},h=d.getLastModifiedInMs();h&&(g.lastmodified=h),this.blueConicClient.recommendation.createEvent(g)},_getPublicationDate:function(){var a=this.jQuery('.article-title .timestamp,.article-share .timestamp').attr('title');if(a)return a;var b=this.jQuery('meta[name="date.release"]').attr('content'),c=this.jQuery('meta[name="time.release"]').attr('content');if(b&&c){var d=b.split('/'),e=c.split(':');return a=new Date(d[0],d[2]-1,d[1],e[0],e[1]),a.toISOString()}},_isPremium:function(){return window.HDN&&window.HDN.dataLayer&&window.HDN.dataLayer.paywall&&'isPremium'===window.HDN.dataLayer.paywall.premiumStatus},_getLastModifiedInMs:function(){var a=this.metaDataService.getLastModifiedInMs();if(a)return a;var b=this.jQuery('.article-title .timestamp').text();if(b&&-1!==b.indexOf('Update'))return isNaN(new Date(this._getPublicationDate()).getTime())?null:new Date(this._getPublicationDate()).getTime();if(b=this.jQuery('span.datestamp span.updated').text(),b&&-1!==b.indexOf('Update')){var c=b.replace('Updated: ','').replace(',','').replace(/(pm|am)/,' $1');return isNaN(new Date(c).getTime())?null:new Date(c).getTime()}},_check404Page:function(a,b){for(var c,d=[this.jQuery('title').text(),this.jQuery('meta[property="description"]').attr('content'),this.jQuery('meta[property="og:title"]').attr('content'),this.jQuery('h1').text()],e=['not found','404','niet gevonden','sorry','probleem'],f=!1,g=this.storeId,h=0;h<d.length;h++)if(c=d[h],!!c)for(var i,k=0;k<e.length;k++)if(i=e[k]||'',-1!==c.toLowerCase().indexOf(i)){f=!0;break}f&&this.jQuery.ajax({url:b,type:'HEAD',statusCode:{404:this.jQuery.proxy(function(){this.blueConicClient.recommendation.createEvent({itemId:a,url:a,storeId:g,lastmodified:new Date().getTime()})},this)}})}});var a = [];var i='connection_content_collector_hearst';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});a.push({url: '/plugins/connection_content_collector_hearst/js/metaDataService/metaDataService.js', sharing: 'local'});a.push({url: '/plugins/connection_content_collector_hearst/lib/md5.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/connection_content_collector_hearst/ts_b82039281d85ddfca42d7c792ec3ac84/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({PF_PROPERTY_PREFIX:"dlpf",BLUECONIC_EVENT_PREFIX:":",init:function(t,e){this.blueConicClient=t,this.context=e||null,this.profile=this.context.getProfile(),this.parameters=this.context.getParameters(),this.objectName=this.parameters.objectname?this.parameters.objectname[0]:this.parameters.objectname,this._goals=[];var a=e.getGoals().reduce((function(t,e){return t[e.getId()]=!0,t}),{});if(this.parameters.goalParameters)for(var i=0;i<this.parameters.goalParameters.length;i++){var n=t.json.parse(this.parameters.goalParameters[i]);n.active&&a[n.id]&&this._goals.push(n)}this.connectionContext={LAST_PUSH_PROPERTY:this.PF_PROPERTY_PREFIX+"lt"+this.context.getInteractionId(),VARIABLE_STATE_PUSH_PROPERTY:this.PF_PROPERTY_PREFIX+"st"+this.context.getInteractionId(),profile:this.profile,variables:[],SENT_TO_SYSTEM_PROPERTY:"sent_to_system",SENT_TO_CONNECTION_PROPERTY:"sent_to_connection",RECEIVED_FROM_SYSTEM_PROPERTY:"received_from_system",RECEIVED_FROM_CONNECTION_PROPERTY:"received_from_connection"}},initDataLayerUtil:function(){this.bcConnectionUtil.md5Lib=this.md5,this._bcDatalayerUtil=new this.BlueConicDataLayerUtil(this.objectName,this.blueConicClient,this.bcConnectionUtil,this.context,this.connectionContext,this.profile),this._bcDatalayerUtil.LAST_PUSH_PROPERTY=this.PF_PROPERTY_PREFIX+"lt"+this.context.getInteractionId(),this._bcDatalayerUtil.VARIABLE_STATE_PUSH_PROPERTY=this.PF_PROPERTY_PREFIX+"st"+this.context.getInteractionId()},onLoad:function(){this.initDataLayerUtil();var t=this,e=0;"true"!==(this.parameters.createDatalayer?this.parameters.createDatalayer[0]:this.parameters.createDatalayer)||window[this.objectName]||(window[this.objectName]={}),function dataLayerReady(){if(t._bcDatalayerUtil.getDataLayer())t._handleGoals();else{if(e>20)return;e++,window.setTimeout(dataLayerReady,250)}}.call(this)},_handleGoals:function(){for(var t=0;t<this._goals.length;t++){var e=this._goals[t],a=e.parameters.segment?e.parameters.segment[0]:null;this._bcDatalayerUtil.visitorInSegment(a)&&("export"===e.type&&this._handleExportGoal(e.parameters,e.id),"import"===e.type&&this._handleImportGoal(e.parameters))}},_handleImportGoal:function(t){this._bcDatalayerUtil.getDataLayer()&&this._bcDatalayerUtil.doImport(t)},_handleExportGoal:function(t,e){this._bcDatalayerUtil.doExport(t,e)},getPreloadProperties:function(){for(var t=[this.connectionContext.SENT_TO_SYSTEM_PROPERTY,this.connectionContext.SENT_TO_CONNECTION_PROPERTY,this.connectionContext.RECEIVED_FROM_SYSTEM_PROPERTY,this.connectionContext.RECEIVED_FROM_CONNECTION_PROPERTY],e=0;e<this._goals.length;e++){var a=this._goals[e];if("export"===a.type){t.push(this.PF_PROPERTY_PREFIX+"st"+this.context.getInteractionId()+"_"+a.id),t.push(this.PF_PROPERTY_PREFIX+"lt"+this.context.getInteractionId()+"_"+a.id);for(var i=this.blueConicClient.json.parse(a.parameters.exportMapping),n=0;n<i.length;n++)"property"===i[n].from.dataType&&i[n].from.values.length>0&&t.push(i[n].from.values[0].id)}else for(var o=this.blueConicClient.json.parse(a.parameters.importMapping),r=0;r<o.length;r++)o[r].to.values.length>0&&t.push(o[r].to.values[0].id)}return t}});var a = [];var i='connection_datalayer';a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.2.5/frontend/src/node_modules/@blueconic/connection_lib/connection_lib.js', sharing: 'local'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.2.5/frontend/src/node_modules/@blueconic/datalayer_lib/datalayer_lib.js', sharing: 'local'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.2.5/frontend/src/lib/jsonpath.min.js', sharing: 'local'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.2.5/frontend/src/lib/md5.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.2.5/'}]);})();(function(){ var PUSH_FREQUENCY_TYPES={ONLY:"only",PLC:"plc"},InteractionTypeImpl=InteractionType.extend({PF_PROPERTY_PREFIX:"tlpf",STANDARD_EVENTS:["ViewContent","Search","AddToCart","AddToWishlist","InitiateCheckout","AddPaymentInfo","Purchase","Lead","CompleteRegistration"],MIGRATED_SEGMENT_ID:"migrated-segment",SENT_TO_SYSTEM_PROPERTY:"sent_to_system",SENT_TO_CONNECTION_PROPERTY:"sent_to_connection",init:function(e,t){this.blueConicClient=e,this.context=t,this.profile=this.context.getProfile(),this.parameters=this.context.getParameters(),this._migrate(),this.pixelId=this.parameters.pixelId[0],this.goals=this._parseGoals(),this.segments=this.blueConicClient.getSegments()},getPreloadProperties:function(){var e=this._getFrontendGoals(this.parameters).reduce((function(e,t){var n=JSON.parse(t.parameters.exportMapping[0]).filter((function(e){return"property"===e.from.dataType&&e.from.values&&e.from.values.length>0})).map((function(e){return e.from.values[0].id}));return e.concat(n)}),[]).concat(this.goals.reduce((function(e,t){return e.push(t.context.LAST_PUSH_PROPERTY),e.push(t.context.VARIABLE_STATE_PUSH_PROPERTY),e}),[]));return e.push(this.SENT_TO_CONNECTION_PROPERTY),e.push(this.SENT_TO_SYSTEM_PROPERTY),e},onLoad:function(){if(0!==this.goals.length&&this.pixelId){this._addVariablesToGoals(),this._createFacebookScript(),window.fbq("init",this.pixelId);for(var e=0;e<this.goals.length;e++)this._handleGoal(this.goals[e].goal,this.goals[e].context)}},_addVariablesToGoals:function(){this.goals.forEach((function(e){var t=[];e.goal.exportMapping.forEach((function(n){if(e.goal.pushFrequency===PUSH_FREQUENCY_TYPES.ONLY){var i=n.from;this.bcConnectionUtil.getVariableValue(i,e.context)&&(i.key=n.to.values[0].id,t.push(i))}})),e.context.variables=t}))},_parseGoals:function(){var e=this._getFrontendGoals(this.parameters);if(0===e.length||!this.pixelId)return[];for(var t=[],n=0;n<e.length;n++)if(this._shouldGoalExecute(e[n])){var i=this._parseGoal(e[n]);t.push({goal:i,context:this._createGoalContext(i)})}return t},_getFrontendGoals:function(e){return e.frontendGoals.map(JSON.parse)},_createFacebookScript:function(){var e,t,n,i,r,a;e=window,t=document,n="script",e.fbq||(i=e.fbq=function(){i.callMethod?i.callMethod.apply(i,arguments):i.queue.push(arguments)},e._fbq||(e._fbq=i),i.push=i,i.loaded=!0,i.version="2.0",i.queue=[],(r=t.createElement(n)).async=!0,r.src="https://connect.facebook.net/en_US/fbevents.js",(a=t.getElementsByTagName(n)[0]).parentNode.insertBefore(r,a))},_parseGoal:function(e){var t=e.parameters;return t.exportMapping=JSON.parse(this._getValue("exportMapping",t)),t.pushFrequency=this._getValue("pushFrequency",t),t.exportSegment=this._getValue("exportSegment",t),t.eventName=this._getValue("eventName",t),t.events=[],t.triggerEvent&&t.events.push(t.triggerEvent),t.pushFrequency===PUSH_FREQUENCY_TYPES.PLC&&t.events.push(this.blueConicClient.event.onProfilePermissionChange),t},_getValue:function(e,t){return t[e]&&t[e][0]||null},_getValues:function(e,t){return t[e]?t[e]:[]},_handleGoal:function(e,t){if(!1!==this._validSegment(e.exportSegment)){var n=this;e.events.forEach((function(i){n.blueConicClient.event.subscribe(i,n,(function(){setTimeout((function(){n.profile.loadValues(n.preloadProperties,n,(function(){n._pushGoalData(e,t)}))}),200)}))})),this.bcConnectionUtil.doPush(t)&&this._pushGoalData(e,t)}},_pushGoalData:function(e,t){for(var n={},i=!1,r=0;r<e.exportMapping.length;r++){var a=e.exportMapping[r];if(a.from){var s=this.bcConnectionUtil.getVariableValue(a.from,t,!0).filter((function(e){return null!==e&&e!==undefined}));s&&s.length>0&&(n[a.to.values[0].id]=1===s.length?s[0]:s,i=!0)}}if(i){var o=e.eventName||"BlueConic";this._isStandardEvent(o)?window.fbq("track",o,n):window.fbq("trackCustom",o,n),this.bcConnectionUtil.setSyncProperties(this.context,this.profile,[this.SENT_TO_SYSTEM_PROPERTY,this.SENT_TO_CONNECTION_PROPERTY])}},_validSegment:function(e){if(e===this.MIGRATED_SEGMENT_ID)return!0;for(var t=0;t<this.segments.length;t++)if(this.segments[t].id===e)return!0;return!1},_createGoalContext:function(e){return{LAST_PUSH_PROPERTY:this.PF_PROPERTY_PREFIX+"lt"+this.context.getInteractionId(),VARIABLE_STATE_PUSH_PROPERTY:this.PF_PROPERTY_PREFIX+"st"+this.context.getInteractionId(),push_frequency:e.pushFrequency||null,profile:this.profile,variables:[]}},_shouldGoalExecute:function(e){return this.context.getGoals().some((function(t){return t.getId()===e.id}))},_isStandardEvent:function(e){for(var t=0;t<this.STANDARD_EVENTS.length;t++)if(e===this.STANDARD_EVENTS[t])return!0;return!1},_migrate:function(){(this.parameters.version&&this.parameters.version[0]?parseInt(this.parameters.version[0]):1)<3&&this._migrateToV3()},_migrateToV3:function(){var e=this.parameters.eventName,t=this.parameters.push_frequency,n=JSON.parse(this.parameters.variables).map((function(e){return{from:{typeId:e.type,values:[{id:e.property}]},to:{typeId:"text",dataType:"text",values:[{id:e.key}]}}}));this.parameters.frontendGoals=[],this.parameters.frontendGoals.push(JSON.stringify({id:"migrated-goal-"+Math.round(1e3*Math.random()),active:!0,type:"export-pixel",parameters:{exportMapping:[JSON.stringify(n)],eventName:e,triggerEvent:null,pushFrequency:t,exportSegment:[this.MIGRATED_SEGMENT_ID]}}))}});var a = [];var i='connection_facebook_ads';a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/4.5.0/frontend/src/node_modules/@blueconic/connection_lib/connection_lib.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/4.5.0/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(e,t){this.blueConicClient=e,this.context=t||null,this.parameters=this.context.getParameters(),this.profile=e.profile.getProfile(),this.isInEditMode=e.isInEditMode(),this._createdElements=[],this.parameters&&this.parameters.content&&(this._fragment=this._createFragment(this.parameters.content))},_createFragment:function(e){var t=document.createElement("div");t.innerHTML=e;for(var n=t.getElementsByTagName("div"),i=0;i<n.length;i++)n[i].getAttribute("data-bc-external")&&(n[i].innerHTML="");return t},onLoad:function(){if(this.element=this.context.getDOMElement(),this.element){window.bc=window.bc||{},window.bc.jQuery=this.jQuery,window.bc.$=this.jQuery;var e=this.element.cloneNode(!0),t=this;this.loadInteraction((function(n,i){if(n)return console.error("[BC] Content interaction couldn't be loaded because of the following error(s)",n),void(t.isInEditMode||(console.error("[BC] The element will be restored to it's previous content"),t._createdElements.forEach((function(e){e.remove()})),t.element.replaceWith?t.element.replaceWith(e):t.element.innerHTML=e.innerHTML));t._createdElements=i.createdElements,t.isInEditMode?t.blueConicClient.event.publish("contentinteractiontype.interactionLoaded",{interaction:t}):t.blueConicClient.createEvent("VIEW",t.context.getInteractionId())}))}},loadInteraction:function(e,t){var n="boolean"!=typeof(t=t||{}).loadContent||t.loadContent,i=window._bcp.interactionUtil,r=this.getValue("content");r||(r=this.element.innerHTML);var l=[];n&&l.push(i.createContentHandler({content:r,interactionId:this.context.getInteractionId(),bcEvent:this.blueConicClient.event,isInEditMode:this.isInEditMode,jQuery:this.jQuery})),l.push(i.createCssHandler({cssUrl:this.getValue("styling_css")}),i.createAdvancedHandler({blueConicClient:this.blueConicClient,interactionId:this.context.getInteractionId(),clickEventSelector:this.getValue("click_event_selector"),jQuery:this.jQuery}),i.createJavaScriptHandler({interactionId:this.context.getInteractionId(),javaScriptUrls:this.getValues("javascript_urls"),inlineJavaScript:this.getValue("javascript"),isInEditMode:this.isInEditMode})),i.runHandlers(this.element,l,e)},getPreloadProperties:function(){for(var e,t=this.context.getParameters().content+"",n=/data-bc-preload="([^"]*)"/g,i=[];null!==(e=n.exec(t));)for(var r=e[1].split(","),l=0;l<r.length;l++)i.push(r[l]);return i||[]},getContent:function(){return this.loadInlineStyling(),this._fragment?this._fragment.innerHTML:null},loadInlineStyling:function(){var e=this.getValue("styling_css_inline");e?(this._inlineStylingElement||(this._inlineStylingElement=document.createElement("style"),document.head.appendChild(this._inlineStylingElement),this._createdElements.push(this._inlineStylingElement)),this._inlineStylingElement.innerHTML=e):this._inlineStylingElement&&(this._inlineStylingElement.remove(),this._inlineStylingElement=null)},onMessageReceived:function(e){this.blueConicClient.event.publish("contentinteractiontype.messageReceived",e)},getValue:function(e){return this.parameters[e]&&this.parameters[e][0]?this.parameters[e][0]:null},getValues:function(e){return this.parameters[e]||[]}});var a = [];var i='contentinteractiontype';a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.1/frontend/src/node_modules/@blueconic/jquery-x-jquerymigrate/load_jQuery3_5_X_jQueryMigrate.js', sharing: 'local'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.1/frontend/src/scripts/handlerUtil.js', sharing: 'none'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.1/frontend/src/scripts/handleCss.js', sharing: 'none'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.1/frontend/src/scripts/handleContent.js', sharing: 'none'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.1/frontend/src/scripts/handleJavaScript.js', sharing: 'none'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.1/frontend/src/scripts/handleAdvanced.js', sharing: 'none'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.1/'},{ id : 'html', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'html/1.0.10/'},{ id : 'string', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'string/1.0.1/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({html:{nl:{content:'<div class="bcCSContent">Plaats hier uw content</div>'},"default":{content:'<div class="bcCSContent">Place your content here</div>'}},init:function(a,b){this.blueConicClient=a,this.context=b?b:null,this.profile=a.profile.getProfile(),this.element=this.context.getDOMElement(),this.identifier='bc_'+this.context.getInteractionId(),this.parameters=this.context.getParameters(),this.currentInsertType=this.parameters.inserttype&&this.parameters.inserttype[0]?this.parameters.inserttype[0]:'replace','replacecontainer'!==this.currentInsertType||document.getElementById(this.identifier)||this._hidePosition();var c=this.parameters.content+'';this.htmlFragment=this._createElement(c),this._lastEvent=null,this._inlineCss=null,this._lastCheckDate=null,this._timeoutID=null},getPreloadProperties:function(){return this.htmlFragment?this._getPropertiesFromPlaceholders(this.htmlFragment.innerHTML):[]},getContent:function(){return(this._handleStyling(),!this.htmlFragment)?null:(this.element||(this.element=this.context.getDOMElement()),'replace'===this.currentInsertType)?(this._emptyElementsWithAttribute(this.htmlFragment,'div','data-bc-external'),this.htmlFragment.innerHTML):void 0},onUpdate:function(){this.currentInsertType!==this.context.getParameters().inserttype[0]&&document.location.reload()},onLoad:function(){window.bc=window.bc||{},window.bc.jQuery=this.jQuery,window.bc.$=this.jQuery,this.currentInsertType&&this._placeContent()},onMessageReceived:function(a){a.parameters&&(this.parameters=a.parameters),'updateStyling'===a.action&&(this.inlineCss&&(document.head.removeChild(this.inlineCss),this.inlineCss=null),this._handleStyling())},_hidePosition:function(){this.styleIdentifier='bcCS'+this.context.getInteractionId();var a=this.context.getPosition()+' {opacity: 0 !important}',b=document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0],c=document.createElement('style');c.type='text/css',c.id=this.styleIdentifier,c.styleSheet?c.styleSheet.cssText=a:c.innerHTML=a,b.appendChild(c)},_showPosition:function(){this.jQuery('#'+this.styleIdentifier).remove()},_placeContent:function(){var a=this.element||this.context.getDOMElement();if(a&&(this._handleStyling(),this.blueConicClient.isInEditMode()||this._handleURLs(this.htmlFragment),'replace'===this.currentInsertType?this._replaceContent(a):this.htmlFragment&&(this._emptyElementsWithAttribute(this.htmlFragment,'div','data-bc-external'),this._setContent()),!this.blueConicClient.isInEditMode())){var b=this.parameters.clickselector&&this.parameters.clickselector[0]?this.parameters.clickselector[0]:'';if(b){this.jQuery('body').one('click',b,this.jQuery.proxy(function(a){this._lastEvent&&this._lastEvent.originalEvent===a.originalEvent||this._logClickEvent(a)},this));try{this.jQuery(b).one('click',this.jQuery.proxy(function(a){this.lastEvent=a,this._logClickEvent(a)},this))}catch(a){}}var c=!!this.parameters.forceclick&&('true'===this.parameters.forceclick[0]||!0===this.parameters.forceclick[0]);c&&this.blueConicClient.createEvent('CLICK',this.context.getInteractionId());var d=this.parameters.javascript&&this.parameters.javascript[0]?this.parameters.javascript[0]:'';if(d)try{d=d.replace(/(^|\W)blueConicVariantId(\W|$)/g,'$1"'+this.context.getInteractionId()+'"$2'),this.jQuery('<script>'+d+'</script>').appendTo(this.jQuery('body'))}catch(a){console.error(a)}}},_replaceContent:function(a){this._assureVisibilty(a);var b=this.getContent();if(b){var c=a.nodeName?a.nodeName.toLowerCase():a.nodeName;if(-1===this.blueConicClient.util.array.indexOfArray(['area','base','br','col','command','embed','hr','img','input','keygen','link','meta','param','source','track','wbr'],c)){if(this.blueConicClient.isInEditMode&&this.blueConicClient.isInEditMode())a.innerHTML!==b&&(a.innerHTML=b);else try{this.jQuery(a).html(b)}catch(a){console.error(a)}}else if(a.parentNode){var d=a.parentNode.innerHTML,e=document.createElement('div');e.appendChild(a.cloneNode(!0));var f=e.innerHTML,g=d.replace(f,b);a.parentNode.innerHTML!==g&&(a.parentNode.innerHTML=g)}this._handleComplexObjects(a),this._trackView(a)}},_setContent:function(){var a=this._getElementByPosition(this.context.getPosition());if(a){var b=a.parent().get(0),c=this.jQuery('[data-bc-id="'+this.identifier+'"],#'+this.identifier);if(0<c.length)return this.blueConicClient.isInEditMode&&this.blueConicClient.isInEditMode()?null:(c.replaceWith(this.htmlFragment.innerHTML),this._handleComplexObjects(b),void('prepend'===this.currentInsertType?(a.prev().attr('data-bc-id',this.identifier),this._trackView(a.prev().get(0))):'append'===this.currentInsertType&&(a.next().attr('data-bc-id',this.identifier),this._trackView(a.next().get(0)))));if('prepend'===this.currentInsertType){var d=a.prev();if(0<d.length&&d.attr('data-bc-id')===this.identifier)return;if(this.blueConicClient.isInEditMode&&this.blueConicClient.isInEditMode())a.get(0).parentNode.insertBefore(this.htmlFragment,a.get(0)),this.blueConicClient.functions.setEditableNode('#bc_'+this.context.getInteractionId(),{positionName:'prepend',lockPosition:!0,redrawPosition:!0});else{try{a.before(this.htmlFragment.innerHTML)}catch(a){console.error(a)}var e=a.prev();e.attr('data-bc-id',this.identifier),this._trackView(e.get(0))}}if('append'===this.currentInsertType){var f=a.next();if(0<f.length&&f.attr('data-bc-id')===this.identifier)return;if(this.blueConicClient.isInEditMode&&this.blueConicClient.isInEditMode())a.get(0).parentNode.insertBefore(this.htmlFragment,a.get(0).nextSibling),this.blueConicClient.functions.setEditableNode('#bc_'+this.context.getInteractionId(),{positionName:'append',lockPosition:!0,redrawPosition:!0});else{try{a.after(this.htmlFragment.innerHTML)}catch(a){console.error(a)}var g=a.next();g.attr('data-bc-id',this.identifier),this._trackView(g.get(0))}}if('replacecontainer'===this.currentInsertType){if(this.blueConicClient.isInEditMode&&this.blueConicClient.isInEditMode())a.get(0).parentNode.replaceChild(this.htmlFragment,a.get(0)),this.blueConicClient.functions.setEditableNode('#bc_'+this.context.getInteractionId(),{positionName:'replace container',lockPosition:!0,redrawPosition:!0});else{var h=this.jQuery(this.htmlFragment.innerHTML).replaceAll(a);this._trackView(h.get(0))}this._showPosition()}this.blueConicClient.isInEditMode()&&null===this.context.getInteractionId()&&setTimeout(function(){window.blueConicClient.fn.postMessage('onOpenEditMode',window.blueConicClient.positionHandlers[0])},500),this._handleComplexObjects(b)}},_trackView:function(a){if(!this.blueConicClient.isInEditMode()){var b=!!(this.parameters.trackviewwhenvisible&&this.parameters.trackviewwhenvisible[0])&&'true'===this.parameters.trackviewwhenvisible[0];b?this._isVisible(a)?this.blueConicClient.createEvent('VIEW',this.context.getInteractionId()):(this._lastCheckDate=new Date().getTime(),this.jQuery(document).on('scroll.bcCSP'+this.identifier,this.jQuery.proxy(function(){this._checkVisibility(a)},this)),this.jQuery(window).on('resize.bcCSP'+this.identifier,this.jQuery.proxy(function(){this._checkVisibility(a)},this)),this._checkVisibility(a)):this.blueConicClient.createEvent('VIEW',this.context.getInteractionId())}},_checkVisibility:function(a){var b=new Date().getTime();return 500<=b-this._lastCheckDate&&(this._lastCheckDate=new Date().getTime(),this._isVisible(a))?(this.blueConicClient.createEvent('VIEW',this.context.getInteractionId()),this.jQuery(document).off('scroll.bcCSP'+this.identifier),this.jQuery(window).off('resize.bcCSP'+this.identifier),void clearTimeout(this._timeoutID)):void(clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this.jQuery.proxy(function(){this._checkVisibility(a)},this),1500))},_isVisible:function(a){var b=a.getBoundingClientRect();return 0<=b.top&&b.top<window.innerHeight&&this.jQuery(a).is(':visible')},_logClickEvent:function(a){if(!(a&&a.originalEvent&&a.originalEvent._blueConicLoggedClickEvent===this.context.getInteractionId())){var b=a&&a.target&&a.target.pathname&&a.target.hostname&&0===a.target.pathname.indexOf('/s/')&&-1!==a.target.hostname.indexOf('blueconic');b||(a.originalEvent&&(a.originalEvent._blueConicLoggedClickEvent=this.context.getInteractionId()),this.blueConicClient.createEvent('CLICK',this.context.getInteractionId()))}},_getElementByPosition:function(a){var b=document.getElementById(a);return b=b?this.jQuery(b):this.jQuery(a),b},_createElement:function(a){var b;if(!a)if(this.blueConicClient.isInEditMode()&&('prepend'===this.currentInsertType||'append'===this.currentInsertType)){var c='nl'===this.context.getLocale()?'nl':'default';a=this.html[c].content}else return null;try{b=document.createElement('div'),b.id=this.identifier,b.innerHTML=a}catch(a){return null}return b},_handleURLs:function(a){var b=!!(this.parameters.newwindow&&this.parameters.newwindow[0])&&'true'===this.parameters.newwindow[0];if(b)for(var c=a.getElementsByTagName('a'),d=0,e=c.length;d<e;d++){var f=c[d],g=f.getAttribute('target');g||f.setAttribute('target','_blank')}this._handlePlaceholders(a)},_assureVisibilty:function(a){this.blueConicClient.isInEditMode&&this.blueConicClient.isInEditMode()&&(a.style.minWidth='10px',a.style.minHeight='10px')},_handlePlaceholders:function(a){for(var b=this._getPropertiesFromPlaceholders(a.innerHTML),c=0;c<b.length;c++){var d=b[c],e=this.profile.getValue(d)||'',f=new RegExp('\\$\\{'+d+'\\}','g');a.innerHTML=a.innerHTML.replace(f,encodeURI(e))}},_getPropertiesFromPlaceholders:function(a){for(var b,c=/\$\{([a-zA-Z\-_0-9]+)\}/g,d=[];null!==(b=c.exec(a));)d.push(b[1]);for(var e=/data-bc-preload="([^"]*)"/g,f=[];null!==(b=e.exec(a));)for(var g=b[1].split(','),h=0;h<g.length;h++)f.push(g[h]);return d.concat(f)},_emptyElementsWithAttribute:function(a,b,c){for(var d,e=this.getElementsWithAttribute(a,b,c),f=0,g=e.length;f<g;f++)d=e[f],d.innerHTML=''},getElementsWithAttribute:function(a,b,c){for(var d,e=[],f=a.getElementsByTagName(b),g=0,h=f.length;g<h;g++)d=f[g],d.getAttribute(c)&&e.push(d);return e},_handleComplexObjects:function(a){for(var b=this.getElementsWithAttribute(a,'div','data-bc-pluginid'),c=0;c<b.length;c++){var d=b[c],e=d.getAttribute('data-bc-pluginid'),f=d.getAttribute('data-bc-config');if(f)try{var g=f.replace(/\n/g,'\\\\n').replace(/\r/g,'\\\\r').replace(/\t/g,'\\\\t');f=this.blueConicClient.json.parse(g)}catch(a){f=null}this.blueConicClient.event.publish('bcComplexObject',{plugin:e,config:f,node:d,interactionId:this.context.getInteractionId()}),this.blueConicClient.isInEditMode()||(d.removeAttribute('data-bc-pluginid'),d.removeAttribute('data-bc-config'))}},_handleStyling:function(){var a='bcIS'+this.context.getInteractionId(),b=this.parameters.styling_css_inline&&this.parameters.styling_css_inline[0]?this.parameters.styling_css_inline[0]:'';b&&(this.inlineCss=document.getElementById(a),this.inlineCss||(this.inlineCss=document.createElement('style'),this.inlineCss.id=a,this.inlineCss.innerHTML=b.replace(/&#xd;/gi,''),document.head.appendChild(this.inlineCss)))}});var a = [];var i='contentinteractiontypespecial';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/contentinteractiontypespecial/ts_25b8fc569d2bb21e2b65eaf5782e7c3a/'},{ id : 'boolean', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'boolean/1.0.1/'},{ id : 'html', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'html/1.0.10/'},{ id : 'string', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'string/1.0.1/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({DEFAULT_MAX_AGE:7776000000,MAX_ITEMS:100,SKIP_LIMITED:'limited',RESET_ROLLING:'rolling',RESET_CALENDAR:'calendar',init:function(a,b){this.blueConicClient=a,this.context=b,this.interactionId='cm'+this.context.getInteractionId(),this.historyProperty='_cm_'+this.interactionId,this.profile=this.context.getProfile(),this.parameters=this.context.getParameters(),this.preLoadProperties=[this.historyProperty],this.excludeRules=[];try{this.excludeRules=this.blueConicClient.json.parse(this.parameters.excludeRules[0])}catch(a){}if(0<this.excludeRules.length){var c=this.excludeRules.filter(function(a){return'expression'===a.area.selectedoption&&-1!==a.area.expression.indexOf('getValue')});this.preLoadProperties=this.preLoadProperties.concat(c.map(function(a){return this._getPropertyIdsFromExpression(a.area.expression)},this))}this.includeRules=[];try{this.includeRules=this.blueConicClient.json.parse(this.parameters.includeRules[0])}catch(a){}if(0<this.includeRules.length){var d=this.includeRules.filter(function(a){return'expression'===a.area.selectedoption&&-1!==a.area.expression.indexOf('getValue')});this.preLoadProperties=this.preLoadProperties.concat(d.map(function(a){return this._getPropertyIdsFromExpression(a.area.expression)},this))}this.freeRules=[];try{this.freeRules=this.blueConicClient.json.parse(this.parameters.freeRules[0])}catch(a){}0<this.freeRules.length&&(this.freeRules=this.freeRules.filter(function(a){return!!a.property}),this.preLoadProperties=this.preLoadProperties.concat(this.freeRules.map(function(a){return a.property.id}))),this.expireAt=parseInt(this.parameters.expireAt[0]),isNaN(this.expireAt)&&(this.expireAt=10),this.resetAfter=this.parameters.resetAfter[0],this.uniqueOnly='true'===this.parameters.uniqueOnly[0],this.onceOnly=!!(this.parameters.onceOnly&&'true'===this.parameters.onceOnly[0]),this.now=this.blueConicClient.getCurrentDate(),this.maxAge=this._getMaxAge(),this.delayMetering=!!(this.parameters.delayMetering&&'true'===this.parameters.delayMetering[0]),this.eventSubscribed=!1,this.blueConicClient.event.subscribe(this.blueConicClient.event.onUrlChange,this,function(){this.onLoad()})},getPreloadProperties:function(){return this.preLoadProperties},onLoad:function(){if(this.delayMetering&&!this.eventSubscribed)return this.eventSubscribed=!0,void this.blueConicClient.event.subscribe('cm_start_metering',this,function(){this.onLoad()});var a=this._visitorQualifies();if(a){var b={};try{var c=this.profile.getValue(this.historyProperty);c&&(b=this.blueConicClient.json.parse(this.profile.getValue(this.historyProperty)))}catch(a){}this.history=new this.History(b,this.maxAge,this.now);var d=this._getCurrentView();if(d){var e=!d.isSkippedView||d.isSkippedView&&!!d.skippedFor;e?(this._addViewToHistory(d),!d.isSkippedView&&this._writeExtraProfileProperties(d),this.blueConicClient.profile.updateProfile(this,function(){this._throwEvents(d)})):this._throwEvents(d)}}},_throwEvents:function(a){var b=this._getCurrentViews(a);(a.isHistoricallyAllowedView||a.isHistoricallyAllowedFreeView)&&this.blueConicClient.createEvent('cm_already_viewed'),a.isFreeView?(this.onceOnly&&!a.isHistoricallyAllowedFreeView||!this.onceOnly)&&(this.freeViewTracker.consumedFreeCount===this.freeViewTracker.totalFree?this.blueConicClient.createEvent('cm_last_free_view'):this.blueConicClient.createEvent('cm_free_view_'+this.freeViewTracker.consumedFreeCount)):((this.onceOnly&&!a.isHistoricallyAllowedView&&!a.isSkippedView||!this.onceOnly)&&(1===b?this.blueConicClient.createEvent('cm_firstview'):b===this.expireAt-1?this.blueConicClient.createEvent('cm_lastview'):b<this.expireAt&&this.blueConicClient.createEvent('cm_view_'+b)),b>=this.expireAt&&this.blueConicClient.createEvent('cm_exceeded'),a.isSkippedView&&this.blueConicClient.createEvent('cm_excluded'));var c=this.parameters.bottomFrom&&this.parameters.bottomFrom[0]?parseInt(this.parameters.bottomFrom[0]):null,d=this.parameters.bottomTo&&this.parameters.bottomTo[0]?parseInt(this.parameters.bottomTo[0]):null,e=this.parameters.middleFrom&&this.parameters.middleFrom[0]?parseInt(this.parameters.middleFrom[0]):null,f=this.parameters.middleTo&&this.parameters.middleTo[0]?parseInt(this.parameters.middleTo[0]):null,g=this.parameters.topFrom&&this.parameters.topFrom[0]?parseInt(this.parameters.topFrom[0]):null,h=this.parameters.topTo&&this.parameters.topTo[0]?parseInt(this.parameters.topTo[0]):null;c&&d&&b>=c&&b<=d&&this.blueConicClient.createEvent('cm_bottom'),e&&f&&b>=e&&b<=f&&this.blueConicClient.createEvent('cm_middle'),g&&h&&b>=g&&b<=h&&this.blueConicClient.createEvent('cm_top')},_addViewToHistory:function(a){this._getCurrentViews(a)>=this.expireAt&&!a.isFreeView||(a.isFreeView?this.history.free.push({u:a.url,ff:a.freeFor,ts:a.timestamp}):a.isSkippedView?this.history.skipped.push({u:a.url,sf:a.skippedFor,ts:a.timestamp}):(this.history.included.push({u:a.url,v:a.includeValue,ts:a.timestamp}),a.isAddedToHistory=!0),this.history.included.length>this.MAX_ITEMS&&(this.history.included.sort(function(c,a){var b=c.ts,d=a.ts;return b<d?-1:b>d?1:0}),this.history.included.shift()),this.profile.setValue(this.historyProperty,this.blueConicClient.json.stringify(this.history)))},_writeExtraProfileProperties:function(a){var b=this._getCurrentViews(a),c=this.parameters.expireAtProperty&&this.parameters.expireAtProperty[0]?this.parameters.expireAtProperty[0]:null,d=this.parameters.numViewsProperty&&this.parameters.numViewsProperty[0]?this.parameters.numViewsProperty[0]:null,e=this.parameters.numViewsLeftProperty&&this.parameters.numViewsLeftProperty[0]?this.parameters.numViewsLeftProperty[0]:null,f=this.parameters.numFreeViewsProperty&&this.parameters.numFreeViewsProperty[0]?this.parameters.numFreeViewsProperty[0]:null,g=this.parameters.numFreeViewsLeftProperty&&this.parameters.numFreeViewsLeftProperty[0]?this.parameters.numFreeViewsLeftProperty[0]:null;if(c&&'null'!==c&&this.profile.setValue(c,this.expireAt),d&&'null'!==d&&this.profile.setValue(d,b<=this.expireAt?b:this.expireAt),e&&'null'!==e&&this.profile.setValue(e,b<this.expireAt?this.expireAt-b:0),a.isFreeView&&(f&&'null'!==f&&this.profile.setValue(f,this.freeViewTracker.consumedFreeCount),g&&'null'!==g)){var h=this.freeViewTracker.totalFree-this.freeViewTracker.consumedFreeCount;this.profile.setValue(g,0<h?h:0)}},_getCurrentView:function(){var a=(this.jQuery('meta[property="og:url"]').attr('content')||document.location.href).toLowerCase(),b=document.referrer.toLowerCase(),c=new this.PageView(a,b,this.now);return c.isHistoricallyAllowedView=this._isHistoricallyAllowed(a),c.includeValue=this._getIncludeValue(c),0<c.includeValue?(c.isSkippedView=this._isPageViewSkipped(c),this._getCurrentViews(c)>=this.expireAt&&this._setPageViewFree(c),c):null},_getIncludeValue:function(a){for(var b,c=0;c<this.includeRules.length;c++)if(b=this.includeRules[c],this._isRuleApplicable(b,a))return b.views;return 0},_isPageViewSkipped:function(a){var b=new this.SkippedViewTracker(this),c=this;return this.excludeRules.filter(function(b){return c._isRuleApplicable(b,a)}).some(function(d){if(d.skip.selectedoption!==c.SKIP_LIMITED)return!0;return!(b.skipped[d.id]=b.skipped[d.id]?b.skipped[d.id]+1:1,!(b.skipped[d.id]<=d.skip.views))&&(a.skippedFor=d.id,!0)})},_setPageViewFree:function(a){var b=this;this.freeViewTracker=new this.FreeViewTracker(this),a.isHistoricallyAllowedFreeView=this._isHistoricallyAllowedFree(a.url),this.freeRules.filter(function(c){return b._isRuleApplicable(c,a)}).forEach(function(c){b.freeViewTracker.totalFree+=c.views,a.isFreeView||(a.isHistoricallyAllowedFreeView?(a.freeFor=c.id,a.isFreeView=!0):(b.freeViewTracker.free[c.id]=b.freeViewTracker.free[c.id]?b.freeViewTracker.free[c.id]+1:1,b.freeViewTracker.free[c.id]<=c.views&&(a.freeFor=c.id,a.isFreeView=!0,b.freeViewTracker.consumedFreeCount++)))})},_isRuleApplicable:function(a,b){var c=a.area.selectedoption;if('url'===c||'referrer'===c){var d='url'===c?b.url:b.referrer;if(a.anyWord||this._URLMatchesWords(d,a.containsmatches,a.words))return!0}else if('selector'===c){var e=this._getContent(a.area.selector,!0);if(e&&a.anyWord)return!0;if(a.area.selector&&a.words&&this._contentMatchesWords(e,a.containsmatches,a.words))return!0}else if('variable'===c){var f=this._getVariableValue(a.area.variable);if(f&&a.anyWord)return!0;if(f&&this._contentMatchesWords(f,a.containsmatches,a.words))return!0}else if('expression'===c){var g=this._getContent(a.area.expression,!1);if(g&&a.anyWord)return!0;if(g&&this._contentMatchesWords(g,a.containsmatches,a.words))return!0}else if('property'===c){var h=this.profile.getValues(a.property.id);if(0<h.length&&a.anyWord)return!0;var i=this;return h.some(function(b){return a.words&&i._contentMatchesWords(b,a.containsmatches,a.words)||a.dateTime&&!isNaN(parseInt(b))&&i.now.getTime()-parseInt(b)<=i.maxAge})}return!1},_isHistoricallyAllowed:function(a){if(!this.uniqueOnly)return!1;var b=this.history.included.filter(function(b){return b.u===a});return 0<b.length},_isHistoricallyAllowedFree:function(a){if(!this.uniqueOnly)return!1;var b=this.history.free.filter(function(b){return b.u===a});return 0<b.length},_getCurrentViews:function(a){for(var b,c=0,d=[],e=0;e<this.history.included.length;e++)(b=this.history.included[e],!(this.uniqueOnly&&-1!==this.blueConicClient.util.array.indexOfArray(d,b.u)))&&(d.push(b.u),c+=b.v);var f=this._isHistoricallyAllowed(a.url)||a.isAddedToHistory;return f||a.isSkippedView||c!==this.expireAt-1||(c+=a.includeValue),c},_visitorQualifies:function(){var a=[];try{a=this.blueConicClient.json.parse(this.parameters.segments)}catch(a){}if(0===a.length)return!0;var b=this.blueConicClient.getSegments();if(0===b.length)return!1;for(var c,d=0;d<b.length;d++){c=b[d];for(var e,f=0;f<a.length;f++)if(e=a[f],c.id===e.id)return!0}return!1},_getMaxAge:function(){if(this.resetAfter===this.RESET_ROLLING){var a=this.parameters.resetRolling&&!isNaN(parseInt(this.parameters.resetRolling[0]))?parseInt(1e3*(60*(60*(24*this.parameters.resetRolling[0])))):this.DEFAULT_MAX_AGE;return a}return this.resetAfter===this.RESET_CALENDAR?this.now.getTime()-new Date(this.now.getFullYear(),this.now.getMonth(),1).getTime():this.DEFAULT_MAX_AGE},_contentMatchesWords:function(a,b,c){if(!a||'string'!=typeof a)return!1;a=a.toLowerCase();for(var d=0;d<c.length;d++)if('contains'===b){if(-1!==a.indexOf(c[d].toLowerCase()))return!0;}else if(a===c[d].toLowerCase())return!0;return!1},_URLMatchesWords:function(a,b,c){for(var d=0;d<c.length;d++)if('contains'===b){var e=this._escapeRegularExpressionCharacters(c[d]);try{var f=new RegExp(e,'i');if(f.test(a))return!0}catch(a){}}else if(a===c[d])return!0;return!1},_getContent:function(a,b){var c=null;b||-1===a.indexOf('return ')||(a='(function(jQuery) {'+a+'}(jQuery))');try{c=b&&-1===a.indexOf('jQuery(')?this.jQuery(a):function(a,b,c){return eval('var jQuery = arguments[1]'),eval('var blueConicProfile = arguments[2]'),eval(a)}(a,this.jQuery,this.profile)}catch(a){}if(c&&c instanceof this.jQuery){if(0<c.length){var d=[];return this.jQuery.each(c,this.jQuery.proxy(function(a,b){var c=this.jQuery(b);c.attr('content')?d.push(this._normalizeText(c.attr('content'))):d.push(this._normalizeText(c.text()))},this)),d.join().toLowerCase()}}else if(null!==c&&'undefined'!=typeof c)return'object'==typeof c||'function'==typeof value?JSON.stringify(c).toLowerCase():c.toLowerCase()},_getVariableValue:function(a){for(var b=a.replace('[','.').replace(']','').replace('""',''),c=b.split('.'),d=window[c.shift()];0<c.length;){if(!d)return null;d=d[c.shift()]}return d instanceof Array?d.join().toLowerCase():'object'==typeof d||'function'==typeof d?null:(''+d).toLowerCase()},_escapeRegularExpressionCharacters:function(a){return a=a.replace(/[\\?.{}+]/g,function(a){return'\\'+a}),a=a.replace(/\*/g,'.*'),a},_normalizeText:function(a){return a?this.jQuery.trim(a).replace(/\r\n+|\r+|\n+/gi,'').replace(/\s+/gi,' '):a},_getPropertyIdsFromExpression:function(a){for(var b,c=RegExp(/getValues?\(["']([^"']+)["']\)/,'g'),d=[];null!==(b=c.exec(a));)d.push(b[1]);return d},PageView:function(a,b,c){this.url=a,this.timestamp=c.getTime(),this.referrer=b,this.includeValue=0,this.isSkippedView=!1,this.skippedFor=null,this.isFreeView=!1,this.isHistoricallyAllowedView=!1,this.isAddedToHistory=!1},SkippedViewTracker:function(a){this.skipped={};for(var b,c=[],d=0;d<a.history.skipped.length;d++)b=a.history.skipped[d],a.uniqueOnly&&-1!==a.blueConicClient.util.array.indexOfArray(c,b.u)||(this.skipped[b.sf]=this.skipped[b.sf]?this.skipped[b.sf]+1:1),c.push(b.u)},FreeViewTracker:function(a){this.free={},this.consumedFreeCount=0,this.totalFree=0;for(var b,c=[],d=0;d<a.history.free.length;d++)b=a.history.free[d],a.uniqueOnly&&-1!==a.blueConicClient.util.array.indexOfArray(c,b.u)||(this.free[b.ff]=this.free[b.ff]?this.free[b.ff]+1:1,this.consumedFreeCount++),c.push(b.u)},History:function(a,b,c){function d(a){for(var d=a.length;d--;){var e=a[d];c.getTime()-e.ts>b&&a.splice(d,1)}return a}this.included=a.included?d(a.included):[],this.skipped=a.skipped?d(a.skipped):[],this.free=a.free?d(a.free):[]}});var a = [];var i='contentmeter';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/contentmeter/ts_6efa750efb0a62c79d1c1ef09e747610/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(e,t){this.blueConicClient=e,this.context=t},onLoad:function(){var e=this.blueConicClient,t=this.context.getParameters(),n=this.jQuery;if(t){var r=(t.clickcandidates||[]).map(JSON.parse).map(_updateSelectorCandidate),a=(t.contentcandidates||[]).map(JSON.parse).map(_updateSelectorCandidate),i={},o={},c={};r.forEach((function(e){candidateChecker(e,registerClickHandlers)})),a.forEach((function(e){candidateChecker(e,checkContentHandler)}))}function candidateChecker(t,n){var handler=function(){n(t);var r=o[t.interactionId],a=c[t.selecterarea];r||a||e.position.subscribe(t.selecterarea,null,handler)};e.position.subscribe(t.selecterarea,null,handler),n(t)}function registerClickHandlers(e){for(var t=getHandler(e),r=n(e.selecterarea),a=0,i=r.length;a<i;a++)r[a].addEventListener("click",t,{once:!0})}function checkContentHandler(e){isContentConversionMomentMet(e)&&getHandler(e)()}function isContentConversionMomentMet(e){if(o[e.interactionId])return!1;for(var t=n(e.selecterarea),r=0,a=t.length;r<a;r++)if(_textContains(t[r].textContent,e.words))return!0;return!1}function getHandler(t){return i[t.interactionId]||(i[t.interactionId]=function(i,l){var s=o[i],u=c[t.selecterarea];if(!s&&!u){var d=[];d=(d=l instanceof MouseEvent?r.filter((function(e){var t=!o[e.interactionId],r=n(e.selecterarea).is(event.target),a=n(e.selecterarea).find(event.target).length>0;return t&&(r||a)})):a.filter((function(e){return isContentConversionMomentMet(e)}))).filter((function(e){return e.interactionId!==t.interactionId})),c[t.selecterarea]=!0,c[t.interactionId]=!0,d.forEach((function(e){c[e.selecterarea]=!0,o[e.interactionId]=!0}));var f=d.map((function(e){return e.interactionId}));e.createEvent("CONVERSION",i,null,(function(){e.util.log("CONVERSION event registered. Interaction: ["+i+"]")}),{losingInteractions:f})}}.bind(null,t.interactionId)),i[t.interactionId]}function _textContains(e,t){if(!e||!Array.isArray(t))return!1;var n=t.filter((function(e){return Boolean(e)&&"pre_any"!==e})).map((function(e){return e.trim().toLowerCase()}));if(0===n.length)return!0;for(var r=e.toLowerCase(),a=0,i=n.length;a<i;a++)if(r.indexOf(n[a])>=0)return!0;return!1}function _updateSelectorCandidate(e){var t=e.selecterarea;return/^pre_any/.test(t)?t="html":/^pre_header/.test(t)?t="h1, h2, h3, h4, h5, h6":/^pre_/.test(t)&&(t=t.replace(/^pre_/,"")),e.selecterarea=t,e}}});var a = [];var i='conversionlistenerinteractiontype';a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.1.9/frontend/src/node_modules/@blueconic/jquery-x-jquerymigrate/load_jQuery3_5_X_jQueryMigrate.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.1.9/'}]);})();(function(){ 
var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a;this.context=b?b:null;this.profile=this.context.getProfile();this.targetingParameters=[]},getPreloadProperties:function(){return this._getProfilePropertiesFromParameters()},onLoad:function(){if(this.targetingParameters&&0<this.targetingParameters.length){for(var a=[],b=0;b<this.targetingParameters.length;b++){var c=this.targetingParameters[b],e=c.key,c=this._getParamValue(c);e&&c&&a.push({key:e,value:c})}if("undefined"!==
typeof window.Storage)try{window.localStorage.setItem("bcDFPTargetingParams",this.blueConicClient.json.stringify(a))}catch(g){}var f=0,d=function(){window.bcDFPCallback?window.bcDFPCallback(a):40<f||(f++,window.setTimeout(d,250))};d.call(this)}},_getParamValue:function(a){if((!a.type||"text"===a.type)&&a.text)return a.text;if("property"===a.type&&a.property)return this.profile.getValues(a.property);if("segments"===a.type&&0<this.blueConicClient.getSegments().length){var b=[],c=this.blueConicClient.getSegments();
if(a.segments&&0<a.segments.length)for(var e=0;e<c.length;e++)for(var g=c[e],f=0;f<a.segments.length;f++){var d=a.segments[f];(g.id&&g.id===d.segmentId||g.name===d.segmentName)&&b.push(d.aamCode||d.dcmCode||d.smCode||g.name)}else for(a=0;a<c.length;a++)b.push(c[a].name);return b}},_getProfilePropertiesFromParameters:function(){var a=[],b=this.context.getParameters(),b=b.targeting_parameters?b.targeting_parameters[0]:b.targeting_parameters;if(!b)return a;this.targetingParameters=this.blueConicClient.json.parse(b);
for(b=0;b<this.targetingParameters.length;b++){var c=this.targetingParameters[b];"property"===c.type&&c.property&&a.push(c.property)}return a}});
var a = [];var i='dfpconnection_to';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/dfpconnection_to/ts_e19317762cea0b7a3658deb94c42c3ed/'}]);})();(function(){ !function(){var t=null,e=null,i=null,n=null,o=null;window.InteractionTypeImpl=InteractionType.extend({init:function(t,e){this.blueConicClient=t,this.context=e,this.parameters=this.context.getParameters(),this.customCssElements=[],this.customJsElements=[],this.isInEditMode=this.blueConicClient.isInEditMode(),this._temporyLocation=null,this._contentElement=null,this._openedOnce=!1,this._resetTimeoutId=0,this.baseURL=this.blueConicClient.getBaseURL(this.context.getInteractionTypeId())},onLoad:function(){t=window._bcp.notificationBar.Enums.FLOW_TYPE,e=window._bcp.notificationBar.Enums.POSITION,i=window._bcp.notificationBar.Enums.ENTER_ANIMATION,n=window._bcp.notificationBar.Enums.APPEAR_ON,o=window._bcp.notificationBar.Enums.CLOSE_POSITION,this.parseParameters(),this.isInEditMode&&(window._bcp.notificationBar.NotificationBar.prototype.close=function(){});var r=this;this.loadCustomContent(function(t){if(t)return r.blueConicClient.util.log(t.message);r.addBlueConicEventHandlers()})},parseParameters:function(){this.notificationBarHeight=parseInt(this.getParameter("height")),this.notificationBarHeight=isNaN(this.notificationBarHeight)?window._bcp.notificationBar.Constants.DEFAULT_HEIGHT:this.notificationBarHeight;var r=this.getParameter("location")||"top";this._position="top"===r?e.TOP:e.BOTTOM;var a=this.getParameter("close_position");if(this._closePosition="TOP_LEFT"===a?o.TOP_LEFT:"BOTTOM_RIGHT"===a?o.BOTTOM_RIGHT:o.TOP_RIGHT,this._closePadding=parseInt(this.getParameter("close_padding")),this._closePadding=isNaN(this._closePadding)?10:this._closePadding,void 0===document.body.style.animationName||!0===this.isInEditMode)this._enterAnimation=i.NONE;else switch(this.getParameter("effect")){case"slideIn":this._enterAnimation=i.SLIDE_IN;break;case"fadeIn":this._enterAnimation=i.FADE_IN;break;default:this._enterAnimation=i.NONE}var s=this.getParameters("selected_when");this._appearOnTriggers=[];for(var c=0;c<s.length;c++)switch(s[c]){case"triggerOn":this._appearOnTriggers.push(n.SCROLL_EVENT);break;case"scroll_depth":this._appearOnTriggers.push(n.SCROLL_DEPTH);break;case"click_selector":this._appearOnTriggers.push(n.ELEMENT_CLICKED);break;case"content_condition":this._appearOnTriggers.push(n.CONTENT_VISIBLE)}0===this._appearOnTriggers.length&&this._appearOnTriggers.push(n.PAGE_LOAD);var l=this.getParameter("location_type");this._type="scroll"===l?t.NON_STICKY:t.STICKY},addBlueConicEventHandlers:function(){this.blueConicClient.event.subscribe("closeoverlay",this,function(t,e){e instanceof Array&&e[0]===this.context.getInteractionId()&&this.notificationBar.close()}),this.blueConicClient.event.subscribe(this.blueConicClient.event.onUrlChange,this,function(){this.notificationBar&&this.notificationBar.isVisible&&this.notificationBar.close()})},loadCustomContent:function(t){t||(t=function(){});var e=this;this.callbackChain([this.createContentElement.bind(this),this.loadComplexObjects.bind(this),this.removeTempLocation.bind(this),this.loadCss.bind(this),this.loadCustomCss.bind(this)],function(i){return i?t(i):(e.createNotificationBar(),e.setShowEventTrigger(),e.isInEditMode&&e.blueConicClient.event.publish("notificationBar.interactionLoaded",{interaction:e}),t())})},callbackChain:function(t,e,i){var n=this;i||(i=0);try{t[i](function(o){return o?e(o):i+1>=t.length?e(null):n.callbackChain(t,e,i+1)})}catch(t){return e(t)}},createContentElement:function(t){return this._temporyLocation=document.createElement("div"),this._temporyLocation.style.display="none",document.body.appendChild(this._temporyLocation),this._contentElement=document.createElement("div"),this._contentElement=this.jQuery("<div></div>").html(this.getContent())[0],this._temporyLocation.appendChild(this._contentElement),t()},removeTempLocation:function(t){return document.body.removeChild(this._temporyLocation),t()},loadComplexObjects:function(t){this.jQuery(this._contentElement).find("div[data-bc-external]").html("");for(var e=this.jQuery(this._contentElement).find("div[data-bc-pluginid]"),i=0;i<e.length;i++){var n=e.eq(i),o=n.attr("data-bc-pluginid"),r=n.attr("data-bc-config");if(r)try{for(var a=r.match(/: *"(\\"|[^"])*\n(\\"|[^"])*"/g)||[],s=r,c=0;c<a.length;c++)s=s.replace(a[c],a[c].replace(/\n/g,"\\n"));r=this.blueConicClient.json.parse(s)}catch(t){console.error("Error parsing the config of the complex object:",t),r=null}this.blueConicClient.event.publish("bcComplexObject",{plugin:o,config:r,node:n[0],interactionId:this.context.getInteractionId()}),this.isInEditMode||(n.removeAttr("data-bc-pluginid"),n.removeAttr("data-bc-config"))}if(0===e.length)return t();var l=0,h=setInterval(function(){if(0===e.length)return clearInterval(h),clearTimeout(l),t();for(var i=e.length-1;i>=0;i--)e.eq(i).html()&&e.splice(i,1)},10);l=setTimeout(function(){return clearInterval(h),t({message:"Couldn't load the complex objects (timeout of 5000ms passed)."})},5e3)},loadCss:function(t){var e=document.createElement("link");e.setAttribute("type","text/css"),e.setAttribute("rel","stylesheet"),e.onload=function(){t()};var i=this.baseURL;e.onerror=function(e){return t({message:"Error occured loading the main css file ("+i+"frontend/src/css/notificationBar.css)",eventData:e})},this.jQuery("head").append(e),e.setAttribute("href",this.baseURL+"frontend/src/css/notificationBar.css")},loadCustomCss:function(t){var e=this,i=this.getParameter("styling_css"),n=this.getParameter("styling_css_inline");if(i){var o=document.createElement("link");o.setAttribute("type","text/css"),o.setAttribute("rel","stylesheet"),o.onload=function(){t()},o.onerror=function(n){return e.isInEditMode?(console.error("[BC] Loading the custom css failed for the following url: "+i),t()):t({message:"Loading the custom css failed for the following url: "+i,eventData:n})},this.customCssElements.push(this.jQuery(o)),this.jQuery("head").append(this.jQuery(o)),o.setAttribute("href",i)}if(n){n=n.replace(/&#xd;/gi,"");var r=this.jQuery("<style>"+n+"</style>");this.customCssElements.push(r),this.jQuery("head").append(r)}if("false"===this.getParameter("show_close")){var a=this.jQuery("<style>.bcpNotificationBarClose { display: none; }</style>");this.customCssElements.push(a),this.jQuery("head").append(a)}else if("true"===this.getParameter("custom_close")){var s=this.getParameter("close_icon"),c=this.getParameter("close_icon_hover"),l="";s&&(l+=".bcpNotificationBarCloseIcon {border-radius: 0;background-image: url("+s+");background-position: 0;background-size: contain;}.bcpNotificationBarCloseIcon:hover {background-position: 0;}"),c&&(l+=".bcpNotificationBarCloseIcon:hover {background-image: url("+c+");}");var h=this.jQuery("<style>"+l+"</style>");this.customCssElements.push(h),this.jQuery("head").append(h)}if(!i)return t()},resetCustomCss:function(){for(var t=0;t<this.customCssElements.length;t++){this.customCssElements[t].remove()}this.customCssElements=[]},setShowEventTrigger:function(){for(var t=this,e=0;e<this._appearOnTriggers.length;e++)switch(this._appearOnTriggers[e]){case n.PAGE_LOAD:this.triggerNotificationBar();break;case n.SCROLL_EVENT:this.jQuery(window).off("scroll.bcpNotificationBarTrigger").one("scroll.bcpNotificationBarTrigger",function(){t.triggerNotificationBar()});break;case n.SCROLL_DEPTH:this.jQuery(window).off("scroll.bcpNotificationBarTrigger").on("scroll.bcpNotificationBarTrigger",function(){t.jQuery(window).scrollTop()/(t.jQuery(document).height()-t.jQuery(window).height())*100>=parseInt(t.getParameter("scroll_depth"))&&(t.jQuery(window).off("scroll.bcpNotificationBarTrigger"),t.triggerNotificationBar())});break;case n.ELEMENT_CLICKED:this.jQuery(this.getParameter("click_selector")).off("click.bcpNotificationBarTrigger").on("click.bcpNotificationBarTrigger",function(){!1===t.notificationBar.isVisible&&t.triggerNotificationBar()});break;case n.CONTENT_VISIBLE:this._addTriggerOnContentHandler(t.getParameter("content_condition"))}},_addTriggerOnContentHandler:function(t){var e=this,i=null,n=null,o=function(){e.jQuery(t).length>0&&e.jQuery(t).html().length>0&&(e.triggerNotificationBar(),i&&i.disconnect(),n&&clearInterval(n))};window.MutationObserver?(i=new MutationObserver(o)).observe(document.body,{childList:!0,subtree:!0}):n=setInterval(o,1e3),o()},triggerNotificationBar:function(){var t=parseInt(this.getParameter("delay")),e=this;function i(){e.callbackChain([function(t){e._handleJavascript(function(i){return i&&!e.isInEditMode?t(i):(e._addInlineJavascript(),t())})},e.notificationBar.show.bind(e.notificationBar),function(t){return!1===e._openedOnce&&(e._addFrontEndBindings(),e._addClickEventLogger(),e.blueConicClient.createEvent("VIEW",e.context.getInteractionId()),e._openedOnce=!0),!0===e.isInEditMode&&setTimeout(function(){e.notificationBar.scrollIntoView()},1e3),t()}],function(t){t&&console.error(t)})}t&&!isNaN(t)&&!0!==this.isInEditMode||(t=0),0===t?i():setTimeout(i,1e3*t)},_addFrontEndBindings:function(){var t=this.jQuery(".bcpNotificationBarDontShowAgainLink"),e=this.jQuery(".bcpNotificationBarCloseButton"),i=this;(t.on("click",function(t){t.preventDefault(),i.blueConicClient.doNotShowAgain(i.context.getInteractionId()),i.notificationBar.close()}),e.on("click",function(){i.notificationBar.close()}),"true"===i.getParameter("hide_after_close"))&&this.jQuery(".bcpNotificationBarClose").on("click",function(){i.blueConicClient.doNotShowAgain(i.context.getInteractionId()),i.notificationBar.close()})},_addClickEventLogger:function(){var t=this.getParameter("click_event_selector");if(t){var e=this;this.jQuery(t).off("click.bcpNotificationBar").one("click.bcpNotificationBar",function(t){t&&t.target&&t.target.pathname&&t.target.hostname&&0===t.target.pathname.indexOf("/s/")&&-1!==t.target.hostname.indexOf("blueconic")||e.blueConicClient.createEvent("CLICK",e.context.getInteractionId())})}},_addInlineJavascript:function(){var t=this.getParameter("javascript");if(t&&!this.isInEditMode){t=t.replace(/(^|\W)blueConicVariantId(\W|$)/g,'$1"'+this.context.getInteractionId()+'"$2');var e=this.jQuery("<script>"+t+"<\/script>");try{e.appendTo(this.jQuery("body"))}catch(t){console.error(t)}}},_handleJavascript:function(t){var e=this.getParameters("javascript_urls")||[],i=this;if(0===e.length)return t();{var n=null,o=0;function r(){if(++o===e.length)return i.isInEditMode?t():t(n)}function a(t){(n=n||{message:"[BC] Loading for the following javascript urls failed, notificationBar will not be shown.",urls:[]}).urls.push(t),r()}for(var s=0;s<e.length;s++){var c=e[s],l=document.createElement("script");l.setAttribute("src",c),l.onload=r,l.onerror=a.bind(null,c),document.head.appendChild(l)}}},onSave:function(){return this.notificationBar.getContentHTML()},onMessageReceived:function(t){this.blueConicClient.event.publish("notificationBar.messageReceived",t)},getContent:function(){var t=this.getParameter("content");if(!t){var e="nl"===this.context.getLocale()?"nl":"default";t=window._bcp.notificationBar.Constants.HTML[e].content}return t},createNotificationBar:function(){var t=window._bcp.notificationBar.NotificationBar;this.notificationBar=new t(this.blueConicClient,this.context,this.jQuery,this._contentElement,{closePosition:this._closePosition,closePadding:this._closePadding,flowType:this._type,position:this._position,animationType:this._enterAnimation,height:this.notificationBarHeight})},resetNotificationBar:function(){this.notificationBar.domModifier.reset(!1),this.jQuery(this.notificationBar._containerElement).remove(),this.resetCustomCss();var t=this;this.loadCustomCss(function(){t.createNotificationBar(),t.notificationBar.show(),!0===t.isInEditMode&&t.notificationBar.scrollIntoView()})},getParameter:function(t){return this.parameters[t]&&this.parameters[t][0]?this.parameters[t][0]:null},getParameters:function(t){return this.parameters[t]?this.parameters[t]:[]}})}();var a = [];var i='dialogue_notification_bar';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.23/frontend/src/scripts/enumsAndConstants.js', sharing: 'none'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.23/frontend/src/scripts/elementModifier.js', sharing: 'none'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.23/frontend/src/scripts/domModifier.js', sharing: 'none'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.23/frontend/src/scripts/notificationBar.js', sharing: 'none'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.23/'},{ id : 'html', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'html/1.0.10/'},{ id : 'image', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'image/1.0.2/'},{ id : 'number', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'number/1.0.2/'},{ id : 'string', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'string/1.0.1/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.context=b,this.parameters=this.context.getParameters();var c=new Date(2017,8,1,0,0,0,0),d=this.blueConicClient.getCurrentDate().getTime(),e=d-c.getTime();this.days=Math.floor(e/86400000);var f=this.parameters.propertyRules&&this.parameters.propertyRules[0]?this.parameters.propertyRules[0]:null;if(f){f=a.json.parse(f),this.preLoadProperties=[];for(var g,h=0,i=0;i<f.length;i++)g=f[i],g.profileproperty&&g.decay&&g.nr&&(this.preLoadProperties.push(g.profileproperty+"_index"),g.decay>h&&(h=g.decay,this.property=g.profileproperty))}else{var j=this.parameters.property?this.parameters.property[0]:this.parameters.property;j&&(this.property=this.blueConicClient.json.parse(j)[0].profileproperty,this.preLoadProperties=[this.property+"_index"])}},getPreloadProperties:function(){return this.preLoadProperties},onLoad:function(){if(0<this.preLoadProperties.length){var a=this.context.getProfile(),b=this.parameters.engagement_rules?this.parameters.engagement_rules[0]:this.parameters.engagement_rules;if(!b)return;if(b=this.blueConicClient.json.parse(b),0===b.length)return;var c=this.parameters.interests?this.parameters.interests[0]:this.parameters.interests;c=c?this.blueConicClient.json.parse(c).values:[];var d=new this.BlueConicEngagement(this.blueConicClient,a,this.context.getInteractionId(),!0,c,this.jQuery,this.days,!0);if(d.applyEngagementRules(b),d.isChanged())d.save();else{for(var e,f=!1,g=0;g<this.preLoadProperties.length;g++)e=this.preLoadProperties[g],a.getValue(e)||(a.setValue(e,"0"),f=!0);f&&this.blueConicClient.profile.updateProfile()}}}});var a = [];var i='engagement_interest_ranking';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/6.3.1/js/engagement_service/engagementService.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/6.3.1/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(e,r){this.blueConicClient=e,this.interaction=r,this.parameters=this.interaction.getParameters();var t=this.parameters.propertyRules&&this.parameters.propertyRules[0]?this.parameters.propertyRules[0]:null;if(t){t=e.json.parse(t),this.preLoadProperties=[];for(var i=0,s=0;s<t.length;s++){var p=t[s];p.profileproperty&&p.decay&&(this.preLoadProperties.push(p.profileproperty),p.decay>i&&(i=p.decay,this.property=p.profileproperty))}}else{var a=this.parameters.property?this.parameters.property[0]:this.parameters.property;a&&(this.property=this.blueConicClient.json.parse(a)[0].profileproperty,this.preLoadProperties=[this.property])}},getPreloadProperties:function(){return this.preLoadProperties},onLoad:function(){if(this.preLoadProperties.length>0){var e=this.interaction.getProfile(),r=this.parameters.engagement_rules?this.parameters.engagement_rules[0]:this.parameters.engagement_rules;if(!r)return;if(0===(r=this.blueConicClient.json.parse(r)).length)return;var t=new this.BlueConicEngagement(this.blueConicClient,e,this.property,!1,"",this.jQuery);if(t.applyEngagementRules(r),t.isChanged())t.save();else{for(var i=!1,s=0;s<this.preLoadProperties.length;s++){var p=this.preLoadProperties[s];e.getValue(p)||(e.setValue(p,"0"),i=!0)}i&&this.blueConicClient.profile.updateProfile()}}}});var a = [];var i='engagement_score';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/6.4.2/frontend/src/node_modules/@blueconic/engagement-service/engagementService.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/6.4.2/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(e,r){this.blueConicClient=e,this.context=r},getPreloadProperties:function(){return this.preloadProperties=[],this.context&&(this.preloadProperties=this.getProfilePropertiesFromParameters(this.context.getParameters())),this.preloadProperties},onLoad:function(){var e=this.context.getProfile(),r=this.context.getParameters(),t=this.jQuery,i=r.listener_rules?r.listener_rules[0]:r.listener_rules;if(i){i=this.blueConicClient.json.parse(i);var s=new this.RuleService(this.blueConicClient,e,t);s.applyRules(i),s.save()}},getProfilePropertiesFromParameters:function(e){var r=[],t=e.listener_rules?e.listener_rules[0]:e.listener_rules;if(!t)return r;t=this.blueConicClient.json.parse(t);for(var i=0;i<t.rules.length;i++){var s=t.rules[i];!s.profileproperty||"set_if_empty"!==s.addset&&"merge"!==s.addset||r.push(s.profileproperty[0].profileproperty)}return r}});var a = [];var i='enrichprofilebyvisitorbehavior';a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'enrichProfileByVisitorBehavior/5.4.0/frontend/src/node_modules/@blueconic/jquery-x-jquerymigrate/load_jQuery3_5_X_jQueryMigrate.js', sharing: 'local'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'enrichProfileByVisitorBehavior/5.4.0/frontend/src/js/ruleService.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'enrichProfileByVisitorBehavior/5.4.0/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({PF_PROPERTY_PREFIX:"enpf",init:function(a,b){this.blueConicClient=a,this.context=b?b:null,this.profile=this.context.getProfile(),this.parameters=this.context.getParameters(),this.connectionContext={LAST_PUSH_PROPERTY:this.PF_PROPERTY_PREFIX+"lt"+this.context.getInteractionId(),VARIABLE_STATE_PUSH_PROPERTY:this.PF_PROPERTY_PREFIX+"st"+this.context.getInteractionId(),push_frequency:this.parameters.push_frequency&&this.parameters.push_frequency[0]?this.parameters.push_frequency[0]:null,profile:this.profile,variables:[],SENT_TO_SYSTEM_PROPERTY:"sent_to_system",SENT_TO_CONNECTION_PROPERTY:"sent_to_connection"},this.preloadProperties=[this.connectionContext.LAST_PUSH_PROPERTY,this.connectionContext.VARIABLE_STATE_PUSH_PROPERTY,this.connectionContext.SENT_TO_SYSTEM_PROPERTY,this.connectionContext.SENT_TO_CONNECTION_PROPERTY],this._getVariablesFromParameters()},getPreloadProperties:function(){return this.preloadProperties},onLoad:function(){if(this.bcConnectionUtil.doPush(this.connectionContext))this._doPush();else if("plc"===this.connectionContext.push_frequency){var a=this.blueConicClient.event.onProfilePermissionChange;this.blueConicClient.event.subscribe(a,this,function(){this._doPush()})}},_doPush:function(){var a=this.context.getParameters(),b=a.objectname?a.objectname[0]:a.objectname;if(b&&0<this.connectionContext.variables.length){window[b]||(window[b]={});for(var c,d=!1,e=0;e<this.connectionContext.variables.length;e++)if(c=this.connectionContext.variables[e],c.key){var f=this.bcConnectionUtil.getVariableValue(c,this.connectionContext,!0);f&&(d=!0,window[b][c.key]=f)}d&&this.bcConnectionUtil.setSyncProperties(this.context,this.profile,[this.connectionContext.SENT_TO_SYSTEM_PROPERTY,this.connectionContext.SENT_TO_CONNECTION_PROPERTY])}},_getVariablesFromParameters:function(){var a=this.parameters.variables&&this.parameters.variables[0]?this.blueConicClient.json.parse(this.parameters.variables[0]):null;if(a&&0<a.length){this.connectionContext.variables=a;for(var b,c=0;c<a.length;c++)b=a[c],b.key&&"property"===b.type&&b.property&&this.preloadProperties.push(b.property)}}});var a = [];var i='ensightenconnection';a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.0.17/js/connection_lib/connection_lib.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.0.17/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.context=b,this.rotationStateProperty=this.context.getInteractionId()+"_rotation",this.profile=this.blueConicClient.profile.getProfile(),this.parameters=this.context.getParameters(),this.rules=[];try{this.rules=this.blueConicClient.json.parse(this.parameters.rules[0])}catch(a){}this.rotationEvents=this.parameters.rotation&&this.parameters.rotation[0]?this.blueConicClient.json.parse(this.parameters.rotation[0]):[],this.rotationEvents.sort(function(c,a){return c.priority>a.priority}),this.rotationInterval=this.parameters.rotationInterval&&this.parameters.rotationInterval[0]?parseInt(this.parameters.rotationInterval[0]):0,this.skipFailedEvents=!!(this.parameters.skipFailed&&this.parameters.skipFailed[0])&&"true"===this.parameters.skipFailed[0],this.blueConicClient.event.subscribe(this.blueConicClient.event.onUrlChange,this,function(){this.onLoad()})},getPreloadProperties:function(){return[this.rotationStateProperty]},onLoad:function(){for(var a,b=0;b<this.rules.length;b++)a=this.rules[b],"click"===a.type?this._setClickBindings(a,!0):this._createEvent(a);var c=!!(this.parameters.useRotation&&this.parameters.useRotation[0])&&"true"===this.parameters.useRotation[0];c&&0<this.rotationEvents.length&&this._rotateEvents()},_createEvent:function(a){var b=a.area.selectedoption,c=!1;if("selector"===b&&a.area.selector?a.words&&this._contentMatchesWords(this._getContentForSelector(a),a.containsmatches,a.words)?c=!0:a.anyWord&&this._getContentForSelector(a)&&(c=!0):"variable"===b&&a.area.variable?a.words&&this._contentMatchesWords(this._getVariableValue(a.area.variable),a.containsmatches,a.words)?c=!0:a.anyWord&&this._getVariableValue(a.area.variable)&&(c=!0):"customjs"===b&&a.area.customjs&&(a.words&&this._contentMatchesWords(this._getCustomJsValue(a.area.customjs),a.containsmatches,a.words)?c=!0:a.anyWord&&this._getCustomJsValue(a.area.customjs)&&(c=!0)),c){var d=0;a.delay&&!isNaN(parseInt(a.delay))&&(d=parseInt(a.delay));var e=this.jQuery;setTimeout(e.proxy(function(){this.blueConicClient.createEvent(a.event.id)},this),d)}},_rotateEvents:function(){var a=this.profile.getValue(this.rotationStateProperty),b=null;b=a?this.blueConicClient.json.parse(a):{lastEvent:{},failedEvents:[]};var c=this.parameters.sourceEvent&&this.parameters.sourceEvent[0]?this.parameters.sourceEvent[0]:"PAGEVIEW";"PAGEVIEW"===c?this._doRotation(b):this.blueConicClient.event.subscribe(c,this,function(){this._doRotation(b)})},_doRotation:function(a){var b=this._getCurrentEvent(a);b&&this.blueConicClient.createEvent(b.id,null,this,function(c){0===c.length&&this.skipFailedEvents?(a.failedEvents.push(b.id),this._doRotation(a)):(a.lastEvent.id=b.id,a.lastEvent.dt=this._getTodayInMs(),this.profile.setValue(this.rotationStateProperty,this.blueConicClient.json.stringify(a)),this.blueConicClient.profile.updateProfile())})},_getCurrentEvent:function(a){return a.lastEvent.id?this.skipFailedEvents&&a.failedEvents&&a.failedEvents.length===this.rotationEvents.length?(this.profile.setValue(this.rotationStateProperty,this.blueConicClient.json.stringify(a)),this.blueConicClient.profile.updateProfile(),null):0===this.rotationInterval||this._intervalHasPassed(a.lastEvent.dt)?this._getNextEvent(a.lastEvent,a):null:this.rotationEvents[0].event},_getNextEvent:function(a,b){for(var c=0;c<this.rotationEvents.length;c++)if(this.rotationEvents[c].event.id===a.id){var d=c+1<=this.rotationEvents.length-1?c+1:0;return this.skipFailedEvents&&-1!==b.failedEvents.indexOf(this.rotationEvents[d].event.id)?this._getNextEvent(this.rotationEvents[d].event,b):this.rotationEvents[d].event}},_intervalHasPassed:function(a){var b=24*(60*(60*(1e3*this.rotationInterval)));return!!(a+b<=this._getTodayInMs())},_getTodayInMs:function(){var a=this.blueConicClient.getCurrentDate();return new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime()},_setClickBindings:function(a,b){if(a.clickarea.selector){var c=this.jQuery,d=null;try{d=c(a.clickarea.selector)}catch(a){return void this.blueConicClient.util.log("Invalid click selector: "+a)}0===d.length?this.blueConicClient.position.subscribe(a.clickarea.selector,this,function(){this._setClickBindings(a,!1)}):d.off("click."+a.id).on("click."+a.id,{clickRule:a},this.jQuery.proxy(function(a){this.lastEvent=a;try{this._createEvent(a.data.clickRule)}catch(a){}},this)),b&&c(document).on("click",a.clickarea.selector,{clickRule:a},c.proxy(function(a){if(!this.lastEvent||this.lastEvent.originalEvent!==a.originalEvent)try{this._createEvent(a.data.clickRule)}catch(a){}},this))}},_contentMatchesWords:function(a,b,c){if(!a)return!1;for(var d=0;d<c.length;d++)if("contains"===b){if(-1!==a.indexOf(c[d].toLowerCase()))return!0;}else if(a===c[d].toLowerCase())return!0;return!1},_getContentForSelector:function(rule){var selector=rule.area.selector,contentArea=null;if(-1!==selector.indexOf("jQuery("))contentArea=function(selector,jQuery){return eval("var jQuery = arguments[1]"),eval(selector)}(selector,this.jQuery);else try{contentArea=this.jQuery(selector)}catch(a){this.blueConicClient.util.log("Invalid content selector: "+a)}if(contentArea&&contentArea instanceof this.jQuery&&0<contentArea.length){var contentArr=[];return this.jQuery.each(contentArea,this.jQuery.proxy(function(a,b){var c=this.jQuery(b);c.attr("content")?contentArr.push(this._normalizeText(c.attr("content"))):c.attr("src")?contentArr.push(this._normalizeText(c.attr("src"))):contentArr.push(this._normalizeText(c.text()))},this)),contentArr.join().toLowerCase()}"content"===rule.type&&this.blueConicClient.position.subscribe(selector,this,function(){this._createEvent(rule)})},_getVariableValue:function(a){try{for(var b=a.replace("[",".").replace("]","").replace("\"\"",""),c=b.split("."),d=window[c.shift()];0<c.length;)d=d[c.shift()];return d instanceof Array?d.join().toLowerCase():"object"==typeof d||"function"==typeof d?this._stringify(d):d?(""+d).toLowerCase():null}catch(a){return null}},_getCustomJsValue:function(customjs){try{var value=function(customjs,jQuery,$){return eval("var jQuery = arguments[1]"),eval("var $ = arguments[2]"),eval(customjs)}(customjs,this.jQuery,this.jQuery);return value&&value instanceof Object&&(value=this._stringify(value)),value?(""+value).toLowerCase():null}catch(a){return null}},_stringify:function(a){try{return this.blueConicClient.json.stringify(a)}catch(a){var b=[];return JSON.stringify(obj,function(a,c){if("object"==typeof c&&null!==c){if(-1!==b.indexOf(c))return;b.push(c)}return c})}},_normalizeText:function(a){return a?this.jQuery.trim(a).replace(/\r\n+|\r+|\n+/gi,"").replace(/\s+/gi," "):a}});var a = [];var i='eventtrigger';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/eventtrigger/ts_daf024fa533d2e356e5dceee07cb54fe/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.context=b,this.parameters=this.context.getParameters()},_ouibounce:function(){var a=this,b="sensitivity",c="delay";this.ouibounce({aggressive:!0,timer:0,sensitivity:this.parameters[b]?parseInt(this.parameters[b][0]):20,delay:this.parameters[c]?parseInt(this.parameters[c][0]):0,callback:function(){window.blueConicClient&&window.blueConicClient.exitIntentThrown||a.blueConicClient.createEvent("exitintent"),window.blueConicClient&&(window.blueConicClient.exitIntentThrown=!0)}})},onLoad:function(){this.blueConicClient.event.subscribe(this.blueConicClient.event.onUrlChange,this,function(){window.blueConicClient&&window.blueConicClient.exitIntentThrown&&(window.blueConicClient.exitIntentThrown=!1,this._ouibounce())}),this._ouibounce()}});var a = [];var i='exitintent';a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.0.5/js/ouibounce.js', sharing: 'none'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.0.5/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(t,e){if(this.blueConicClient=t,this.context=e||null,this.parameters=this.context.getParameters(),this._initPublishedEvents(),this.parameters){"true"!==this.parameters.hasOverlay[0]||this._isViewEventPublished()||(this._setViewEventPublished(!0),this.blueConicClient.createEvent("VIEW",this.context.getInteractionId()));var i=this.parameters.positions;if(i)for(var n=0;n<i.length;n++){var s=i[n];this.blueConicClient.position.subscribe(s,this,this._handlePosition)}}},_initPublishedEvents:function(){window._bcp=window._bcp||{},window._bcp.publishedEvents=window._bcp.publishedEvents||{},window._bcp.publishedEvents.viewEvent=window._bcp.publishedEvents.viewEvent||{},window._bcp.publishedEvents.clickEvent=window._bcp.publishedEvents.clickEvent||{}},_handleClick:function(){this._isClickEventPublished()||(this._setClickEventPublished(!0),this.blueConicClient.createEvent("CLICK",this.context.getInteractionId()))},_handlePosition:function(t){this._isViewEventPublished()||this.blueConicClient.isInEditMode()||(this._setViewEventPublished(!0),this.blueConicClient.createEvent("VIEW",this.context.getInteractionId()));var e=this;try{var i="bcCtrl"+this.context.getInteractionId();if(this.jQuery(t+" a").off("click."+i).on("click."+i,(function(){e._handleClick()})),this.jQuery(document).off("click."+i).on("click."+i,t+" a",(function(){e._handleClick()})),this.jQuery(document).off("submit."+i).on("submit."+i,t+" form",(function(){e._handleClick()})),this.jQuery(t).find("iframe").length>0){window.focus();var n=!1,s=this.jQuery(this.jQuery(t).find("iframe"));s.off("mouseenter."+i).on("mouseenter."+i,(function(){n=!0})),s.off("mouseleave."+i).on("mouseleave."+i,(function(){n=!1})),document.querySelectorAll(window).removeEventListener("blur."+i).addEventListener("blur."+i,function(){n&&this._handleClick()}.bind(this))}}catch(o){}},onLoad:function(){if(this.parameters){var t=this.parameters.positions;if(t)for(var e=0;e<t.length;e++){var i=t[e];this.jQuery(i).length>0&&this._handlePosition(i)}}},_isViewEventPublished:function(){return Boolean(window._bcp.publishedEvents.viewEvent[this.context.getInteractionId()])},_setViewEventPublished:function(t){window._bcp.publishedEvents.viewEvent[this.context.getInteractionId()]=t},_isClickEventPublished:function(){return Boolean(window._bcp.publishedEvents.clickEvent[this.context.getInteractionId()])},_setClickEventPublished:function(t){window._bcp.publishedEvents.clickEvent[this.context.getInteractionId()]=t}});var a = [];var i='globallistener_controlgroup';a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.1.0/frontend/src/node_modules/@blueconic/jquery-x-jquerymigrate/load_jQuery3_5_X_jQueryMigrate.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.1.0/'}]);})();(function(){ var InteractionTypeImpl = InteractionType.extend({

  /**
     * Init.
     */
  init: function(blueConicClient, context) {
    this.blueConicClient = blueConicClient;
    this.context = context;
    this.profile = blueConicClient.profile.getProfile();
    this.isPremiumSite = true;
  },
  
  /**
     * Main function of the interaction.
     *
     */
  //marketValue = //market domain for api
  //entitlementValue = //entitlment property
  //propertyValue = //login profile property
  //cookieName = //cookie value
  //eventName =//name for the event to throw
  //get logged in status from TREG
  _bcLogginStatus: function(propertyParameter, marketValue, entitlementValue, cookieName, starbucksFlag) {
    console.error("start checking login status");
    var loggedInStatus = this.jQuery.Deferred();
    this._setStatusBasedOnTreg(propertyParameter, loggedInStatus, marketValue, entitlementValue, cookieName, starbucksFlag);
    return loggedInStatus.promise()
  },
  //get entitlement status based off cookie, CASPER API, or TREG object. Also checks for Stabucks flag and sets entitlement if true.
  _bcEntitlementStatus: function(marketParameter, pubcode, entitlementProperty, cookieName, starbucksFlag) {
    console.error("start checking entitlement status");
    console.error("cookie name:"+cookieName);
    console.error(starbucksFlag)
    var entitlementStatus = this.jQuery.Deferred();
    this._entitlementCheck(marketParameter, pubcode, entitlementProperty, cookieName, starbucksFlag, entitlementStatus);
    console.error("entitlement promise");
    return entitlementStatus.promise();
  },

  //check the refresh event has happened
  _bcRealmRefresh: function() {
    var treg = window.treg;
    console.error("refresh promise started");
    var realmRefreshEvent = this.jQuery.Deferred();
    treg.realm.events.registerReplayLast("realm.Oidc.refreshLogicComplete", function() {
      realmRefreshEvent.resolve();
      if (this.realmRefreshHappened) {
        console.error("realm refresh complete, promise fulfilled");
      }
    });
    return realmRefreshEvent.promise();
  },

  _setStatusBasedOnTreg: function(propertyName, loggedInStatus, marketValue, entitlementValue, cookieName, starbucksFlag) {
    var treg = window.treg;
    var me = this;
    window.treg = window.treg || {};
    window.treg.cmd = window.treg.cmd || [];

    //window._bcEvents = window._bcEvents || {};
    //window._bcDeferred = {};

    console.log("setting treg status...");
    treg.cmd.push(function() {
      //this._setStatusBasedOnTreg()
      treg.realm.events.registerReplayLast("treg.onSessionFound", function() {
        console.log("treg session found... ");
        me._setTregEmailAdress();
        me._setPropertyValueAndDoCallback(propertyName, true, me, loggedInStatus);
        me._callBcRefresh();
        //me._bcEntitlementStatus(marketValue, entitlementValue, cookieName, starbucksFlag)
      });

      treg.realm.events.registerReplayLast("treg.onSessionEnd", function() {
        console.log("treg session not ending... ");
        me._setPropertyValueAndDoCallback(propertyName, false, me, loggedInStatus);
        if(localStorage.getItem('bc_refresh')){
          localStorage.removeItem('bc_refresh', "true");
          // window.location.reload();
        }
        //me._bcEntitlementStatus(marketValue, entitlementValue, cookieName, starbucksFlag)
      });

      treg.realm.events.registerReplayLast("treg.onSessionNotFound", function() {
        console.log("treg session not found... ");
        me._setPropertyValueAndDoCallback(propertyName, false, me, loggedInStatus);
        if(localStorage.getItem('bc_refresh')){
          localStorage.removeItem('bc_refresh', "true");
          // window.location.reload();
        }
        //me._bcEntitlementStatus(marketValue, entitlementValue, cookieName, starbucksFlag)
      });
    });
  },

  _setPropertyValueAndDoCallback: function(propertyName, value, me, loggedInStatus) {
    me.profile.setValue(propertyName, value);
    //me.blueConicClient.profile.updateProfile();
    loggedInStatus.resolve()
  },

  _callBcRefresh: function(){
    var me = this;
    //extend for all premium sites
    this.isPremiumSite = (document.URL.indexOf('houstonchronicle') > -1)
    if(!localStorage.getItem('bc_refresh') && me.isPremiumSite){
        localStorage.setItem('bc_refresh', "true");
        window.location.reload();
    }
  },

  //sets a cookie in if the user is in a Starbucks which is used to set entitlement status as true.
  _setStarbucksCookie: function(name, exhours, domain, cookieName) {
    var exdate = new Date();
    var value = `st=${exdate}`;
    console.log("inside set starbucks cookie");
    if (window.location.hostname.indexOf("qa") !== -1) {
      exdate.setMinutes(exdate.getMinutes() + 5);
    } else {
      exdate.setHours(exdate.getHours() + exhours);
    }
    value = value + `,et=${exdate}` + ",expires=" + exdate.toUTCString() + ",domain=." + domain + ",pal=hc_hc,path=/";
    var starbucksCookieValue = encodeURIComponent(value) + ",expires=" + exdate.toUTCString() + ",domain=." + domain + ",vendor=starbucks;path=/";
    var cookieValue = encodeURIComponent(value) ;
    var vendorCookieName = cookieName;
    document.cookie = name + "=" + cookieValue;
    document.cookie = vendorCookieName + "=" + starbucksCookieValue;
    console.log("Starbucks Cookie set...");
    console.log(cookieValue);
  },

  //checks entitlement status based on the market value provided in the listener.
  _entitlementCheck: function(marketValue, pubcode, entitlementProfileProperty, cookieName, starbucksFlag, entitlementStatus) {
    var me = this;
    console.error('entitlement check')
    if (window.treg.identity.isEntitled){
      me.profile.setValue(entitlementProfileProperty, "true");
      //me.blueConicClient.profile.updateProfile();
      entitlementStatus.resolve();
      me._checkInGraceAndCCDStatus(window.treg.identity.id, marketValue, pubcode, "in_grace_status_" + marketValue, "in_grace_status_set_date_" + marketValue)
      return;
    } 
    //if the starbucks flag is checked check if the user is on a starbucks page and set a cookie/entitlement status
    else if (starbucksFlag === "true") {
      console.error('sb true')
      if (this.blueConicClient.util.cookie.getCookie(cookieName)) {
        me.profile.setValue(entitlementProfileProperty, "true");
        //me.blueConicClient.profile.updateProfile();
        entitlementStatus.resolve();
        return;
      } else {
        console.error('sb true, but no cookie')
        me._starbucksCheck(window.location.hostname, cookieName, entitlementProfileProperty, marketValue, entitlementStatus);
      }
    //if no cookie is set call the api and get status of the user then set the cookie and update profile.
    } else if(!window.treg.identity.isEntitled){
        me.profile.setValue(entitlementProfileProperty, window.treg.identity.isEntitled);
        entitlementStatus.resolve();
        return
      }
    //start metering after entitlements are set. 
    me.blueConicClient.createEvent("cm_start_metering");
    /* else {
      console.error('no sb flag no cookie')
      me._bcEntitlementStatusApi(marketValue, entitlementProfileProperty, me, entitlementStatus, cookieName)
    }
    */
  },

  //if the starbucks flag is checked and no cookie is present will check the page if it is a starbucks page  
  _starbucksCheck: function(domain, cookieName, entitlementProfileProperty, marketValue, entitlementStatus) {
    var me = this;
    var sbRegexp = new RegExp(domain + "\/starbucks", "i");
    if (sbRegexp.test(window.location.hostname)) {
      me.profile.setValue(entitlementProfileProperty, "true");
      //me.blueConicClient.profile.updateProfile();
      me._setStarbucksCookie(cookieName, 4, window.location.hostname, cookieName);
      //fufill promise
      entitlementStatus.resolve();
      return;
    }
    else if(window.treg.identity.isEntitled){
        me.profile.setValue(entitlementProfileProperty, window.treg.identity.isEntitled);
        entitlementStatus.resolve();
        return
      } else {
        me.profile.setValue(entitlementProfileProperty, window.treg.identity.isEntitled);
        entitlementStatus.resolve();
        return
      }
      //console.error('not on sb page')
      //me._bcEntitlementStatusApi(marketValue, entitlementProfileProperty, me, entitlementStatus, cookieName)
  },
  _checkInGraceAndCCDStatus: function(realmId, market, publicationCode, gracestatusPP, gracestatusDatePP) {
    var graceLocalItem = JSON.parse(localStorage.getItem("in_grace_check_item"));
    var graceDateChecked;
    var graceDateDifference;
    var graceDateInterval;
    //check for the item in local storage and the email
    if(graceLocalItem){
        if((graceLocalItem.email === window.treg.identity.email)) {
            graceDateChecked = JSON.parse(localStorage.getItem("in_grace_check_item")).date
            if(document.URL.indexOf('cmf.qa') > -1){
                //compare the date for 2 minutes
                graceDateDifference = (Date.now() - graceDateChecked)/ (1000 * 60);
                graceDateInterval = 2; // 2 minutes
            }
            else {
                //compare the date for 24 hours
                graceDateDifference = (Date.now() - graceDateChecked)/ (1000 * 60 * 60);  
                graceDateInterval = 24; // 24 hours
            }
        }
    }
    if((graceDateDifference > graceDateInterval) || !graceLocalItem) {
        var me = this;
        var hasSubInGrace = false;
        var hasActiveRenewal = false; 
        var url = "https://casper-services-prod-dot-eco-cyclist-168716.appspot.com/getSubscriptionDetailsByUserid"
        if(document.URL.indexOf("cmf.qa") > -1){
            url = "https://casper-services-qa2-dot-eco-cyclist-168716.appspot.com/getSubscriptionDetailsByUserid"
        }
        window.$.ajax({
            type: "POST",
            url: url,
            dataType: "json",
            contentType: "application/json",
            crossDomain: true,
            data: JSON.stringify({
                realmID: realmId,
                market: market,
                origin: "",
                publicationCode: publicationCode
            }),
            success: function(res) {
                //check the status
                if(res.data.subscriptions){
                    // res.data.subscriptions.forEach(function(subscription){
                    //     if(subscription.subscription.active === "In Grace Period"){
                    //         hasSubInGrace = true;
                    //         console.log("BC PRELISTENER - In Grace True");
                    //     }
                    //     if(subscription.subscription.automaticRenewal === "yes"){
                    //         hasActiveRenewal = true;
                    //     }
                    //     else{
                    //         console.log("BC PRELISTENER - In Grace False");

                    //     }
                    // });

                    for(var index in res.data.subscriptions) {
                        if(res.data.subscriptions[index].subscription.active === "In Grace Period" && res.data.subscriptions[index].subscription.automaticRenewal === "no"){
                            //set the rate code
                            me.blueConicClient.profile.getProfile().setValue("rate_code", res.data.subscriptions[index].subscription.rateCode);
                            hasSubInGrace = true;
                            break;
                        }
                        else if(res.data.subscriptions[index].subscription.ccDecline  && res.data.subscriptions[index].subscription.automaticRenewal === "yes") {
                            //set to ccd1
                            if(res.data.subscriptions[index].subscription.pubCode === 'HC_TSN'){
                                me.blueConicClient.profile.getProfile().setValue("ccdecline_status", "HC_TSN" + "_CCD1");
                            }
                            else me.blueConicClient.profile.getProfile().setValue("ccdecline_status", market + "_CCD1");
                        }
                    }
                    //for HC reset the grace pp 
                    if(document.URL.indexOf('houstonchronicle.com') > -1){
                        //check the pub codes
                        if(res.data.subscriptions[index].subscription.pubCode === 'HC_TSN') {
                            //set the fields to TSN 
                            gracestatusPP = 'in_grace_status_tsn';
                            gracestatusDatePP = 'in_grace_status_set_date_tsn';
                        }
                        //
                    }
                    //set the status
                    if(hasSubInGrace){
                        me.blueConicClient.profile.getProfile().setValue(gracestatusPP, "true");
                    }
                    else {
                        me.blueConicClient.profile.getProfile().setValue(gracestatusPP, "false");
                    }
                    //set the date
                    var graceSetDate = Date.now();
                    var newGraceItem;
                    if(document.URL.indexOf('ctinsider.com') > -1){
                        newGraceItem = {
                            email: window.treg.identity.email,
                            date:  graceSetDate,
                            pubCode: res.data.subscriptions[index].subscription.pubCode
                        };
                    }
                    else {
                        newGraceItem = {
                            email: window.treg.identity.email,
                            date:  graceSetDate
                        };
                    }
                    localStorage.setItem("in_grace_check_item", JSON.stringify(newGraceItem));
                    me.blueConicClient.profile.getProfile().setValue(gracestatusDatePP, graceSetDate);
                    me.blueConicClient.profile.updateProfile(this, function() {
                        // publish event to that will trigger content metering
                        // this will allow the content meter to wait for the entitlement status to get set
                        // before evaluating the profile
                        // this.blueConicClient.createEvent("cm_start_metering");
                    });
                }
            },
            error: function() {
                console.log('BC PRELISTENER ERROR - In Grace status not able to be set');
            }
        });
    }
  },
  _setTregEmailAdress: function() {
    if(window.treg.identity.email) {
        var emailDomain = window.treg.identity.email.split("@")[1];
        this.profile.setValue("email_domain", emailDomain);
        this.profile.setValue("realm_id", window.treg.identity.id);
        this.profile.setValue("edb_email", window.treg.identity.email);
        this.profile.setValue("email", window.treg.identity.email);
        //this.blueConicClient.profile.updateProfile();
    }
    //check realm id from localstorage, if none found set it 
    if(window.localStorage.getItem('bc.realm.id')){
      //check if they are the same
      if(!(window.localStorage.getItem('bc.realm.id') === window.treg.identity.id)){
          //set it to the new one
          window.localStorage.setItem('bc.realm.id', window.treg.identity.id);
      }
    }
    else{
      window.localStorage.setItem('bc.realm.id', window.treg.identity.id);
    }
    console.log('updated email from TREG');
  },

  onLoad: function() {
    window.treg = window.treg || {};
    window.treg.cmd = window.treg.cmd || [];
    window.bc_deferreds = window.bc_deferreds || {};
    

    //get properties set in UI
    var parameters = this.context.getParameters();
    var propertyId = parameters.loginprofileproperties  ? parameters.loginprofileproperties[0] : null;
    var entitlementValue = parameters.entitlementproperties  ? parameters.entitlementproperties[0] : null;
    var marketValue = parameters.marketvalue  ? parameters.marketvalue[0] : null;
    var pubcode = parameters.pubcode  ? parameters.pubcode[0] : null;
    var cookieName = parameters.cookievalue  ? parameters.cookievalue[0] : null;
    var eventName = parameters.eventname  ? parameters.eventname[0] : null;
    var starbucksFlag = parameters.starbucksflag  ? parameters.starbucksflag[0] : null;

    //wait for each function to resolve and return before updating the profile and firing the event.
    this.jQuery.when(
      this._bcLogginStatus(propertyId, marketValue, entitlementValue, cookieName, starbucksFlag), 
      this._bcEntitlementStatus(marketValue, pubcode, entitlementValue, cookieName, starbucksFlag), 
      this._bcRealmRefresh()
    ).done(function() {
      console.error("done");
      blueConicClient.profile.updateProfile(this, function() {
        blueConicClient.createEvent(eventName);
      });
    })
      .fail(function() {
        //handle errors
      });
  }
});
var a = [];var i='hearst_login_entitlement_listener';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/hearst_login_entitlement_listener/ts_5e41e232a45e9693cbd9c4ab3b05bd9b/'}]);})();(function(){ // ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level SIMPLE_OPTIMIZATIONS
// ==/ClosureCompiler==

var InteractionTypeImpl = InteractionType.extend({

    init: function(blueConicClient, context) {
        this.blueConicClient = blueConicClient;
        this.context = context ? context : null;
        this.profile = blueConicClient.profile.getProfile();
        this.pollCounter = 0;
        //Refresh properties
        this.realmRefreshHappened = false;
        this.entitlementSet = false;
        this.isPremiumSite = true;

    },

    // Zendesk #5397: Using onPrepare() instead of onLoad() to make sure that the
    // segments based on the profile properties set here can be used on the first
    // page view. This assumes that the script "treg.hearstnp.com/treg.js" will be
    // run BEFORE the BlueConic script.
    onPrepare: function() {
        // Built to specs of Zendesk #5149
        var regexp;
        var hostname = window.location.hostname;
        var referrer = document.referrer;

        window.detection = window.detection || {};
        window.detection.hc_ent_detection_complete = false;
        //Reset entitlement sources
        this.blueConicClient.profile.getProfile().setValue("entitlement_sources", undefined);
        //metered no paywall
        this.blueConicClient.profile.getProfile().setValue("paywall_policy", window.HDN.dataLayer.paywall.policy);
        //set the most recent realm id
        if(window.localStorage.getItem('bc.realm.id')){
            this.blueConicClient.profile.getProfile().setValue("realm_identifier_most_recent_", window.localStorage.getItem('bc.realm.id'));
        }
        //STARBUCKS ENTITLEMENTS
        if(window.detection && window.detection.hc_ent_detection_complete) {
            this.blueConicClient.createEvent("hc_ent_detection_complete");
            console.log('onLoad: AFTER - Calling the event - HC ENT DETECTION COMPLETE');
          }
            console.log("refferer: " + referrer);
            
            if (referrer && (referrer.toLowerCase().indexOf("https://www.houstonchronicle.com/starbucks") > -1 || referrer.toLowerCase().indexOf("https://www.sfchronicle.com/starbucks") > -1 || referrer.toLocaleLowerCase().indexOf("https://wifi.starbucks.com/") > -1)) {
                
            this.blueConicClient.profile.getProfile().setValue("starbucks_referrer", "true");
                console.log('From starbucks netowork');
                //set the entitlements
                var me = this;
                if (!window.HDN) {
                    window.HDN = {};
                }
                window.HDN.dataLayer = window.HDN.dataLayer || {};
                window.HDN.dataLayer.paywall = window.HDN.dataLayer.paywall || {};
                window.HDN.dataLayer.paywall.accessRule = "starbucksFreeOffer";
                var sfcRegexp = new RegExp("\\.sfchronicle\\.com$", "i");
                var houRegexp = new RegExp("\\.houstonchronicle\\.com$", "i");
                if(sfcRegexp.test(hostname)) {
                    me._setStarbucksCookie("hrstctok", "", 4, "sfchronicle.com");
                    me.blueConicClient.profile.getProfile().setValue("sfc_entitlement_status", "true");
                    me.blueConicClient.profile.getProfile().setValue("sfc_starbucks_entitlement_status", "true");
                    console.log("SFC Starbucks entitlements set!");
                    me.blueConicClient.profile.getProfile().addValue("entitlement_sources", "starbucks");
                } else if (houRegexp.test(hostname)) {
                    me._setStarbucksCookie("hrstctok", "", 4, "houstonchronicle.com");
                    me.blueConicClient.profile.getProfile().setValue("hou_entitlement_status", "true");
                    me.blueConicClient.profile.getProfile().setValue("hou_tsn_entitlement_status", "true");
                    me.blueConicClient.profile.getProfile().setValue("hou_starbucks_entitlement_status", "true");
                    me.blueConicClient.profile.getProfile().addValue("entitlement_sources", "starbucks");
                    console.log("HOU Starbucks entitlements set!");                
                }
                me.blueConicClient.profile.updateProfile();
                if(document.URL.toLowerCase().indexOf("https://www.houstonchronicle.com/starbucks") > -1 || document.URL.toLowerCase().indexOf("https://www.sfchronicle.com/starbucks") > -1) {
                    //redirect to the home 
                    console.log('starbucks redirect');
                    window.location.href = window.location.hostname;
                }
             } else {
                 this.blueConicClient.profile.getProfile().setValue("starbucks_referrer", "false");
                 //let the vendor  cookie time out
            }
        //END STARBUCKS ENTITLEMENTS
        // Domain houstonchronicle.com
        regexp = new RegExp("cmf\\.qa\\d\\.houstonchronicle\\.com$", "i");
        if (regexp.test(hostname) && document.URL.indexOf('cmf.qa1') < -1) {
            // ZD #8486
            // console.log("before calling set cookies: EVENT");
            // this.contentServiceURL = "https://casper-services-dev2-dot-eco-cyclist-168716.ue.r.appspot.com/userManager/getEntitlementStatusForBC"; //new
            // this.marketValue="HC";
            // this._setStatusBasedOnTreg("hou_logged_in_status", "houstonchronicle.com", this._processHOULoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("HC","hou_logged_in_status");
            //let the plugin handle it 
        } else {
            regexp = new RegExp("\\.houstonchronicle\\.com$", "i");
            if (regexp.test(hostname) && document.URL.indexOf('subscription.') < 0 && document.URL.indexOf('cmf.qa1') < 0) {
                    // console.log("before calling set cookies Prod: EVENT");
                    // this.contentServiceURL = "https://casper-services-prod-dot-eco-cyclist-168716.appspot.com/getEdbpToken";
                    // this.marketValue="HOU";
                    // this._setStatusBasedOnTreg("hou_logged_in_status", "houstonchronicle.com", this._processHOULoggedInStatus);
                this._setStatusAndEntitlementBasedOnTreg("HC","hou_logged_in_status");
            }
        }
        // Domain chron.com
        regexp = new RegExp("\\.chron\\.com$", "i");

        if (regexp.test(hostname)) {
            this.isPremiumSite = false;
            // this._setStatusBasedOnTreg("hou_logged_in_status", "chron.com");
            this._setStatusAndEntitlementBasedOnTreg("HC","hou_logged_in_status");
        }
            
        regexp = new RegExp("\\.sfchronicle\\.com$", "i");
        if (regexp.test(hostname) && document.URL.indexOf('subscription.') < 0) {
                this._setStatusAndEntitlementBasedOnTreg("SFC","sfc_logged_in_status");
        }

        regexp = new RegExp("\\.sfgate\\.com$", "i");
        if (regexp.test(hostname)) {
            this.isPremiumSite = false;
            //this._setStatusBasedOnTreg("sfc_logged_in_status", "sfgate.com", this._processSFLoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("SFC","sfc_logged_in_status");
        }

        //ctinsider
        regexp = new RegExp("\\.ctinsider\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "ctinsider.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }

        //ct freesites
        regexp = new RegExp("\\.ctpost\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "ctpost.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }
        
        regexp = new RegExp("\\.stamfordadvocate\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "stamfordadvocate.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }
        
        regexp = new RegExp("\\.greenwichtime\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "greenwichtime.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }
        
        regexp = new RegExp("\\.nhregister\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "nhregister.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }
        
        regexp = new RegExp("\\.thehour\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "thehour.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }
        
        regexp = new RegExp("\\.newstimes\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "newstimes.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }
        // 1CT additional Publications
        regexp = new RegExp("\\.middletownpress\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "newstimes.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }

        regexp = new RegExp("\\.registercitizen\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "newstimes.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }

        regexp = new RegExp("\\.darientimes\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "newstimes.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }
        regexp = new RegExp("\\.milfordmirror\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "newstimes.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }
        regexp = new RegExp("\\.ncadvertiser\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "newstimes.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }
        regexp = new RegExp("\\.theridgefieldpress\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "newstimes.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }
        regexp = new RegExp("\\.trumbulltimes\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "newstimes.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }
        regexp = new RegExp("\\.sheltonherald\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "newstimes.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }
        regexp = new RegExp("\\.wiltonbulletin\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            if(document.URL.indexOf('/projects/') < 0){
                // this.isPremiumSite = false;
            }
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "newstimes.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("CTI","cti_logged_in_status");
        }




        regexp = new RegExp("\\.mrt\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "newstimes.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("MP_MRT","mrt_logged_in_status");
        }
        
        regexp = new RegExp("\\.beaumontenterprise\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "newstimes.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("BE_BMT","bmt_logged_in_status");
        }
        
        regexp = new RegExp("\\.lmtonline\\.com$", "i");//change to cmf
        if (regexp.test(hostname)) {
            // this._setStatusBasedOnTregCT("cti_logged_in_status", "newstimes.com", this._processCTILoggedInStatus);
            this._setStatusAndEntitlementBasedOnTreg("SA_LMT","lmt_logged_in_status");
        }

        // Domain timesunion.com
        regexp = new RegExp("\\.timesunion\\.com$", "i");
        if (regexp.test(hostname) && !(document.URL.indexOf("subscription.") > -1)) {
            this._setStatusAndEntitlementBasedOnTreg("TU","alby_logged_in_status");
            // // https://blueconic.zendesk.com/agent/tickets/9140
            // this.timesunionContentServiceUrl = "https://edbp.timesunion.com/contentservice.svc/gettokensbyid";
            // this._setStatusBasedOnTregTU("alby_logged_in_status", "timesunion.com", this._processTULoggedInStatus)
            // // this._setTUStatus();
            // this.edbId = this._getEdbId();
            // // set EDB e-mail address according to https://blueconic.zendesk.com/agent/tickets/7817
            // this._setEdbEmailAddress();
        } 
        
         // Domain expressnews.com
        regexp = new RegExp("\\.expressnews\\.com$", "i");
        if (regexp.test(hostname) && document.URL.indexOf('subscription.') < 0) {
            this._setStatusAndEntitlementBasedOnTreg("SAEN","saen_logged_in_status");
            // console.log("before calling set cookies: EVENT");
            // this.contentServiceURL = "https://casper-services-qa-dot-eco-cyclist-168716.appspot.com/getEdbpToken";
            // this.marketValue="SAEN";
            // this._setStatusBasedOnTreg("saen_logged_in_status", "expressnews.com", this._processSAENLoggedInStatus);
            // this.profile.setValue("saen_hnpabt2_cookie", this.blueConicClient.util.cookie.getCookie("hnpabt2"));
            //Incase that fails...
            // this._setCookiesFromCMF("https://"+hostname+"/validateAndSetHrstctok.php", this._setENEntitlementStatus);
                // https://blueconic.zendesk.com/agent/tickets/7879
                if (referrer && referrer.toLowerCase().indexOf("mysanantonio.com") > -1) {
                    this.profile.setValue("saen_meter_audience", "MySA");
                } else if (referrer && referrer.toLowerCase().indexOf("google.com") > -1) {
                    this.profile.setValue("saen_meter_audience", "google");
                } else if (referrer && referrer.toLowerCase().indexOf("facebook.com") > -1) {
                    this.profile.setValue("saen_meter_audience", "facebook");
                } else if (referrer && referrer.toLowerCase().indexOf("pinterest.com") > -1) {
                    this.profile.setValue("saen_meter_audience", "pinterest");
                } else if (referrer && referrer.toLowerCase().indexOf("t.co") > -1) {
                    this.profile.setValue("saen_meter_audience", "twitter");
                } else if (referrer && referrer.toLowerCase().indexOf("reddit.com") > -1) {
                    this.profile.setValue("saen_meter_audience", "reddit");
                }

        }

        // Domain mysanantonio.com
        regexp = new RegExp("\\.mysanantonio\\.com$", "i");

        if (regexp.test(hostname)) {
            this.isPremiumSite = false;
             this._setStatusAndEntitlementBasedOnTreg("SAEN","saen_logged_in_status");
            //this._setStatusBasedOnTreg("saen_logged_in_status", "mysanantonio.com", this._processSAENLoggedInStatus);

            // set EDB e-mail address according to https://blueconic.zendesk.com/agent/tickets/7817
            this._setEdbEmailAddress();
        }

        if (window.HDN && window.HDN.dataLayer && window.HDN.dataLayer.paywall && window.HDN.dataLayer.paywall.premiumStatus) {
            this.profile.setValue("current_article_premium_status", window.HDN.dataLayer.paywall.premiumStatus);
        } else {
            this.profile.setValue("current_article_premium_status", "");
        }
    },


    /**
     * On load function
     * Triggered when BlueConic is ready to create events for dialogues to show.
     */
    onLoad: function() {
      var referrer = document.referrer;
      var hostname = window.location.hostname;

        
        if(this.blueConicClient.profile.getProfile().getValue('hou_starbucks_entitlement_status') === "true") {
            this.blueConicClient.profile.getProfile().setValue("hou_entitlement_status", "true");
            this.blueConicClient.profile.getProfile().setValue("hou_tsn_entitlement_status", "true");
        }
        
        this.blueConicClient.profile.updateProfile(this, function() {});
    },
    /**
     * Set a profile property based on the provided cookie domain and the window.treg object
     *
     * @param propertyName {String} The name of the profile property to set
     * @param cookieDomain {String} The name of the cookie domain to verify
     * @param callbackFn {Function} Callback function to call when the status is set
     */
    _setStatusBasedOnTreg: function(propertyName, cookieDomain, callbackFn) {

        var me = this;
        window.treg = window.treg || {};
        window.treg.cmd = window.treg.cmd || [];

        console.log("setting treg status...")
        treg.cmd.push(function(){
            var treg = window.treg;
            
            treg.realm.events.register("treg.onSessionFound", function() {
                console.log('treg session found... ');
                me._setPropertyValueAndDoCallback(propertyName, true, callbackFn, cookieDomain);
            });

            treg.realm.events.registerReplayLast("realm.Oidc.refreshLogicComplete", function () {
                console.log('realm refresh start -BC');
                me.realmRefreshHappened = true;
                if(me.realmRefreshHappened && me.entitlementSet) {
                    me._triggerEntitlementEvent(cookieDomain);
                }
                console.log('realm refresh complete, event created - BC');
            });

            treg.realm.events.register("treg.onSessionNotFound", function() {
                console.log('treg session not found... ');
                me._setPropertyValueAndDoCallback(propertyName, false, callbackFn, cookieDomain);
            });

            treg.realm.events.register("treg.onSessionEnd", function() {
                console.log('treg session not ending... ');
                me._setPropertyValueAndDoCallback(propertyName, false, callbackFn, cookieDomain);
            });
        });
        
    },
    /**
     * Set a profile property based on the provided cookie domain and the window.treg object
     *
     * @param propertyName {String} The name of the profile property to set
     * @param cookieDomain {String} The name of the cookie domain to verify
     * @param callbackFn {Function} Callback function to call when the status is set
     */
    _setStatusBasedOnTregCT: function(propertyName, cookieDomain, callbackFn) {
        var me = this;

        // hasActiveSession() will return "false" if called too early, depend on events instead.
        window.treg = window.treg || {};
        window.treg.cmd = window.treg.cmd || [];

        console.log('Setting Status CT...');
        console.log(window.treg);
        treg.cmd.push(function (){
            var treg = window.treg;
            treg.realm.events.register("treg.onSessionFound", function() {
                console.log('treg session found!')
                me._setPropertyValueAndDoCallback(propertyName, true, callbackFn, cookieDomain);
            });
            
            treg.realm.events.registerReplayLast("realm.Oidc.refreshLogicComplete", function () {
                console.log('realm refresh start -BC');
                me.realmRefreshHappened = true;
                if(me.realmRefreshHappened && me.entitlementSet) {
                    me._triggerEntitlementEvent(cookieDomain);
                }
                console.log('realm refresh complete, event created - BC');
            });

            treg.realm.events.registerReplayLast("treg.onSessionNotFound", function() {
                me._setPropertyValueAndDoCallback(propertyName, false, callbackFn, cookieDomain);
                if(localStorage.getItem('bc_cti_refresh')){
                    console.log('bc_cti_refresh found, deleting and reloading...')
                    window.location.reload();
                    localStorage.removeItem('bc_cti_refresh'); 
                }
            });

            treg.realm.events.registerReplayLast("treg.onSessionEnd", function() {
                me._setPropertyValueAndDoCallback(propertyName, false, callbackFn, cookieDomain);
                console.log('CTI Logging out...');
                if(localStorage.getItem('bc_cti_refresh')){
                    window.location.reload();
                    localStorage.removeItem('bc_cti_refresh'); 
                }
            });
            console.log('treg functions pushed');
        });
    },

    /**
     * Set a profile property based on the provided cookie domain and the window.treg object
     *
     * @param propertyName {String} The name of the profile property to set
     * @param cookieDomain {String} The name of the cookie domain to verify
     * @param callbackFn {Function} Callback function to call when the status is set
     */
    _setStatusBasedOnTregTU: function(propertyName, cookieDomain, callbackFn) {
        var me = this;

        // hasActiveSession() will return "false" if called too early, depend on events instead.
        window.treg = window.treg || {};
        window.treg.cmd = window.treg.cmd || [];

        console.log('Setting Status TU...');
        console.log(window.treg);
        treg.cmd.push(function (){
            var treg = window.treg;
            treg.realm.events.register("treg.onSessionFound", function() {
                if(document.URL.indexOf('cmf.qa') >= 0 ){
                    me._setPropertyValueAndDoCallback(propertyName, true, callbackFn, cookieDomain)
                }
                else{
                    me.profile.setValue("alby_logged_in_status", "true");
                    if (me.blueConicClient.util.cookie.getCookie("hrstctok")) {
                        // if we have a hrstctok cookie, call setTUEntitlement status immediately no need to call api
                        me._setTUEntitlementStatus("true");
                        me.entitlementSet = true;
                        me.profile.setValue("alby_logged_in_status", "true");
                        me.profile.setValue('edb_email', me._getEdbEmailAddress());
                        me.profile.setValue('edb_id', me._getEdbId());
                        if(me.realmRefreshHappened && me.entitlementSet) {
                            console.log('entitlment set: ', me.entitlementSet);
                            me.blueConicClient.createEvent("tu_entitlement_status_set");       
                            console.log('Entitlement event fired...');             
                        }
                    } else {
                        //set the hrstptok cookie if the ID is valid
                        var edbid = window.treg.identity.entitlementId;
                        var edbURL;
                        if(document.URL.indexOf("cmf.qa") > 0){
                            edbURL = "https://casper-services-dev2-dot-eco-cyclist-168716.appspot.com/getEdbpToken";
                        }
                        else edbURL = "https://casper-services-prod-dot-eco-cyclist-168716.appspot.com/getEdbpToken";
                        var entitlementStatus = "false";
                        window.$.ajax({
                            type: "POST",
                            url: edbURL,
                            dataType: "json",
                            contentType: "application/json",
                            crossDomain: true,
                            data: JSON.stringify({
                                edbId: window.treg.identity.entitlementId,
                                edbpMarket: 'ALBY',
                                sourceSystem: 'SITE'
                            }),
                            success: function(res) {
                                // The parsing has changed between ticket #9140 and #10071
                                if (res && res.meta && res.meta.code === 200 && res.data && res.data.Success == "true"){
                                    try {
                                        var hrstptok = res.data.ProductToken;
                                        res = JSON.parse(res.data.ContentToken);
                                        var hrstctok = res.contentToken.cookies ? res.contentToken.cookies.hrstctok : undefined;
                                        me._setCookie("hrstctok", hrstctok, 1, "timesunion.com");
                                        me._setCookie("hrstptok", hrstptok, 1, "timesunion.com");
                                        //set edb email and id
                                        me.profile.setValue('edb_email', me._getEdbEmailAddress());
                                        me.profile.setValue('edb_id', me._getEdbId());
                                    } catch (e) {
                                        // failed parsing, skipping
                                    }
                
                                    if (me.blueConicClient.util.cookie.getCookie("hrstctok")) {
                                        // 'hrstctok' cookie is now set, (re)set entitlement status
                                        entitlementStatus = "true";
                                    }
                                    me._setTUEntitlementStatus(entitlementStatus);
                                }
                            },
                            error: function(error) {
                                me._setTUEntitlementStatus("false");
                            }
                
                        });
                        //Set the logged in status
                        me._setTUStatus();
                        //refresh the page
                        if(!localStorage.getItem('bc_tu_refresh')){
                            localStorage.setItem('bc_tu_refresh','true');
                            window.location.reload();
                        }
                    }
                    this.blueConicClient.profile.updateProfile();
                }
            });
            treg.realm.events.registerReplayLast("realm.Oidc.refreshLogicComplete", function () {
                console.log('realm refresh start -BC');
                me.realmRefreshHappened = true;

                if(me.realmRefreshHappened && me.entitlementSet) {
                    me._triggerEntitlementEvent('timesunion.com');
                }
                console.log('realm refresh complete, event created - BC');
            });

            treg.realm.events.registerReplayLast("treg.onSessionNotFound", function() {
                let hrstctok = me.blueConicClient.util.cookie.getCookie("hrstctok");
                let hrstptok = me.blueConicClient.util.cookie.getCookie("hrstptok");
                me._setCookie("hrstctok", hrstctok, -1, "timesunion.com");
                me._setCookie("hrstptok", hrstptok, -1, "timesunion.com");
                me._setTUStatus();

            });

            treg.realm.events.registerReplayLast("treg.onSessionEnd", function() {
                //Invalidate the cookies
                let hrstctok = me.blueConicClient.util.cookie.getCookie("hrstctok");
                let hrstptok = me.blueConicClient.util.cookie.getCookie("hrstptok");
                me._setCookie("hrstctok", hrstctok, -1, "timesunion.com");
                me._setCookie("hrstptok", hrstptok, -1, "timesunion.com");
                me._setTUStatus();
                if(localStorage.getItem('bc_tu_refresh')){
                    window.location.reload();
                    localStorage.removeItem('bc_tu_refresh'); 
                }
            });
        });
    },

    _setPropertyValueAndDoCallback: function(propertyName, value, callbackFn, cookieDomain) {
        this.profile.setValue(propertyName, value);
        if(this.blueConicClient.profile.getProfile().getValue('hou_starbucks_entitlement_status') === "true") {
            console.log('inside starbucks entitlement status');
            this.blueConicClient.profile.getProfile().setValue("hou_entitlement_status", "true");
            this.blueConicClient.profile.getProfile().setValue("hou_tsn_entitlement_status", "true");
        }
        console.log(this.blueConicClient.profile.getProfile().getValue("hou_entitlement_status"));
        if (callbackFn && typeof callbackFn === "function") {
            // callback will trigger the profile update
            callbackFn.call(this, cookieDomain);
        }
        // Update Profile
        this.blueConicClient.profile.updateProfile();
    },

    // See https://blueconic.zendesk.com/agent/tickets/9140
    _setTUStatus: function() {
        var hrstptokCookie = this._readCookie("hrstptok");


        var hrstctokCookie = this.blueConicClient.util.cookie.getCookie("hrstctok");

        if (hrstctokCookie) {
            // if we have a hrstctok cookie, call setTUEntitlement status immediately
            this._setTUEntitlementStatus("true");
            this.entitlementSet = true;
            this.blueConicClient.profile.getProfile().addValue("entitlement_sources", "paid");
            if(this.realmRefreshHappened && this.entitlementSet) {
                console.log('entitlment set: ', this.entitlementSet);
                this.blueConicClient.createEvent("tu_entitlement_status_set");       
                console.log('Entitlement event fired...');             
            }
        } else if (hrstptokCookie && window.$) {
            // if we don't have a hrstctok cookie, but do have hrstptokCookie and jQuery, call the contentservice
            // call the content service
            // this._checkContentServiceForCookies(hrstptokCookie);
        } else {
            // if we don't have a hrstctok and also no hrstptok, set entitlementstatus to false;
            this._setTUEntitlementStatus("false");
            this.entitlementSet = true;
            if(this.entitlementSet) {
                console.log('entitlment set: ', this.entitlementSet);
                this.blueConicClient.createEvent("tu_entitlement_status_set");       
                console.log('Entitlement event fired...');             
            }
        }
    },

    _setTUEntitlementStatus: function(status) {
        this.profile.setValue("alby_entitlement_status", status);
        this.blueConicClient.profile.updateProfile(this, function() {
            // publish event to that will trigger content metering
            // this will allow the content meter to wait for the entitlement status to get set
            // before evaluating the profile
            window.setTimeout(function() {
                this.blueConicClient.createEvent("cm_start_metering");
            }, 2000);
        });
    },

    // See https://blueconic.zendesk.com/agent/tickets/9140 and https://blueconic.zendesk.com/agent/tickets/10071
    _checkContentServiceForCookies: function(hrstptokCookie) {
        var me = this;
        var entitlementStatus = "false";
        window.$.ajax({
            url: this.timesunionContentServiceUrl, // https://edbp.timesunion.com/contentservice.svc/gettokensbyid
            type: "post",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify({
                "EdbProductToken": hrstptokCookie,
                "SourceSystem": "SITE"
            }),
            success: function(res) {
                // The parsing has changed between ticket #9140 and #10071
                if (res && res.Success && res.ContentToken) {
                    try {
                        res = JSON.parse(res.ContentToken);
                        var hrstctok = res.contentToken.cookies ? res.contentToken.cookies.hrstctok : undefined;
                        me._setCookie("hrstctok", hrstctok, 1, "timesunion.com");
                    } catch (e) {
                        // failed parsing, skipping
                    }

                    if (me.blueConicClient.util.cookie.getCookie("hrstctok")) {
                        // 'hrstctok' cookie is now set, (re)set entitlement status
                        entitlementStatus = "true";
                    }
                    me._setTUEntitlementStatus(entitlementStatus);
                }
            },
            error: function() {
                me._setTUEntitlementStatus(entitlementStatus);
            }

        });
    },

    // See https://blueconic.zendesk.com/agent/tickets/7817
    _setEdbEmailAddress: function() {
        var email = this._getEdbEmailAddress();
        if (email) {
            this.profile.setValue("edb_email", email);
        }
    },
    // See https://blueconic.zendesk.com/agent/tickets/8348
    _processTULoggedInStatus: function(cookieDomain) {
        var hrstctokCookie = this.blueConicClient.util.cookie.getCookie("hrstctok");
        var tuLoggedInStatus = this.profile.getValue("alby_logged_in_status");
        if ((tuLoggedInStatus && tuLoggedInStatus === true)) {
            this._setTregEmailAdress();
            if (window.treg && window.treg.identity && window.treg.identity.edbId && !hrstctokCookie && window.treg.identity.id && window.$) {
                // 'hrstctok' cookie not present, check identity service
                //This conditional can be taken out and soley use the _checkISCookiesForTUCookies method later.
                if(document.URL.indexOf('cmf.qa') >= 0){
                    this._checkIdentityServiceForCookiesTU();
                }
                else{

                    this._checkIdentityServiceForCookiesTU();

                }
            } else if (hrstctokCookie) {
                // 'hrstctok' cookie already present, set entitlement status
                this._setTUEntitlementStatus("true");
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    this.blueConicClient.createEvent("alby_entitlement_status_set");                   
                }
            } else {
                this._setTUEntitlementStatus("false");
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    this.blueConicClient.createEvent("alby_entitlement_status_set");                   
                }
            }
        } else {
            // not logged in, invalidate 'hrstctok' cookie
            if (hrstctokCookie) {
                // invalidate 'hrstctok' cookie
                this._setCookie("hrstctok", "", -1, cookieDomain);
                this._setCookie("hrstptok", "", -1, cookieDomain);
            }
            this.blueConicClient.profile.updateProfile();
            // reset entitlement status
            this._setTUEntitlementStatus("false");
            this.entitlementSet = true;
            if(this.realmRefreshHappened && this.entitlementSet) {
                this.blueConicClient.createEvent("alby_entitlement_status_set");                      
            }
        }
    },        
    // See https://blueconic.zendesk.com/agent/tickets/8348
    _processHOULoggedInStatus: function(cookieDomain) {
        var hrstctokCookie = this.blueConicClient.util.cookie.getCookie("hrstctok");
        var houLoggedInStatus = this.profile.getValue("hou_logged_in_status");
        var houStarbucksEntitlementStatus = this.profile.getValue("hou_starbucks_entitlement_status");
        if ((houLoggedInStatus && houLoggedInStatus === true)) {
            this._setTregEmailAdress();
            if (window.treg && window.treg.identity && window.treg.identity.edbId && !hrstctokCookie && window.treg.identity.id && window.$) {
                // 'hrstctok' cookie not present, check identity service
                //This conditional can be taken out and soley use the _checkISCookiesForHOUCookies method later.
                if(document.URL.indexOf('cmf.qa') >= 0){
                    this._checkISCookiesForHOUCookies(cookieDomain, this._setHCEntitlementStatus);
                }
                else{

                    this._checkISCookiesForHOUCookies(cookieDomain, this._setHCEntitlementStatus);

                }
            } else if (hrstctokCookie || this.blueConicClient.util.cookie.getCookie("hrstvdtok")) {
                // 'hrstctok' cookie already present, set entitlement status
                this._setHCEntitlementStatus("true");
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    this.blueConicClient.createEvent("hou_entitlement_status_set");       
                    console.log('hou entitlement event fired...');               
                }
            } else {
                this._setHCEntitlementStatus("false");
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    this.blueConicClient.createEvent("hou_entitlement_status_set");       
                    console.log('hou entitlement event fired...');               
                }
            }
        } else {
            //if they have starbucks entitlements, don't clear entitlements
            if(this._checkandUpdateStarbucksEntitlements('hou_starbucks_entitlement_status')){
                this._setHCEntitlementStatus("true");
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    this.blueConicClient.createEvent("hou_entitlement_status_set");       
                    console.log('hou entitlement event fired...');               
                }
            }
            else{
                // not logged in, invalidate 'hrstctok' cookie
                if (hrstctokCookie) {
                    // invalidate 'hrstctok' cookie
                    this._setCookie("hrstctok", "", -1, cookieDomain);
                }
                this.profile.setValue('hou_starbucks_entitlement_status', "false");
                this.blueConicClient.profile.updateProfile();
                // reset entitlement status
                this._setHCEntitlementStatus("false");
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    this.blueConicClient.createEvent("hou_entitlement_status_set");       
                    console.log('hou entitlement event fired...');               
                }
            }
        }
    },    
    
    // See https://blueconic.zendesk.com/agent/tickets/8348
    _processSAENLoggedInStatus: function(cookieDomain) {
        var hrstctokCookie = this.blueConicClient.util.cookie.getCookie("hrstctok");
        var saenLoggedInStatus = this.profile.getValue("saen_logged_in_status");
        console.log(window.treg.identity);
        if (saenLoggedInStatus && saenLoggedInStatus === true) {
            this._setTregEmailAdress();
            if (window.treg && window.treg.identity && window.treg.identity.entitlementId && !hrstctokCookie && window.treg.identity.id && window.$) {
                // 'hrstctok' cookie not present, check identity service
                this._checkISCookiesForSAEN(cookieDomain, this._setENEntitlementStatus); //ENABLE LATER
            } 
            else if (hrstctokCookie) {
                // 'hrstctok' cookie already present, set entitlement status
                this._setENEntitlementStatus("true");
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    me.blueConicClient.createEvent("sean_entitlement_status_set");       
                    console.log('sean entitlement event fired...');               
                }
            } else {
                this._setENEntitlementStatus("false");
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    me.blueConicClient.createEvent("sean_entitlement_status_set");       
                    console.log('sean entitlement event fired...');               
                }
            }
        } else {
            // not logged in, invalidate 'hrstctok' cookie
            if (hrstctokCookie) {
                // invalidate 'hrstctok' cookie
                this._setCookie("hrstctok", "", -1, cookieDomain);
            }
            // reset entitlement status
            this._setENEntitlementStatus("false");
            this.entitlementSet = true
            if(this.realmRefreshHappened && this.entitlementSet) {
                me.blueConicClient.createEvent("sean_entitlement_status_set");       
                console.log('sean entitlement event fired...');               
            }
        }
    },

    // See https://blueconic.zendesk.com/agent/tickets/8348
    _processSFLoggedInStatus: function(cookieDomain) {
        var hrstctokCookie = this.blueConicClient.util.cookie.getCookie("hrstctok");
        var sfcLoggedInStatus = this.profile.getValue("sfc_logged_in_status");
        if ((sfcLoggedInStatus && sfcLoggedInStatus === true)) {
            this._setTregEmailAdress();
            if(document.URL.indexOf('cmf.qa') > -1){
                if (window.treg && window.treg.identity && !hrstctokCookie && window.treg.identity.id && window.$) {
                    // 'hrstctok' cookie not present, check identity service
                    this._checkIdentityServiceForCookies(cookieDomain); //ENABLE LATER
                }                
            }
            else if (window.treg && window.treg.identity && window.treg.identity.edbId && !hrstctokCookie && window.treg.identity.id && window.$) {
                // 'hrstctok' cookie not present, check identity service
                this._checkIdentityServiceForCookies(cookieDomain); //ENABLE LATER
            } else if (hrstctokCookie) {
                // 'hrstctok' cookie already present, set entitlement status
                this._setSFEntitlementStatus("true");
                this.blueConicClient.profile.getProfile().addValue("entitlement_sources", "paid");
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    this.blueConicClient.createEvent("sfc_entitlement_status_set");       
                    console.log('sfc entitlement event fired...');               
                }
            } else {

                this._setSFEntitlementStatus("false");
                this.profile.setValue('sfc_starbucks_entitlement_status', "false");
                this.blueConicClient.profile.updateProfile();
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    this.blueConicClient.createEvent("sfc_entitlement_status_set");       
                    console.log('sfc entitlement event fired...');               
                }
            }
        } else {
            //check vendor token
            if(this._checkandUpdateStarbucksEntitlements('sfc_starbucks_entitlement_status')){
                //give entitlements
                this._setSFEntitlementStatus("true");
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    this.blueConicClient.createEvent("sfc_entitlement_status_set");       
                    console.log('sfc entitlement event fired...');               
                }
            }
            else {
                // not logged in, invalidate 'hrstctok' cookie
                if (hrstctokCookie) {
                    // invalidate 'hrstctok' cookie
                    this._setCookie("hrstctok", "", -1, cookieDomain);
                }
                // reset entitlement status
                this._setSFEntitlementStatus("false");
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    this.blueConicClient.createEvent("sfc_entitlement_status_set");       
                    console.log('sfc entitlement event fired...');               
                }
            }
        }
    },

    //CT Insider
    _processCTILoggedInStatus: function(cookieDomain) {
        var hrstctokCookie = this.blueConicClient.util.cookie.getCookie("hrstctok");
        var ctiLoggedInStatus = this.profile.getValue("cti_logged_in_status");

        if (ctiLoggedInStatus && ctiLoggedInStatus === true) {
            this._setTregEmailAdress();
            if (window.treg && window.treg.identity && !hrstctokCookie && window.treg.identity.id && window.$) {
                // 'hrstctok' cookie not present, check identity service with the CT market value
                this._checkIdentityServiceForCookiesCTI(cookieDomain);  //ENABLE LATER

            } else if (hrstctokCookie) {
                // 'hrstctok' cookie already present, set entitlement status
                this._setCTIEntitlementStatus("true");
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    this.blueConicClient.createEvent("cti_entitlement_status_set");       
                    console.log('Entitlement event fired after cookie was found...');               
                }
                console.log('CTI Entitlment Set...');
            } else {
                this._setCTIEntitlementStatus("false");
                this.entitlementSet = true;
                if(this.realmRefreshHappened && this.entitlementSet) {
                    this.blueConicClient.createEvent("cti_entitlement_status_set");  
                         
                    console.log('Entitlement event fired after no cookie was found...');    
                }
                console.log('CTI Entitlment Set...');
            }
        } else {
            // not logged in, invalidate 'hrstctok' cookie
            if (hrstctokCookie) {
                // invalidate 'hrstctok' cookie
                this._setCookie("hrstctok", "", -1, cookieDomain);
            }
            // reset entitlement status
            this._setCTIEntitlementStatus("false");
            this.entitlementSet = true;
            if(this.realmRefreshHappened && this.entitlementSet) {
                this.blueConicClient.createEvent("cti_entitlement_status_set");       
                console.log('Entitlement event fired...');    
            }
            console.log('CTI Entitlment Set...');
        }
    },

    _checkIdentityServiceForCookies: function(cookieDomain) {
        var me = this;
        var entitlementStatus = "false";
        var subscriberId = window.treg.identity.id;
        var url = "https://casper-services-prod-dot-eco-cyclist-168716.appspot.com/";
        if (window.location.hostname.indexOf("qa") !== -1) {
            // call the QA service instead
            url = "https://casper-services-qa-dot-eco-cyclist-168716.appspot.com/";
        }
        window.$.ajax({
            type: "POST",
            url: url + "userManager/getEntitlementStatusForBC",
            dataType: "json",
            contentType: "application/json",
            crossDomain: true,
            data: JSON.stringify({
                realmID: subscriberId,
                market: 'SF'
            }),
            success: function(res) {
                console.log('success:', res);
                if (res && res.meta && res.meta.code == "200" && res.data && res.data.status == "1" && res.data.cookies && res.data.cookies.length > 0) {
                    // set cookies from response
                    console.log('setting cookies: ', res.data.cookies);
                    res.data.cookies.forEach(function(cookie) {
                        var cookieValue = [];
                        for (var attr in cookie) {
                            if (attr !== "name") {
                                cookieValue.push(attr + "=" + (cookie[attr] || ""));
                            }
                        }
                        me._setCookie(cookie.name, cookieValue.join(","), 1, cookieDomain);
                    });
                    
                     if (me.blueConicClient.util.cookie.getCookie("hrstctok")) {
                        // 'hrstctok' cookie is now set, (re)set entitlement status
                        entitlementStatus = "true";
                    }
                    me._setSFEntitlementStatus(entitlementStatus);
                    
                    if(document.URL.indexOf("#")==-1){ //Check if the current URL contains '#'
                        var localURL = document.URL+"#"; // use "#". Add hash to URL
                        location = "#";
                        location.reload(true); //Reload the page
                     }
                }
            },
            error: function() {
                console.log('error');
                me._setSFEntitlementStatus(entitlementStatus);
            }
        });
    },
    
    //Check Cookies for HOU
    _checkISCookiesForHOUCookies: function(cookieDomain, callbackfn) {
        var me = this;
        var url = "https://casper-services-prod-dot-eco-cyclist-168716.appspot.com/";
        if (window.location.hostname.indexOf("cmf.qa") !== -1) {
            // call the QA service instead
            url = "https://casper-services-dev2-dot-eco-cyclist-168716.ue.r.appspot.com/";
        }
        window.$.ajax({
            type: "POST",
            url: url + "userManager/getEntitlementStatusForBC",
            dataType: "json",
            contentType: "application/json",
            crossDomain: true,
            data: JSON.stringify({
                realmID: window.treg.identity.id,
                market: 'HC'
            }),
            success: function(res) {
                console.log('success:', res);
                if (res && res.meta && res.meta.code === 200 && res.data && res.data.status == "1") {
                    // set cookies from response
                    var hrstctok = res.data.cookies[0].ch + ',pal=' + res.data.activePublication[0]; // cookie value
                    me._setCookie("hrstctok", hrstctok, 1, cookieDomain);
                    
                    if(document.URL.indexOf("#")==-1 && !(document.URL.search('subscription')> -1)){ //Check if the current URL contains '#' or if it's on the subscription domain
                        var localURL = document.URL+"#"; // use "#". Add hash to URL
                        location = "#";
                        location.reload(true); //Reload the page
                    }
                    callbackfn.call(me);
                }
            },
            error: function() {
                console.log('error');
                callbackfn.call(me);
            }
        });
    },
    _checkISCookiesForSAEN: function(cookieDomain, callbackfn) {
        var me = this;
        var url = "https://casper-services-prod-dot-eco-cyclist-168716.appspot.com/";
        if (window.location.hostname.indexOf("cmf.qa") !== -1) {
            // call the QA service instead
            url = "https://casper-services-qa2-dot-eco-cyclist-168716.ue.r.appspot.com/";
        }
        window.$.ajax({
            type: "POST",
            url: url + "userManager/getEntitlementStatusForBC",
            dataType: "json",
            contentType: "application/json",
            crossDomain: true,
            data: JSON.stringify({
                realmID: window.treg.identity.id,
                market: 'SA'
            }),
            success: function(res) {
                console.log('success:', res);
                if (res && res.meta && res.meta.code === 200 && res.data && res.data.status == "1") {
                    // set cookies from response
                    var hrstctok = res.data.cookies[0].ch;
                    me._setCookie("hrstctok", hrstctok, 1, cookieDomain);
                    
                    if(document.URL.indexOf("#")==-1 && !(document.URL.search('subscription')> -1)){ //Check if the current URL contains '#' or if it's on the subscription domain
                        var localURL = document.URL+"#"; // use "#". Add hash to URL
                        location = "#";
                        location.reload(true); //Reload the page
                    }
                    callbackfn.call(me);
                }
            },
            error: function() {
                console.log('error');
                callbackfn.call(me);
            }
        });
    },
    //Check Cookies for HOUSAEN
    _checkISCookiesForHOUSAEN: function(cookieDomain, callbackfn) {
        var me = this;
        var entitlementStatus = "false";
        var entitlementID = window.treg.identity.entitlementId;
        window.$.ajax({
            type: "POST",
            url: this.contentServiceURL,
            dataType: "json",
            contentType: "application/json",
            crossDomain: true,
            data: JSON.stringify({
                edbId: window.treg.identity.entitlementId,
                edbpMarket: this.marketValue,
                sourceSystem: 'SITE'
            }),
            success: function(res) {
                console.log('success:', res);
                if (res && res.meta && res.meta.code === 200 && res.data && res.data.Success == "true") {
                    // set cookies from response
                    console.log('setting cookies: ', res.data.ContentToken);
                    var contentTokenData = JSON.parse(res.data.ContentToken);
                    
                    var hrstctok = contentTokenData.contentToken.cookies ? contentTokenData.contentToken.cookies.hrstctok : undefined;
                    me._setCookie("hrstctok", hrstctok, 1, cookieDomain);
                    
                     if(document.URL.indexOf("#")==-1 || !(document.URL.search('subscription')> -1)){ //Check if the current URL contains '#' or if it's on the subscription domain
                        var localURL = document.URL+"#"; // use "#". Add hash to URL
                        location = "#";
                        location.reload(true); //Reload the page
                     }
                    callbackfn.call(me);
                }
            },
            error: function() {
                console.log('error');
                callbackfn.call(me);
            }
        });
    },

    //Check Cookies for TU
    _checkIdentityServiceForCookiesTU: function() {
        var me = this;
        var edbURL;
        if(document.URL.indexOf("cmf.qa") > 0){
            edbURL = "https://casper-services-dev2-dot-eco-cyclist-168716.appspot.com/getEdbpToken";
        }
        else edbURL = "https://casper-services-prod-dot-eco-cyclist-168716.appspot.com/getEdbpToken";
        var entitlementStatus = "false";
        window.$.ajax({
            type: "POST",
            url: edbURL,
            dataType: "json",
            contentType: "application/json",
            crossDomain: true,
            data: JSON.stringify({
                edbId: window.treg.identity.entitlementId,
                edbpMarket: 'ALBY',
                sourceSystem: 'SITE'
            }),
            success: function(res) {
                // The parsing has changed between ticket #9140 and #10071
                if (res && res.meta && res.meta.code === 200 && res.data && res.data.Success == "true"){
                    try {
                        var hrstptok = res.data.ProductToken;
                        res = JSON.parse(res.data.ContentToken);
                        var hrstctok = res.contentToken.cookies ? res.contentToken.cookies.hrstctok : undefined;
                        me._setCookie("hrstctok", hrstctok, 1, "timesunion.com");
                        me._setCookie("hrstptok", hrstptok, 1, "timesunion.com");
                    } catch (e) {
                        // failed parsing, skipping
                    }

                    if (me.blueConicClient.util.cookie.getCookie("hrstctok")) {
                        // 'hrstctok' cookie is now set, (re)set entitlement status
                        entitlementStatus = "true";
                    }
                    me._setTUEntitlementStatus(entitlementStatus);
                }
            },
            error: function(error) {
                me._setTUEntitlementStatus("false");
            }
        });
    },

    //Check Cookies for CTI
    _checkIdentityServiceForCookiesCTI: function(cookieDomain) {
        var me = this;
        var entitlementStatus = "false";
        var subscriberId = window.treg.identity.id;
        var url = "https://casper-services-prod-dot-eco-cyclist-168716.appspot.com/";
        if (window.location.hostname.indexOf("cmf.qa") !== -1) {
            // call the QA service instead
            url = "https://casper-services-qa2-dot-eco-cyclist-168716.appspot.com/";
        }
        window.$.ajax({
            type: "POST",
            url: url + "userManager/getEntitlementStatusForBC",
            dataType: "json",
            contentType: "application/json",
            crossDomain: true,
            data: JSON.stringify({
                realmID: subscriberId,
                market: 'CT'
            }),
            success: function(res) {
                console.log('success:', res);
                if (res && res.meta && res.meta.code == "200" && res.data && res.data.status == "1" && res.data.cookies && res.data.cookies.length > 0) {
                    // set cookies from response
                    console.log('setting cookies: ', res.data.cookies);
                    res.data.cookies.forEach(function(cookie) {
                        var cookieValue = [];
                        for (var attr in cookie) {
                            if (attr !== "name") {
                                cookieValue.push(attr + "=" + (cookie[attr] || ""));
                            }
                        }
                        me._setCookie(cookie.name, cookieValue.join(","), 1, cookieDomain);
                    });
                    
                    if (me.blueConicClient.util.cookie.getCookie("hrstctok")) {
                        // 'hrstctok' cookie is now set, (re)set entitlement status
                        entitlementStatus = "true";
                        me.blueConicClient.profile.getProfile().addValue("entitlement_sources", "paid");
                    }
                    me._setCTIEntitlementStatus(entitlementStatus);
                   // me.entitlementSet = true;
                    console.log('CTI Entitlment Set...');
                    console.log('cookie found for cti')
                    
                    //reload the page after entitlement is set
                    if(!localStorage.getItem('bc_cti_refresh')){
                        localStorage.setItem('bc_cti_refresh','true');
                        window.location.reload();
                        console.log('ctidomain refresh after setting cookie...');
                    }
                }
            },
            error: function() {
                console.log('error');
                me._setCTIEntitlementStatus(entitlementStatus);
                me.entitlementSet = true;
                if(me.realmRefreshHappened && me.entitlementSet) {
                    me.blueConicClient.createEvent("cti_entitlement_status_set");         
                    console.log('Entitlement event fired...');           
                }
                console.log('CTI Entitlment Set...');
            }
        });
    },

    _setSFEntitlementStatus: function(status) {
        //if true, check and set in grace entitlement status
        if(status === "true" ){
            //check the date
            var graceDateChecked = JSON.parse(localStorage.getItem('in_grace_date_set_sfc'));
            var graceDateDifference;
            var graceDateInterval;
            if(graceDateChecked){
                if(document.URL.indexOf('cmf.qa') > -1){
                    //compare the date for 2 minutes
                    // graceDateDifference = (Date.now() - graceDateChecked)/ (1000 * 60);
                    // graceDateInterval = 2; // 2 minutes
                    this._checkInGraceStatus(window.treg.identity.id, 'SF', 'SFC', 'in_grace_date_set_sfc', 'in_grace_status_sfc','in_grace_status_set_date_sfc');
                }
                else {
                    //compare the date for 24 hours
                    graceDateDifference = (Date.now() - graceDateChecked)/ (1000 * 60 * 60);  
                    graceDateInterval = 24; // 24 hours
                }
                if(graceDateDifference > graceDateInterval){
                    this._checkInGraceStatus(window.treg.identity.id, 'SF', 'SFC', 'in_grace_date_set_sfc', 'in_grace_status_sfc','in_grace_status_set_date_sfc');
                }
            }
            else{
                this._checkInGraceStatus(window.treg.identity.id, 'SF', 'SFC', 'in_grace_date_set_sfc', 'in_grace_status_sfc','in_grace_status_set_date_sfc');
            }
        }
        this.profile.setValue("sfc_entitlement_status", status);
        if(window.treg.identity.email){
            if(window.treg.identity.email.indexOf("@49ers.com") > -1 || window.treg.identity.email.indexOf("@49ers-smc.com") > -1){
                this.profile.setValue("sfc_entitlement_status", "true");
                this.profile.addValue("entitlement_sources", "49ers");
                if(!localStorage.getItem('sfc_refresh')){
                    localStorage.setItem('sfc_refresh', "true");
                    window.location.reload();
                }
            }
        }
        else {
            if(localStorage.getItem('sfc_refresh')){
                localStorage.removeItem('sfc_refresh');
            }
        }
        this.blueConicClient.profile.updateProfile(this, function() {
            // publish event to that will trigger content metering
            // this will allow the content meter to wait for the entitlement status to get set
            // before evaluating the profile
            // this.blueConicClient.createEvent("cm_start_metering");
            window.setTimeout(function() {
                this.blueConicClient.createEvent("cm_start_metering");
            }, 3000);
        });
    },

    _setCTIEntitlementStatus: function(status) {
        this.profile.setValue("cti_entitlement_status", status);
        this.blueConicClient.profile.updateProfile(this, function() {
            // publish event to that will trigger content metering
            // this will allow the content meter to wait for the entitlement status to get set
            // before evaluating the profile
            window.setTimeout(function() {
                this.blueConicClient.createEvent("cm_start_metering");
            }, 2000);
            
        });
    },

    _setCookie: function(name, value, exdays, domain) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var cookieValue = encodeURIComponent(value) + ";expires=" + exdate.toUTCString() + ";domain=." + domain + ";path=/";
        document.cookie = name + "=" + cookieValue;
    },
    _setStarbucksCookie: function(name, value, exhours, domain) {
        var exdate = new Date();
        value = 'st=' + exdate;
        console.log('inside set starbucks cookie');
        if (window.location.hostname.indexOf("qa") !== -1) {
            exdate.setMinutes(exdate.getMinutes() + 5);    
        } else {
            exdate.setHours(exdate.getHours() + exhours);
        }
        value = value + ',et=' + exdate + ",expires=" + exdate.toUTCString() + ",domain=." + domain + ",pal=hc_hc,path=/";
        var starbucksCookieValue = encodeURIComponent(value) + ",expires=" + exdate.toUTCString() + ",domain=." + domain + ",vendor=starbucks;path=/";
        var cookieValue = encodeURIComponent(value) ;
        var vendorCookieName = " hrstvdtok";
        document.cookie = name + "=" + cookieValue;
        document.cookie = vendorCookieName + "=" + starbucksCookieValue;
        console.log('Starbucks Cookie set...');
        console.log(cookieValue);
    },
    // getEdbId from cookie
    _getEdbId: function() {
        var edbId;
        
        if(window.treg && window.treg.identity && window.treg.identity.entitlementId) {
            edbid = window.treg.identity.entitlementId;    
        }
        
        return edbId;
    },

    // get EDB e-mail address from cookie
    _getEdbEmailAddress: function() {
        var edbEmailAddress;
        edbEmailAddress = window.treg.identity.email;
        return edbEmailAddress;
    },

    // https://jira.blueconic.com/jira/browse/BC-9233
    _readCookie: function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(";");
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) === " ") {
                c = c.substring(1, c.length);
            }
            if (c.indexOf(nameEQ) === 0) {
                return c.substring(nameEQ.length, c.length);
            }
        }
        return null;
    },

    _setHCCookiesFromCMF: function() {
        var me = this;
        var url = "https://www.houstonchronicle.com/validateAndSetHrstctok.php";
        var hrstctok = this.blueConicClient.util.cookie.getCookie("hrstctok");
        var hrstptok = this.blueConicClient.util.cookie.getCookie("hrstptok");
        if (window.location.hostname.indexOf("qa") !== -1) {
            url = "https://cmf.qa1.houstonchronicle.com/validateAndSetHrstctok.php";
        }
        
        if (hrstptok && !hrstctok) {
            fetch(url).then(function(response) {
                if (response.ok) {
                    me._setHCEntitlementStatus();
                } else {
                    me._setHCEntitlementStatus();
                }
            });
        } else {
            this._setHCEntitlementStatus();
        }
    },
    
    _setCookiesFromCMF: function(url, callbackfn) {
        var me = this;
        var hrstctok = this.blueConicClient.util.cookie.getCookie("hrstctok");
        var hrstptok = this.blueConicClient.util.cookie.getCookie("hrstptok");
        var page = "";
        if (window.HDN && window.HDN.dataLayer && window.HDN.dataLayer.content && window.HDN.dataLayer.content.objectType) {
            page = window.HDN.dataLayer.content.objectType;
        }
        console.log('evaluate page status and cookies before: EVENT');
        if (hrstptok && !hrstctok) {
            fetch(url).then(function(response) {
                if (response.ok) {
                    console.log('response OK : EVENT');
                    callbackfn.call(me);
                } else {
                    callbackfn.call(me);
                }
            });
        } else {
            console.log('no calling the endpoint; calling hc entitlement status: before call : EVENT');
            callbackfn.call(me);
        }
    },

    // See https://blueconic.zendesk.com/agent/tickets/8486
    _setHCEntitlementStatus: function() {
        var me = this;
        console.log('inside entitlement status: EVENT');
        var hrstctok = this.blueConicClient.util.cookie.getCookie("hrstctok");
        var palVal = null;
        if (hrstctok) {
            var pal = hrstctok.split(",").filter(function(entry) {
                return entry.indexOf("pal=") === 0;
            });
            if (pal.length > 0) {
                palVal = pal[0].split("=")[1].toLowerCase();
            }
        }
        var houEntitlement = palVal !== null && (palVal.indexOf("hc_hc") !== -1 || palVal.indexOf("HC_HC") !== -1 || palVal.indexOf("HC_KR") !== -1 || palVal.indexOf("HC_WV") !== -1
            || palVal.indexOf("hc_kr") !== -1 || palVal.indexOf("hc_wv") !== -1);
        me.profile.setValue("hou_entitlement_status", houEntitlement);
        me.profile.setValue("hou_tsn_entitlement_status", palVal !== null && (palVal.indexOf("hc_tsn") !== -1 || palVal.indexOf("hc_hc") !== -1 || palVal.indexOf("HC_HC") !== -1 ||  palVal.indexOf("HC_TSN") !== -1));
        me.blueConicClient.profile.getProfile().addValue("entitlement_sources", houEntitlement ? "paid" : "");
        console.log('BEFORE - Calling the event - CMF QA1 HC ENT DETECTION COMPLETE : EVENT');
        window.detection = window.detection || {};
        window.detection.hc_ent_detection_complete = true;
        console.log('Calling onLoad: EVENT');
        //this.onLoad();
        console.log('after Calling onLoad: EVENT');
        this.blueConicClient.profile.updateProfile(this, function(){
            let regexp = new RegExp("cmf\\.qa\\d\\.houstonchronicle\\.com$", "i");
            if(!regexp.test(me.hostname)) {
                window.setTimeout(function() {
                    this.blueConicClient.createEvent("cm_start_metering");
                }, 2000);
            }    
        });
    },
    
    _setENEntitlementStatus: function() {
        var me = this;
        var status = me.blueConicClient.util.cookie.getCookie("hrstctok") ? "true" : "false";
        me.profile.setValue("saen_entitlement_status", status);
        me.blueConicClient.profile.getProfile().addValue("entitlement_sources", status=="true" ? "paid" : "");
        // set EDB e-mail address according to https://blueconic.zendesk.com/agent/tickets/7817
        me._setEdbEmailAddress();
        window.detection = window.detection || {};
        window.detection.hc_ent_detection_complete = true;
        if(document.URL.indexOf('cmf.qa') > -1){
            //if true, check and set in grace entitlement status
            if(status === "true" ){
                //check the date
                var graceDateChecked = JSON.parse(localStorage.getItem('in_grace_date_set_saen'));
                var graceDateDifference;
                var graceDateInterval;
                if(graceDateChecked){
                    if(document.URL.indexOf('cmf.qa') > -1){
                        //compare the date for 2 minutes
                        graceDateDifference = (Date.now() - graceDateChecked)/ (1000 * 60);
                        graceDateInterval = 2; // 2 minutes
                    }
                    else {
                        //compare the date for 24 hours
                        graceDateDifference = (Date.now() - graceDateChecked)/ (1000 * 60 * 60);  
                        graceDateInterval = 24; // 24 hours
                    }
                    if(graceDateDifference > graceDateInterval){
                        this._checkInGraceStatus(window.treg.identity.id, 'SA', 'SA_SAEN', 'in_grace_date_set_saen', 'in_grace_status_saen','in_grace_status_set_date_saen');
                    }
                }
                else{
                    this._checkInGraceStatus(window.treg.identity.id, 'SA', 'SA_SAEN', 'in_grace_date_set_saen', 'in_grace_status_saen','in_grace_status_set_date_saen');
                }
            }
        }
        this.blueConicClient.profile.updateProfile(this, function() {
            // publish event to that will trigger content metering
            // this will allow the content meter to wait for the entitlement status to get set
            // before evaluating the profile
            window.setTimeout(function() {
                this.blueConicClient.createEvent("cm_start_metering");
            }, 2000);
        });
    },

    /* code supplied by hearst, see https://blueconic.zendesk.com/agent/tickets/6316 */
    // code supplied by Hearst for Interstitial
    
    _triggerEntitlementEvent: function (cookieDomain) {
        if(cookieDomain === 'houstonchronicle.com' || cookieDomain === 'chron.com') {
            this.blueConicClient.createEvent('hou_entitlement_status_set');
            console.log('Hou entitlment event fired...')
        }
        else if(cookieDomain === 'expressnews.com' || cookieDomain === 'mysanantonio.com') {
            this.blueConicClient.createEvent('sean_entitlement_status_set');
            console.log('sean entitlment event fired...')
        }
        else if(cookieDomain === 'sfchronicle.com' || cookieDomain === 'sfgate.com') {
            this.blueConicClient.createEvent('sfc_entitlement_status_set');
            console.log('sfc entitlment event fired...')
        }
        else if(cookieDomain === 'ctinsider.com') {
            this.blueConicClient.createEvent('cti_entitlement_status_set');
            console.log('cti entitlment event fired from trigger method...')
        }
    },
    _setTregEmailAdress: function() {
        if(window.treg.identity.email) {
            var emailDomain = window.treg.identity.email.split("@")[1];
            this.profile.setValue("email_domain", emailDomain);
            this.profile.setValue("realm_id", window.treg.identity.id);
            this.profile.setValue("realm_id", window.treg.identity.id);
            this.profile.setValue("edb_email", window.treg.identity.email);
            this.profile.setValue("email", window.treg.identity.email);
            this.blueConicClient.profile.updateProfile();

            //check realm id from localstorage, if none found set it 
            if(window.localStorage.getItem('bc.realm.id')){
                //check if they are the same
                if(!(window.localStorage.getItem('bc.realm.id') === window.treg.identity.id)){
                    //set it to the new one
                    window.localStorage.setItem('bc.realm.id', window.treg.identity.id);
                }
            }
            else{
                window.localStorage.setItem('bc.realm.id', window.treg.identity.id);
            }
        }
        console.log('updated email from TREG');
    },
    _setStarbucksEntitlements: function () {
        //give valid entitlments and set cookie
        let hrstctok = '';
        let cookieDomain = 'sfchronicle.com';
        this._setStarbucksCookie("hrstctok", hrstctok, 4, cookieDomain);
        this.blueConicClient.profile.getProfile().setValue("sfc_entitlement_status", "true");
        this.blueConicClient.profile.getProfile().setValue("sfc_starbucks_entitlement_status", "true");
        console.log('this.referrer: '+this.referrer);
         if (this.referrer && this.referrer.toLowerCase().indexOf("/starbucks") > -1) {
            this.profile.setValue("starbucks_referrer", "true");
         } else {
             this.profile.setValue("starbucks_referrer", "false");
         }
        this.blueConicClient.profile.updateProfile();
        console.log(this.profile.getValue('sfc_starbucks_entitlement_status'));
    },
    _checkandUpdateStarbucksEntitlements: function(marketStarbucksProperty){
        //search for vendor cookie
        var hrstvdtok = this.blueConicClient.util.cookie.getCookie("hrstvdtok");
        if(hrstvdtok) {
            //set starbucks entitlements
            console.log('Vendor token found!');
            this.blueConicClient.profile.getProfile().setValue(marketStarbucksProperty, "true");
            return true;
        }
        else{
            console.log('no vendor token or expired');
            this.blueConicClient.profile.getProfile().setValue(marketStarbucksProperty, "false");
            return false;
        }
    },

    //Check the vendor cookies and add valid entitlements to the sources
    _checkVendorCookies: function(){
        var hrstvdok = this.blueConicClient.util.cookie.getCookie("hrstvdtok");
        var vendorVal = null;
        if (hrstvdok) {
            var vendor = hrstvdok.split(",").filter(function(entry) {
                return entry.indexOf("vendor=") === 0;
            });
            if (vendor.length > 0) {
                vendorVal = vendor[0].split("=")[1].toLowerCase();
            }
            this.blueConicClient.profile.getProfile().setValue("entitlement_sources", vendorVal);
            this.blueConicClient.profile.updateProfile();
        }
    },

    _checkInGraceStatus: function(realmId, market, publicationCode, localStorageItem, gracestatusPP, gracestatusDatePP) {
        var graceLocalItem = JSON.parse(localStorage.getItem(localStorageItem));
        var graceDateChecked;
        var graceDateDifference;
        var graceDateInterval;
        //check for the item in local storage and the email
        if(graceLocalItem){
            if((graceLocalItem.email === window.treg.identity.email)) {
                graceDateChecked = JSON.parse(localStorage.getItem(localStorageItem)).date
                if(document.URL.indexOf('cmf.qa') > -1){
                    //compare the date for 2 minutes
                    graceDateDifference = (Date.now() - graceDateChecked)/ (1000 * 60);
                    graceDateInterval = 2; // 2 minutes
                }
                else {
                    //compare the date for 24 hours
                    graceDateDifference = (Date.now() - graceDateChecked)/ (1000 * 60 * 60);  
                    graceDateInterval = 24; // 24 hours
                }
            }
        }
        if((graceDateDifference > graceDateInterval) || !graceLocalItem) {
            var me = this;
            var hasSubInGrace = false;
            var hasActiveRenewal = false; 
            var url = "https://casper-services-prod-dot-eco-cyclist-168716.appspot.com/getSubscriptionDetailsByUserid"
            if(document.URL.indexOf("cmf.qa") > -1){
                url = "https://casper-services-qa2-dot-eco-cyclist-168716.appspot.com/getSubscriptionDetailsByUserid"
            }
            window.$.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                contentType: "application/json",
                crossDomain: true,
                data: JSON.stringify({
                    realmID: realmId,
                    market: market,
                    origin: "",
                    publicationCode: publicationCode
                }),
                success: function(res) {
                    //check the status
                    if(res.data.subscriptions){
                        // res.data.subscriptions.forEach(function(subscription){
                        //     if(subscription.subscription.active === "In Grace Period"){
                        //         hasSubInGrace = true;
                        //         console.log("BC PRELISTENER - In Grace True");
                        //     }
                        //     if(subscription.subscription.automaticRenewal === "yes"){
                        //         hasActiveRenewal = true;
                        //     }
                        //     else{
                        //         console.log("BC PRELISTENER - In Grace False");

                        //     }
                        // });

                        for(var index in res.data.subscriptions) {
                            if(res.data.subscriptions[index].subscription.active === "In Grace Period" && res.data.subscriptions[index].subscription.automaticRenewal === "no"){
                                //set the rate code
                                me.blueConicClient.profile.getProfile().setValue("rate_code", res.data.subscriptions[index].subscription.rateCode);
                                hasSubInGrace = true;
                                break;
                            }
                        }
                        //for HC reset the grace pp 
                        if(document.URL.indexOf('houstonchronicle.com') > -1){
                            //check the pub codes
                            if(res.data.subscriptions[index].subscription.pubCode === 'HC_TSN') {
                                //set the fields to TSN 
                                gracestatusPP = 'in_grace_status_tsn';
                                gracestatusDatePP = 'in_grace_status_set_date_tsn';
                            }
                            //
                        }
                        //set the status
                        if(hasSubInGrace){
                            me.blueConicClient.profile.getProfile().setValue(gracestatusPP, "true");
                        }
                        else {
                            me.blueConicClient.profile.getProfile().setValue(gracestatusPP, "false");
                        }
                        //set the date
                        var graceSetDate = Date.now();
                        var newGraceItem;
                        if(document.URL.indexOf('ctinsider.com') > -1){
                            newGraceItem = {
                                email: window.treg.identity.email,
                                date:  graceSetDate,
                                pubCode: res.data.subscriptions[index].subscription.pubCode
                            };
                        }
                        else {
                            newGraceItem = {
                                email: window.treg.identity.email,
                                date:  graceSetDate
                            };
                        }
                        localStorage.setItem(localStorageItem, JSON.stringify(newGraceItem));
                        me.blueConicClient.profile.getProfile().setValue(gracestatusDatePP, graceSetDate);
                        me.blueConicClient.profile.updateProfile(this, function() {
                            // publish event to that will trigger content metering
                            // this will allow the content meter to wait for the entitlement status to get set
                            // before evaluating the profile
                            // this.blueConicClient.createEvent("cm_start_metering");
                        });
                    }
                },
                error: function() {
                    console.log('BC PRELISTENER ERROR - In Grace status not able to be set');
                }
            });
        }
    },

    _checkInGraceAndCCDStatus: function(realmId, market, publicationCode, localStorageItem, gracestatusPP, gracestatusDatePP) {
        var graceLocalItem = JSON.parse(localStorage.getItem(localStorageItem));
        var graceDateChecked;
        var graceDateDifference;
        var graceDateInterval;
        //check for the item in local storage and the email
        if(graceLocalItem){
            if((graceLocalItem.email === window.treg.identity.email)) {
                graceDateChecked = JSON.parse(localStorage.getItem(localStorageItem)).date
                if(document.URL.indexOf('cmf.qa') > -1){
                    //compare the date for 2 minutes
                    graceDateDifference = (Date.now() - graceDateChecked)/ (1000 * 60);
                    graceDateInterval = 2; // 2 minutes
                }
                else {
                    //compare the date for 24 hours
                    graceDateDifference = (Date.now() - graceDateChecked)/ (1000 * 60 * 60);  
                    graceDateInterval = 24; // 24 hours
                }
            }
        }
        if((graceDateDifference > graceDateInterval) || !graceLocalItem) {
            var me = this;
            var hasSubInGrace = false;
            var hasActiveRenewal = false; 
            var ccdstatus = "none";
            var url = "https://casper-services-prod-dot-eco-cyclist-168716.appspot.com/getSubscriptionDetailsByUserid"
            if(document.URL.indexOf("cmf.qa") > -1){
                url = "https://casper-services-qa2-dot-eco-cyclist-168716.appspot.com/getSubscriptionDetailsByUserid"
            }
            window.$.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                contentType: "application/json",
                crossDomain: true,
                data: JSON.stringify({
                    realmID: realmId,
                    market: market,
                    origin: "",
                    publicationCode: publicationCode
                }),
                success: function(res) {
                    //check the status
                    if(res.data.subscriptions){
                        // res.data.subscriptions.forEach(function(subscription){
                        //     if(subscription.subscription.active === "In Grace Period"){
                        //         hasSubInGrace = true;
                        //         console.log("BC PRELISTENER - In Grace True");
                        //     }
                        //     if(subscription.subscription.automaticRenewal === "yes"){
                        //         hasActiveRenewal = true;
                        //     }
                        //     else{
                        //         console.log("BC PRELISTENER - In Grace False");

                        //     }
                        // });

                        for(var index in res.data.subscriptions) {
                            if(res.data.subscriptions[index].subscription.active !== "Perm Stopped"){
                                if(res.data.subscriptions[index].subscription.active === "In Grace Period" && res.data.subscriptions[index].subscription.automaticRenewal === "no"){
                                    //set the rate code
                                    me.blueConicClient.profile.getProfile().setValue("rate_code", res.data.subscriptions[index].subscription.rateCode);
                                    hasSubInGrace = true;
                                }
                                if(res.data.subscriptions[index].subscription.ccDecline  && res.data.subscriptions[index].subscription.automaticRenewal === "yes") {
                                    //set to ccd1
                                    ccdstatus = "ccd1";
                                    if(res.data.subscriptions[index].subscription.pubCode === 'HC_TSN'){
                                        me.blueConicClient.profile.getProfile().setValue("ccdecline_status", "HC_TSN" + "_CCD1");
                                    }
                                    else me.blueConicClient.profile.getProfile().setValue("ccdecline_status", market + "_CCD1");
                                }
                                if(res.data.subscriptions[index].subscription.ccDecline  && res.data.subscriptions[index].subscription.automaticRenewal === "no" && ccdstatus !== "ccd1") {
                                    //set to ccd2
                                    ccdstatus = "ccd2";
                                    if(res.data.subscriptions[index].subscription.pubCode === 'HC_TSN'){
                                        me.blueConicClient.profile.getProfile().setValue("ccdecline_status", "HC_TSN" + "_CCD2");
                                    }
                                    else me.blueConicClient.profile.getProfile().setValue("ccdecline_status", market + "_CCD2");
                                }
                            }
                        }
                        //for HC reset the grace pp 
                        if(document.URL.indexOf('houstonchronicle.com') > -1){
                            //check the pub codes
                            if(res.data.subscriptions[index].subscription.pubCode === 'HC_TSN') {
                                //set the fields to TSN 
                                gracestatusPP = 'in_grace_status_tsn';
                                gracestatusDatePP = 'in_grace_status_set_date_tsn';
                            }
                            //
                        }
                        //set the in grace status
                        if(hasSubInGrace){
                            me.blueConicClient.profile.getProfile().setValue(gracestatusPP, "true");
                        }
                        else {
                            me.blueConicClient.profile.getProfile().setValue(gracestatusPP, "false");
                        }

                        //if ccd is none
                        if(ccdstatus === "none"){
                            me.blueConicClient.profile.getProfile().setValue("ccdecline_status", "");
                        }

                        //set the date
                        var graceSetDate = Date.now();
                        var newGraceItem;
                        if(document.URL.indexOf('ctinsider.com') > -1){
                            newGraceItem = {
                                email: window.treg.identity.email,
                                date:  graceSetDate,
                                pubCode: res.data.subscriptions[index].subscription.pubCode
                            };
                        }
                        else {
                            newGraceItem = {
                                email: window.treg.identity.email,
                                date:  graceSetDate
                            };
                        }
                        localStorage.setItem(localStorageItem, JSON.stringify(newGraceItem));
                        me.blueConicClient.profile.getProfile().setValue(gracestatusDatePP, graceSetDate);
                        me.blueConicClient.profile.updateProfile(this, function() {
                            // publish event to that will trigger content metering
                            // this will allow the content meter to wait for the entitlement status to get set
                            // before evaluating the profile
                            // this.blueConicClient.createEvent("cm_start_metering");
                        });
                    }
                },
                error: function() {
                    console.log('BC PRELISTENER ERROR - In Grace status not able to be set');
                }
            });
        }
    },
    //Set entitlements from realm 
    _setStatusAndEntitlementBasedOnTreg: function(marketValue, loggedInProperty) {

        var me = this;
        window.treg = window.treg || {};
        window.treg.cmd = window.treg.cmd || [];

        console.log("setting treg status...")
        treg.cmd.push(function(){
            var treg = window.treg;
            
            treg.realm.events.registerReplayLast("treg.onSessionFound", function() {
                me.blueConicClient.profile.getProfile().setValue(loggedInProperty, "true");
                me._setTregEmailAdress();
                me.blueConicClient.profile.updateProfile();
                me._setEntitlmentsFromRealm(marketValue);
                //refresh if first login
                me._callBcRefresh();
            });

            treg.realm.events.registerReplayLast("realm.Oidc.refreshLogicComplete", function () {
                console.log('realm refresh start -BC');
                me.realmRefreshHappened = true;
                if(me.realmRefreshHappened && me.entitlementSet) {
                    me._triggerEntitlementEvent(cookieDomain);
                }
                console.log('realm refresh complete, event created - BC');
            });

            treg.realm.events.registerReplayLast("treg.onSessionNotFound", function() {
                console.log('treg session not found... ');
                me.blueConicClient.profile.getProfile().setValue(loggedInProperty, "false");
                me.blueConicClient.profile.updateProfile();
                me._setEntitlmentsFromRealm(marketValue);
                if(localStorage.getItem('sfc_refresh')){
                    localStorage.removeItem('sfc_refresh', "true");
                }
                else if(localStorage.getItem('bc_refresh')){
                    localStorage.removeItem('bc_refresh', "true");
                }
            });

            treg.realm.events.registerReplayLast("treg.realm.tenantDataMonitor", function() {
                console.log("BC - TREG event fired: tenantDataMonitoring");
            });

            treg.realm.events.registerReplayLast("treg.onSessionEnd", function() {
                me.blueConicClient.profile.getProfile().setValue(loggedInProperty, "false");
                me.blueConicClient.profile.updateProfile();
                me._setEntitlmentsFromRealm(marketValue);
                if(localStorage.getItem('sfc_refresh')){
                    localStorage.removeItem('sfc_refresh', "true");
                    //window.location.reload();
                }
                else if(localStorage.getItem('bc_refresh')){
                    localStorage.removeItem('bc_refresh', "true");
                    //window.location.reload();
                }
            });
        });
        
    },

    _setHCEntitlementsFromRealm: function() {
        var me = this;

        if(window.treg.identity.isEntitled){
            //check in grace status
            // me._checkInGraceStatus(window.treg.identity.id, 'HC', 'HC_HC', 'in_grace_check_item_hc', 'in_grace_status_hc','in_grace_status_set_date_hc');
            me._checkInGraceAndCCDStatus(window.treg.identity.id, "HC", "HC_HC", 'in_grace_check_item_hc', 'in_grace_status_hc', 'in_grace_status_set_date_hc');
            //check if they are only TSN entitled
            if(window.treg.identity.productAccessList.length === 1) {
                if(window.treg.identity.productAccessList[0] === "HC_TSN"){
                    //set tsn entitlement
                    me.blueConicClient.profile.getProfile().setValue("hou_entitlement_status", "false");
                    me.blueConicClient.profile.getProfile().setValue("hou_tsn_entitlement_status", "true");
                    me.blueConicClient.profile.updateProfile();
                    return true;
                }
                else{
                    //set HC entitlement
                    me.blueConicClient.profile.getProfile().setValue("hou_entitlement_status", "true");
                    me.blueConicClient.profile.updateProfile();
                    return true;
                }
            }
            else {
                //set HC entitlement
                me.blueConicClient.profile.getProfile().setValue("hou_entitlement_status", "true");
                me.blueConicClient.profile.updateProfile();
                return true;
            }
        }
        else {
            me.blueConicClient.profile.getProfile().setValue("hou_entitlement_status", "false");
            me.blueConicClient.profile.getProfile().setValue("hou_tsn_entitlement_status", "false");
            me.blueConicClient.profile.updateProfile();
            return false;
        }
    },

    _callBcRefresh: function(){
        var me = this;
        if(!localStorage.getItem('bc_refresh') && me.isPremiumSite){
            localStorage.setItem('bc_refresh', "true");
            window.location.reload();
        }
    },

    _setMarketEntitlementsFromRealm: function(entitlementProperty, marketValue, pubCode, graceMarket, graceFlag) {
        var me = this;
        if(window.treg.identity.isEntitled) {
            me.blueConicClient.profile.getProfile().setValue(entitlementProperty, "true");
            //check for in grace period
            if(graceFlag){
                // if(document.URL.indexOf("cmf.qa") > -1){
                //     me._checkInGraceAndCCDStatus(window.treg.identity.id, marketValue, pubCode, 'in_grace_check_item_' + graceMarket, 'in_grace_status_'+ graceMarket);
                // }
                me._checkInGraceAndCCDStatus(window.treg.identity.id, marketValue, pubCode, 'in_grace_check_item_' + graceMarket, 'in_grace_status_'+ graceMarket, 'in_grace_status_set_date_'  + graceMarket);
                // else me._checkInGraceStatus(window.treg.identity.id, marketValue, pubCode, 'in_grace_check_item_' + graceMarket, 'in_grace_status_'+ graceMarket,'in_grace_status_set_date_'  + graceMarket);
            }
            //
            me.blueConicClient.profile.updateProfile();
            return true;
        }
        else {
            me.blueConicClient.profile.getProfile().setValue(entitlementProperty, "false");
            me.blueConicClient.profile.updateProfile();
            return false;
        }
    },

    _whiteListEmailDomain: function(entitlementProperty, entitlementSource) {
        this.profile.setValue(entitlementProperty, "true");
        this.profile.addValue("entitlement_sources", entitlementSource);
        me.blueConicClient.profile.updateProfile();
    },

    _setEntitlmentsFromRealm: function (marketValue) {
        var me = this;

        if(marketValue === "SFC"){
            var isEntitled = false;
            //check realm for entitlements
            if(!me._setMarketEntitlementsFromRealm("sfc_entitlement_status", "SF", "SFC", "sfc", true)) {
                // check whitelisted emails
                if(window.treg.identity.email && document.URL.indexOf("cmf.qa") === -1){
                    if(window.treg.identity.email.indexOf("@49ers.com") > -1 || window.treg.identity.email.indexOf("@49ers-smc.com") > -1){
                        me._whiteListEmailDomain('sfc_entitlement_status', '49ers');
                        isEntitled = true;
                    }
                    else if(window.treg.identity.email.indexOf("@alamedahealthsystem.org") > -1) {
                        me._whiteListEmailDomain('sfc_entitlement_status', 'alameda_health');
                        isEntitled = true;
                    }
                    else if(window.treg.identity.email.indexOf("@thelibrafoundation.org") > -1 || window.treg.identity.email.indexOf("@taorising.com") > -1) {
                        me._whiteListEmailDomain('sfc_entitlement_status', 'corp_sub');
                        isEntitled = true;
                    }
                    else if(window.treg.identity.email.indexOf("@parsintl.com") > -1) {
                        me._whiteListEmailDomain('sfc_entitlement_status', 'corp_sub');
                        isEntitled = true;
                    }
                }
                // if user is not entitled check for the starbucks cookie
                if(!isEntitled){
                    if(me._checkandUpdateStarbucksEntitlements("sfc_starbucks_entitlement_status")) {
                        me.blueConicClient.profile.getProfile().setValue("sfc_entitlement_status", "true");
                    }
                }
            }
        }

        if(marketValue === "SAEN"){
            if(document.URL.indexOf("cmf.qa") > -1){
                me._setMarketEntitlementsFromRealm("saen_entitlement_status", "SA", "SA_SAEN", "saen", true);
            }
            else{
                me._setMarketEntitlementsFromRealm("saen_entitlement_status", "SA", "SA_SAEN", "saen", true);
            }
         }
        
        if(marketValue === "BE_BMT"){
            if(document.URL.indexOf("cmf.qa") > -1){
                me._setMarketEntitlementsFromRealm("be_be_entitlement_status", "SA", "BE_BE", "saen", false);
            }
            else{
                me._setMarketEntitlementsFromRealm("be_be_entitlement_status", "SA", "BE_BE", "saen", false);
            }
         }
        
        if(marketValue === "MP_MRT"){
            if(document.URL.indexOf("cmf.qa") > -1){
                me._setMarketEntitlementsFromRealm("mp_mrt_entitlement_status", "SA", "MP_MRT", "saen", false);
            }
            else{
                me._setMarketEntitlementsFromRealm("mp_mrt_entitlement_status", "SA", "MP_MRT", "saen", false);
            }
         }
        
        if(marketValue === "SA_LMT"){
            if(document.URL.indexOf("cmf.qa") > -1){
                me._setMarketEntitlementsFromRealm("sa_lmt_entitlement_status", "SA", "SA_LMT", "saen", false);
            }
            else{
                me._setMarketEntitlementsFromRealm("sa_lmt_entitlement_status", "SA", "SA_LMT", "saen", false);
            }
         }
        
        
        if(marketValue === "TU"){
            if(document.URL.indexOf("cmf.qa") > -1){
                me._setMarketEntitlementsFromRealm("alby_entitlement_status", "NY_ATU", "NY_ATU", "alby", true);
            }
           else me._setMarketEntitlementsFromRealm("alby_entitlement_status", "NY_ATU", "NY_ATU", "alby", true);
         }
         if(marketValue === "CTI"){
            if(document.URL.indexOf("cmf.qa") > -1){
                me._setMarketEntitlementsFromRealm("cti_entitlement_status", "CT", "CT_PO", "cti", true);
            }
            else me._setMarketEntitlementsFromRealm("cti_entitlement_status", "CT", "CT_PO", "cti", true);
         }
         if(marketValue === "HC") {
            if(!me._setHCEntitlementsFromRealm()) {
                if(me._checkandUpdateStarbucksEntitlements("hou_starbucks_entitlement_status")) {
                    me.blueConicClient.profile.getProfile().setValue("hou_entitlement_status", "true");
                }
            }
         }
         //update the profile
         
         this.blueConicClient.profile.updateProfile(this, function() {
            // publish event to that will trigger content metering
            // this will allow the content meter to wait for the entitlement status to get set
            // before evaluating the profile
            console.log('BC - start metering before');
            window.setTimeout(function() {
            	this.blueConicClient.createEvent('cm_start_metering');
            }, 2000);
            console.log('BC - after metering before');

        });
    },
    
});var a = [];var i='hearstprelistener';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/hearstprelistener/ts_5e7d7292f8cbff4cca00bd54f17aabee/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({_timeout:null,_timestamp:null,_interval:200,init:function(t,e){this.blueConicClient=t,this.context=e||null},onLoad:function(){var t=this;this.blueConicClient.event.subscribe(this.blueConicClient.event.onUrlChange,this,(function(e,i){this._setTimestamp(),clearTimeout(t._timeoutID),t._timeoutID=setTimeout((function(){t._checkTimeout()}),t._interval)})),this._setTimestamp();var e,i=this.context.getParameters(),n="true"===i.clicks[0],o="true"===i.inputs[0];if(e=!i.scrolling||"true"===i.scrolling[0],this._timeout=i.timeout[0],this._timeout?isNaN(parseInt(this._timeout))||(this._timeout=1e3*parseInt(this._timeout)):this._timeout=6e4,n||o||e){if(n&&document.addEventListener("click",(function(){t._setTimestamp()})),o){var c=document.querySelectorAll("input"),s=document.querySelectorAll("textarea"),u=document.querySelectorAll("select");Array.prototype.forEach.call(c,(function(e){e.addEventListener("keyup",(function(){t._setTimestamp()}))})),Array.prototype.forEach.call(c,(function(e){e.addEventListener("change",(function(){t._setTimestamp()}))})),Array.prototype.forEach.call(s,(function(e){e.addEventListener("keyup",(function(){t._setTimestamp()}))})),Array.prototype.forEach.call(u,(function(e){e.addEventListener("change",(function(){t._setTimestamp()}))}))}e&&window.addEventListener("scroll",(function(){t._setTimestamp()})),this._timeoutID=setTimeout((function(){t._checkTimeout()}),t._interval)}},_handleInactivity:function(){this.blueConicClient.createEvent("inactivity")},_checkTimeout:function(){var t=(new Date).getTime(),e=this;t-this._timestamp>this._timeout?this._handleInactivity():e._timeoutID=setTimeout((function(){e._checkTimeout()}),e._interval)},_setTimestamp:function(){this._timestamp=(new Date).getTime()}});var a = [];var i='inactivitylistener';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.0/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.interaction=b},onLoad:function(){var a=this.interaction.getProfile(),b=this.interaction.getParameters(),c=b.ip_range_rules?b.ip_range_rules[0]:b.ip_range_rules,d=b.property?b.property[0]:b.property,e=this.blueConicClient.getIPAddress();if(c&&d&&e&&(c=this.blueConicClient.json.parse(c),0!==c.length)){for(var f=!1,g=0;g<c.rules.length;g++){var h=c.rules[g],i=h.lowest,k=h.highest,l=h.addset,m=h.values;if(i&&k&&m&&0<m.length){var n,o,p;if(1<i.split(":").length&&1<k.split(":").length&&1<e.split(":").length?(n=this.ip2num(this.ip6hexToNumber(e)),o=this.ip2num(this.ip6hexToNumber(i)),p=this.ip2num(this.ip6hexToNumber(k))):(n=this.ip2num(e),o=this.ip2num(i),p=this.ip2num(k)),n<=p&&n>=o)if(f=!0,"add"===l)for(var q=0;q<m.length;q++)a.addValue(d,m[q]);else a.setValues(d,m)}}f&&this.blueConicClient.profile.updateProfile()}},ip2num:function(b){var c=b.split(".");0===c.length&&(c=b.split(":")),4===c.length&&c.unshift(0,0,0,0);var d=256*(256*(256*(256*(256*(256*(256*+c[0]+ +c[1])+ +c[2])+ +c[3])+ +c[4])+ +c[5])+ +c[6])+1*+c[7];return d},ip6hexToNumber:function(a){for(var b=a.split(":"),c=[],d=0;d<b.length;d++)if(""===b[d])for(var e=0;e<=8-b.length;e++)c.push(0);else c.push(parseInt(b[d],16));return c.join(".")}});var a = [];var i='iplistenerinteractiontype';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.0.8/'}]);})();(function(){ /* eslint-disable max-statements */
/* eslint-disable complexity */
var InteractionTypeImpl = InteractionType.extend({
  init: function (blueConicClient, context) {
    this.blueConicClient = blueConicClient;
    this.context = context;
    this.parameters = this.context.getParameters();
    this.isInEditMode = this.blueConicClient.isInEditMode();
    this.fancyBoxLib = "frontend/src/lib/fancybox/jquery.fancybox.pack.js";

    var interactionTypeId = this.context.getInteractionTypeId();
    this.baseURL = this.blueConicClient.getBaseURL(interactionTypeId);

    // Create a html fragment for the html we need to add to the dom
    var html = this.parameters.content + "";
    this.htmlFragment = this.createElement(html);

    this.profile = blueConicClient.profile.getProfile();

    // custom inline styling
    this.inlineCss = null;

    // content observing related props
    this._timestamp = null;
    this._observer = null;
    this._eventListenerFunction = null;
    this._lightboxTriggered = false;

    this.blueConicClient._renderedInteractions =
      this.blueConicClient._renderedInteractions || [];
    this.blueConicClient.event.subscribe(
      this.blueConicClient.event.onUrlChange,
      this,
      function () {
        var index = this.blueConicClient.util.array.indexOfArray(
          this.blueConicClient._renderedInteractions,
          this.context.getInteractionId()
        );
        this.blueConicClient._renderedInteractions.splice(index, 1);
      }
    );
  },

  getPreloadProperties: function () {
    var html = this.context.getParameters().content + "";

    var regex = /data-bc-preload="([^"]*)"/g;
    var propertiesFromToolbar = [];
    var match;

    while ((match = regex.exec(html)) !== null) {
      var matchedProperties = match[1].split(",");
      for (var i = 0; i < matchedProperties.length; i++) {
        propertiesFromToolbar.push(matchedProperties[i]);
      }
    }

    var propertiesFromPlaceHolders = this.htmlFragment
      ? this._getPropertiesFromPlaceholders(this.htmlFragment.innerHTML)
      : [];

    for (var j = 0; j < propertiesFromToolbar.length; j++) {
      propertiesFromPlaceHolders.push(propertiesFromToolbar[j]);
    }

    return propertiesFromPlaceHolders;
  },

  /**
   * Called by the framework.
   * Receiving messages from the Properties widget in the sidebar.
   *
   * @param message
   */
  onMessageReceived: function (message) {
    this.blueConicClient.event.publish("lightbox.messageReceived", message);
  },

  /*
   * There are 3 scenario's for displaying the Lightbox
   *  - There is a Click Trigger configured, only show the Lightbox when a specific (set of) element(s) is clicked
   *  - There is a Content Trigger configured, only show the Lightbox when a piece of content becomes available
   *  - No triggers configured, show the Lightbox right away
   */
  onLoad: function () {
    // Add BlueConic jQuery on the window scope to allow customer using bc.$ when jquery is removed from the globalscope
    window.bc = window.bc || {};
    window.bc.jQuery = this.jQuery;
    window.bc.$ = this.jQuery;

    if (window.bcFancyboxLoading) {
      // loading in progress for another instance, wait for the loaded event
      this.blueConicClient.event.subscribe(
        "bcFancyboxLoaded",
        this,
        function () {
          this.onLoad();
        }
      );
      return;
    }
    if (this.blueConicClient._lightboxinteractiontypeFancybox) {
      // if library is already loaded in another lightbox instance, use the cached one from the blueConicClient
      this.jQuery.fancybox = this.blueConicClient._lightboxinteractiontypeFancybox;

      // proceed, library is loaded from another instance
      this._onLoadWithLibrary();
    } else {
      // flag for loading in progress
      window.bcFancyboxLoading = true;
      // load the library now
      this.blueConicClient.util.loadScript(
        this.baseURL + this.fancyBoxLib,
        this,
        function () {
          // notice that the default fancybox implementation has been slightly altered
          // when the script is loaded, it injects a "_loadLightboxInteractionTypeFancyBox" method which can be called from within a plugin.
          // this is needed to inject the right jQuery instance (of the plugin, not of the website)
          // an alternative would be to just use fancybox as is, but that would possibly inject fancybox on the website's jQuery, which is far from ideal.
          this.blueConicClient._loadLightboxInteractionTypeFancyBox(
            window,
            document,
            this.jQuery
          );

          // keep track of the avaluated fancybox library, for other lightbox instances to re-use
          this.blueConicClient._lightboxinteractiontypeFancybox = this.jQuery.fancybox;

          // delete the load method, as the library is now present
          delete this.blueConicClient._loadLightboxInteractionTypeFancyBox;

          // proceed, library is properly loaded and cached
          this._onLoadWithLibrary();

          // loading done
          window.bcFancyboxLoading = false;
          this.blueConicClient.event.publish("bcFancyboxLoaded");
        }
      );
    }
  },

  /**
   * This was the previous "onLoad" method.
   */
  _onLoadWithLibrary: function () {
    if (this.isInEditMode) {
      // Always show the lightbox in Edit Mode
      this.showLightbox();
    } else {
      // check if it is in the checked list
      var selectedWhen = this.parameters.selected_when || [];

      var clickTriggerSelector = this.getParameter("click_selector");
      if (
        clickTriggerSelector &&
        this.blueConicClient.util.array.indexOfArray(
          selectedWhen,
          "click_selector"
        ) !== -1
      ) {
        // Click Trigger
        this._addClickTriggerBindings(clickTriggerSelector);
      }
      var contentCondition = this.getParameter("content_condition");

      if (
        contentCondition &&
        this.blueConicClient.util.array.indexOfArray(
          selectedWhen,
          "content_condition"
        ) !== -1
      ) {
        // Content Trigger
        this._addContentPolling(contentCondition);
      }

      var scrollDepthCondition =
        this.parameters.scroll_depth &&
        this.parameters.scroll_depth[0] &&
        !isNaN(this.parameters.scroll_depth[0])
          ? parseInt(this.parameters.scroll_depth[0])
          : 0;
      if (
        scrollDepthCondition &&
        this.blueConicClient.util.array.indexOfArray(
          selectedWhen,
          "scroll_depth"
        ) !== -1
      ) {
        // Scroll depth trigger Trigger
        this._addScrollBinding(scrollDepthCondition);
      }

      if (selectedWhen.length === 0) {
        // show the lightbox right away
        this.showLightbox();
      }

      this._addCloseEventHandler();
    }
  },

  _getScrollPercent: function () {
    var currentScrollDistance = document.documentElement.scrollTop;
    var totalPossibleScrollDistance = document.documentElement.scrollHeight;
    var windowHeight = window.innerHeight;
    return (
      (currentScrollDistance / (totalPossibleScrollDistance - windowHeight)) *
      100
    );
  },

  /*
   * Enforce the scroll condition
   */
  _checkScrollCondition: function (scrollDepthCondition) {
    var scrollPercent = this._getScrollPercent();
    if (scrollPercent >= scrollDepthCondition) {
      this.showLightbox();
    }
  },

  /*
   * Add scroll depth handler bindings for the lightbox trigger
   */
  _addScrollBinding: function (scrollDepthCondition) {
    // check if the desired scroll position is already reached
    this._checkScrollCondition(scrollDepthCondition);
    document.addEventListener(
      "scroll",
      function () {
        this._checkScrollCondition(scrollDepthCondition);
      }.bind(this)
    );
  },

  /*
   * Add click bindings for the lightbox trigger
   */
  _addClickTriggerBindings: function (clickTriggerSelector) {
    try {
      var $clickTrigger = this.jQuery(clickTriggerSelector);
      if ($clickTrigger.length > 0) {
        $clickTrigger.off("click.lightboxinteractiontype").on(
          "click.lightboxinteractiontype",
          this.jQuery.proxy(function () {
            this.showLightbox(true);
          }, this)
        );
      } else {
        this.blueConicClient.position.subscribe(
          clickTriggerSelector,
          this,
          this.jQuery.proxy(
            this._addClickTriggerBindings,
            this,
            clickTriggerSelector
          )
        );
      }
    } catch (err) {
      // empty catch
    }
  },

  /*
   * Poll for specific content before showing the lightbox
   */
  _addContentPolling: function (contentCondition) {
    // check if the content condition is already true
    this._checkContentCondition(contentCondition);

    var me = this;
    var body = document.getElementsByTagName("body")[0];
    // We need to be able to listen to DOM changes for the Content Trigger option
    var mutationObserver =
      // eslint-disable-next-line compat/compat
      window.MutationObserver ||
      window.WebKitMutationObserver ||
      window.MozMutationObserver;
    // modern browsers (GC, FF, IE11+) support the mutation observer
    if (mutationObserver) {
      // eslint-disable-next-line compat/compat
      this._observer = new MutationObserver(function () {
        me._observeContentChanges(contentCondition);
      });
      this._observer.observe(body, {
        childList: true,
        subtree: true
      });
    } else if (window.addEventListener) {
      // This is for older IE versions
      this._eventListenerFunction = function () {
        me._observeContentChanges(contentCondition);
      };
      body.addEventListener(
        "DOMNodeInserted",
        this._eventListenerFunction,
        false
      );
    } else {
      // Very old browsers, just use setInterval
      var pollInterval = setInterval(function () {
        if (!me._lightboxTriggered) {
          me._checkContentCondition(contentCondition);
        } else {
          clearInterval(pollInterval);
        }
      }, 500);
    }
  },

  /*
   * Poll for content changes, with some delay
   */
  _observeContentChanges: function (contentCondition) {
    if (this._lightboxTriggered) {
      // Lightbox already triggered, remove observers
      if (this._observer) {
        // remove content observer
        this._observer.disconnect();
      } else {
        // remove the event listener
        var body = document.getElementsByTagName("body")[0];
        body.removeEventListener(
          "DOMNodeInserted",
          this._eventListenerFunction,
          false
        );
      }
      return;
    }

    // Make sure we don't check the content too often (in case of many content changes at once)
    var me = this;
    var ts = new Date().getTime();
    this._timestamp = ts;
    setTimeout(function () {
      if (me._timestamp === ts && !me._lightboxTriggered) {
        me._checkContentCondition(contentCondition);
      }
    }, 250);
  },

  /*
   * Enforce the content condition
   */
  _checkContentCondition: function (contentCondition) {
    if (
      this.jQuery(contentCondition).length > 0 &&
      this.jQuery(contentCondition).html() &&
      this.jQuery(contentCondition).html().length > 0
    ) {
      this.showLightbox();
    }
  },

  /*
   * Close the lightbox
   */
  closeLightbox: function () {
    if (!this.isInEditMode) {
      this.jQuery.fancybox.close();
    }
  },

  /*
   * Listen to the "closeoverlay" event and close the lightbox if the event was meant for this interaction
   */
  _addCloseEventHandler: function () {
    this.blueConicClient.event.subscribe(
      "closeoverlay",
      this,
      function (event, context) {
        if (
          context instanceof Array &&
          context[0] === this.context.getInteractionId()
        ) {
          this.closeLightbox();
        }
      }
    );
  },

  /*
   * Shows the lightbox taking the delay into account
   */
  showLightbox: function (forceShow) {
    // check if the interaction needs to be triggered, see BC-9628
    if (
      this.blueConicClient.util.array.indexOfArray(
        this.blueConicClient._renderedInteractions,
        this.context.getInteractionId()
      ) !== -1
    ) {
      return;
    }

    if (this._lightboxTriggered && !this.isInEditMode && !forceShow) {
      // don't trigger the lightbox twice
      return;
    }

    this.blueConicClient._renderedInteractions.push(
      this.context.getInteractionId()
    );

    // Show the lightbox right away, possibly with delay
    var delay =
      this.parameters.delay &&
      this.parameters.delay[0] &&
      !isNaN(this.parameters.delay[0])
        ? parseInt(this.parameters.delay[0]) * 1000
        : 0;
    if (!this.isInEditMode && delay > 0) {
      window.setTimeout(this._showLightbox.bind(this), delay);
    } else {
      this._showLightbox();
    }
  },

  getSettings: function () {
    var content = null;
    var width = this.getParameter("width") || null;
    var height = this.getParameter("height") || null;
    var hideAfterClose = this.getParameter("hide_after_close") === "true";

    // Let url overrule the content
    if (this.htmlFragment) {
      content = this.htmlFragment.innerHTML;
    }

    // Check if their is an width and height available
    var autoDimensions = !(width || height);

    var showClose = this.getParameter("show_close");
    var alternativeClose = this.getParameter("alternative_close");

    var settings = {
      parent: "body",
      autoSize: autoDimensions,
      autoCenter: false,
      autoWidth: !width,
      autoHeight: !height,
      closeBtn: showClose !== "false",
      width: width || "auto",
      height: height || "auto",
      keys: {
        close: alternativeClose !== "false" && !this.isInEditMode ? [27] : null
      },
      helpers: {
        overlay: {
          locked: true,
          closeClick: alternativeClose !== "false" && !this.isInEditMode,
          // Remove the overlay as quickly as possible to prevent issues when running multiple fancyboxes
          // See BC-20822
          speedOut: 0
        }
      }
    };
    var template = this.getParameter("template");
    if (template) {
      settings.padding = 0;
    }

    if (content || this.isInEditMode) {
      settings.content = " ";
      settings.type = "inline";
    }

    var me = this;
    var $ = this.jQuery;

    var afterLoad = function (element) {
      me.emptyElementsWithAttribute(me.htmlFragment, "div", "data-bc-external");

      // add the content
      try {
        // left this here as jQuery ensures script tags are evaluated upon injection.
        // .innerHTML is unable to do this
        element.inner.html(me.htmlFragment.innerHTML);
      } catch (err) {
        console.error(
          "[BC] Error occured when injecting the HTML in the DOM",
          err
        );
      }

      if (me.isInEditMode) {
        // notify the editmode plugin the slideout is shown
        me.blueConicClient.event.publish("lightbox.interactionLoaded", {
          interaction: me
        });
      }

      me.handleComplexElements(element.inner[0]);

      // check if we have to add javascript
      var javascript = me.getParameter("javascript");
      if (javascript && !me.blueConicClient.isInEditMode()) {
        // add the current interaction Id to the javascript for conversion tracking
        javascript = javascript.replace(
          /(^|\W)blueConicVariantId(\W|$)/g,
          '$1"' + me.context.getInteractionId() + '"$2'
        );
        me._inlineJs = me.jQuery("<script>" + javascript + "</script>");
        try {
          me._inlineJs.appendTo(me.jQuery("body"));
        } catch (err) {
          console.error(err);
        }
      }
    };

    // check if we have to apply an opening effect
    var effect = this.getParameter("effect");
    var direction = this.getParameter("effect_slide_direction") || "left";

    // this is to prevent the effect is constantly executed in the inline modus
    if (this.isInEditMode) {
      effect = "noEffect";
    }

    if (effect && effect !== "noEffect") {
      if (effect === "fadeIn") {
        $.fancybox.transitions.openEffect = function () {
          var endPos = $.fancybox._getPosition(true);
          endPos.opacity = 0;

          $.fancybox.wrap.css(endPos).show().animate(
            {
              opacity: 1
            },
            {
              duration: $.fancybox.current.openSpeed,
              complete: $.fancybox._afterZoomIn
            }
          );
        };
      } else if (effect === "slideIn") {
        $.fancybox.transitions.openEffect = function () {
          var endPos = $.fancybox._getPosition(true);
          var windowHeight = window.innerHeight;
          var windowWidth = window.innerWidth;
          var rect = $.fancybox.current.wrap[0].getBoundingClientRect();
          var property =
            direction === "top" || direction === "bottom" ? "top" : "left";
          var pxs;
          if (direction === "top" || direction === "bottom") {
            pxs = windowHeight - (windowHeight - rect.height) / 2;
          } else if (direction === "left" || direction === "right") {
            pxs = windowWidth - (windowWidth - rect.width) / 2;
          }
          if (direction === "top" || direction === "left") {
            endPos[property] = parseInt(endPos[property]) - pxs + "px";
          } else {
            endPos[property] = parseInt(endPos[property]) + pxs + "px";
          }

          var config = {};
          var sign = direction === "top" || direction === "left" ? "+" : "-";
          config[property] = sign + "=" + pxs + "px";
          $.fancybox.wrap.css(endPos).show().animate(config, {
            duration: $.fancybox.current.openSpeed,
            complete: $.fancybox._afterZoomIn
          });
        };
      }

      if ($.fancybox.transitions.openEffect) {
        settings.openMethod = "openEffect";
        settings.openSpeed = 600;
      }
    }

    if (content) {
      // make sure the complex objects are loaded
      settings.afterLoad = afterLoad;
    } else if (me.isInEditMode) {
      var inEditModeAfterLoad = function () {
        me.blueConicClient.event.publish("lightbox.interactionLoaded", {
          interaction: me
        });
      };
      settings.afterLoad = inEditModeAfterLoad;
    }

    if (this.isInEditMode) {
      // Prevent the lightbox from being closed in the inline editor
      settings.afterShow = function () {
        $(".fancybox-close").off("click.fb");
      };
    } else if (hideAfterClose) {
      settings.afterShow = function () {
        Array.prototype.forEach.call(
          document.querySelectorAll(".fancybox-close"),
          function (node) {
            node.addEventListener(
              "click",
              me.blueConicClient.doNotShowAgain(me.context.getInteractionId())
            );
          }
        );
      };
    }
    settings.afterClose = function () {
      var index = me.blueConicClient.util.array.indexOfArray(
        me.blueConicClient._renderedInteractions,
        me.context.getInteractionId()
      );
      me.blueConicClient._renderedInteractions.splice(index, 1);
    };

    return settings;
  },

  updateLightbox: function () {
    this.jQuery.fancybox.update();
  },

  getCurrentFancyBox: function () {
    return this.jQuery.fancybox.current;
  },

  /*
   * Trigger the lightbox
   */
  _showLightbox: function () {
    this._lightboxTriggered = true;
    var closeIcon = this.getParameter("close_icon");
    var closeIconHover = this.getParameter("close_icon_hover");

    // Load the custom styling
    var me = this;
    var $ = this.jQuery;
    this.handleStyling(closeIcon, closeIconHover, function (err) {
      if (err) {
        // Unable to load all the CSS, so don't show the lightbox
        console.error(err);

        // Break when not in edit mode. Better to show nothing then a badly
        // styled lightbox.
        if (!me.isInEditMode) {
          var index = me.blueConicClient.util.array.indexOfArray(
            me.blueConicClient._renderedInteractions,
            me.context.getInteractionId()
          );
          me.blueConicClient._renderedInteractions.splice(index, 1);
          return;
        }
      }

      // Load the additional custom javascript
      me.handleJavascript().then(
        // Only show the lightbox on success
        function () {
          doLightBox.call(me, $);
        },
        function (err) {
          console.error(
            "[BC] Loading Javascript urls for the lightbox failed:",
            err
          );
          if (me.isInEditMode) {
            // We always want to show the lighbox in edit mode
            doLightBox.call(me, $);
          } else {
            var index = me.blueConicClient.util.array.indexOfArray(
              me.blueConicClient._renderedInteractions,
              me.context.getInteractionId()
            );
            me.blueConicClient._renderedInteractions.splice(index, 1);
          }
        }
      );
    });

    function doLightBox() {
      if (!this.isInEditMode) {
        // Register the View
        this.blueConicClient.createEvent(
          "VIEW",
          this.context.getInteractionId()
        );

        var forceClick = this.parameters.forceclick
          ? this.parameters.forceclick[0] === "true" ||
            this.parameters.forceclick[0] === true
          : false;
        if (forceClick) {
          this.blueConicClient.createEvent(
            "CLICK",
            this.context.getInteractionId()
          );
        }

        // Add click event binding, in case it is configured
        var clickEventSelector = this.getParameter("click_event_selector");
        if (clickEventSelector) {
          this.jQuery("body").one(
            "click",
            clickEventSelector,
            function (e) {
              // check if the current event was already handled through direct binding
              if (
                !this.lastClickEvent ||
                this.lastClickEvent.originalEvent !== e.originalEvent
              ) {
                this._logClickEvent(e);
              }
            }.bind(this)
          );

          try {
            this.jQuery(clickEventSelector).one(
              "click",
              function (e) {
                // keep track of the last event to check for duplicates
                this.lastClickEvent = e;
                this._logClickEvent(e);
              }.bind(this)
            );
          } catch (e) {
            // empty catch
          }
        }
      }

      /**
       * BC-4013 Dynamic z-index.
       *
       * @param   {HTMLElement} elem
       * @returns {number} Highest z-index.
       */
      function findHighestZIndex(elem) {
        var elems = document.getElementsByTagName(elem),
          zindex,
          highest = 0,
          i = 0;
        for (i = 0; i < elems.length; i++) {
          zindex = document.defaultView
            .getComputedStyle(elems[i], null)
            .getPropertyValue("z-index");
          if (zindex !== "auto") {
            if (parseInt(zindex) > highest) {
              highest = parseInt(zindex);
            }
          }
        }
        return highest;
      }

      // Remove possible lightbox and overlays that are already visible
      Array.prototype.forEach.call(
        document.querySelectorAll(".fancybox-wrap"),
        function (el) {
          el.parentNode.removeChild(el);
        }
      );
      Array.prototype.forEach.call(
        document.querySelectorAll(".fancybox-overlay"),
        function (el) {
          el.parentNode.removeChild(el);
        }
      );

      var highestZindex = findHighestZIndex("*");

      // Let url overrule the content
      if (this.htmlFragment) {
        this.emptyElementsWithAttribute(
          this.htmlFragment,
          "div",
          "data-bc-external"
        );
        if (!this.isInEditMode) {
          // Replace Profile Property place holders
          this.handlePlaceholders(this.htmlFragment);
        }
      }

      // Show the fancy box
      this.jQuery.fancybox(this.getSettings());

      var MAX_Z_INDEX = 2147483647;

      if (highestZindex > 8000 && highestZindex + 1030 < MAX_Z_INDEX) {
        Array.prototype.forEach.call(
          document.querySelectorAll(".fancybox-opened"),
          function (node) {
            node.style.zIndex = highestZindex + 1030;
          }
        );
        Array.prototype.forEach.call(
          document.querySelectorAll(".fancybox-wrap"),
          function (node) {
            node.style.zIndex = highestZindex + 920;
          }
        );
        Array.prototype.forEach.call(
          document.querySelectorAll(".fancybox-overlay"),
          function (node) {
            node.style.zIndex = highestZindex + 910;
          }
        );
      }

      if (highestZindex + 1030 >= MAX_Z_INDEX) {
        // Max z-index value. Make sure the overlay gets a lower z-index than the content wrapper
        Array.prototype.forEach.call(
          document.querySelectorAll(".fancybox-opened"),
          function (node) {
            node.style.zIndex = MAX_Z_INDEX;
          }
        );
        Array.prototype.forEach.call(
          document.querySelectorAll(".fancybox-wrap"),
          function (node) {
            node.style.zIndex = MAX_Z_INDEX - 1;
          }
        );
        Array.prototype.forEach.call(
          document.querySelectorAll(".fancybox-overlay"),
          function (node) {
            node.style.zIndex = MAX_Z_INDEX - 2;
          }
        );
      }

      if (!this.isInEditMode) {
        this._setupFrontEndBindings();
      }
    }
  },

  /*
   * Logs a click event but not when the click event is already logged (eg in the recommendation toolbar plugin)
   * and not when it's a shortened URL (check for path starts with /s/ and hostname contains blueconic): the click event is logged serverside
   */
  _logClickEvent: function (e) {
    if (
      e &&
      e.originalEvent &&
      e.originalEvent._blueConicLoggedClickEvent ===
        this.context.getInteractionId()
    ) {
      // prevent double clicks, see: BC-8901
      return;
    }
    var isShortenedUrl =
      e &&
      e.target &&
      e.target.pathname &&
      e.target.hostname &&
      e.target.pathname.indexOf("/s/") === 0 &&
      e.target.hostname.indexOf("blueconic") !== -1;
    if (isShortenedUrl) {
      // do nothing: click event is logged serverside
      return;
    }
    if (e.originalEvent) {
      e.originalEvent._blueConicLoggedClickEvent = this.context.getInteractionId();
    }
    this.blueConicClient.createEvent("CLICK", this.context.getInteractionId());
  },

  /**
   * Function to setup frontend bindings (not in edit mode). This should be called after the content
   * is set and the lightbox is shown. It is for example used to set the bindings for the "Don't show again"-link
   * and the "Close"-button (in the content of the lightbox).
   */
  _setupFrontEndBindings: function () {
    var $dontShowAgainLinks = this.jQuery(".bcLightboxDontShowAgainLink");
    var $closeButtons = this.jQuery(".bcLightboxCloseButton");

    // Handle the "Don't show again"-link(s).
    if ($dontShowAgainLinks.length > 0) {
      $dontShowAgainLinks.off("click.dontShowAgainLinks").on(
        "click.dontShowAgainLinks",
        function (evt) {
          evt.preventDefault();
          this.blueConicClient.doNotShowAgain(this.context.getInteractionId());
          // Close the fancybox.
          this.closeLightbox();
        }.bind(this)
      );
    }

    // Handle the close button(s).
    if ($closeButtons.length > 0) {
      $closeButtons.off("click.closeButtons").on(
        "click.closeButtons",
        function () {
          // Close the fancybox.
          this.closeLightbox();
        }.bind(this)
      );
    }
  },

  /*
   * Handle complex objects, which have been inserted into the content using the Toolbar
   */
  handleComplexElements: function (element) {
    // throw an event for each complex object
    var complexObjects = this.getElementsWithAttribute(
      element,
      "div",
      "data-bc-pluginid"
    );

    for (var i = 0; i < complexObjects.length; i++) {
      var complexObject = complexObjects[i];
      var pluginId = complexObject.getAttribute("data-bc-pluginid");
      var config = complexObject.getAttribute("data-bc-config");

      if (config) {
        try {
          // first escaped newlines in inlne_message to prevent parsing errors.
          var escapedConfig = config
            .replace(/\n/g, "\\\\n")
            .replace(/\r/g, "\\\\r")
            .replace(/\t/g, "\\\\t");
          config = this.blueConicClient.json.parse(escapedConfig);
        } catch (e) {
          config = null;
        }
      }

      this.blueConicClient.event.publish("bcComplexObject", {
        plugin: pluginId,
        config: config,
        node: complexObject,
        interactionId: this.context.getInteractionId()
      });

      if (!this.isInEditMode) {
        // remove the data attributes
        complexObject.removeAttribute("data-bc-pluginid");
        complexObject.removeAttribute("data-bc-config");
      }
    }
  },

  /*
   * Empties all elements with a specific attribute
   */
  emptyElementsWithAttribute: function (htmlFragment, htmlTag, attribute) {
    var allElements = this.getElementsWithAttribute(
      htmlFragment,
      htmlTag,
      attribute
    );
    for (var i = 0, l = allElements.length; i < l; i++) {
      var element = allElements[i];
      element.innerHTML = "";
    }
  },

  /*
   * The functions below are needed for the shortened urls and profile properties
   */
  getElementsWithAttribute: function (htmlFragment, htmlTag, attribute) {
    var matchingElements = [];

    var allElements = htmlFragment.getElementsByTagName(htmlTag);
    for (var i = 0, l = allElements.length; i < l; i++) {
      var element = allElements[i];
      if (element.getAttribute(attribute)) {
        matchingElements.push(element);
      }
    }
    return matchingElements;
  },

  /*
   * Create an element from the content parameter
   */
  createElement: function (html) {
    var fragment;

    if (!html) {
      return null;
    }

    try {
      fragment = document.createElement("div");
      fragment.innerHTML = html;
    } catch (error) {
      return null;
    }

    return fragment;
  },

  /*
   * Replace any profile property place holders with the actual values from the profile
   */
  handlePlaceholders: function (htmlFragment) {
    var placeholders = this._getPropertiesFromPlaceholders(
      htmlFragment.innerHTML
    );
    for (var i = 0; i < placeholders.length; i++) {
      var propertyId = placeholders[i];
      var value = this.profile.getValue(propertyId) || "";
      var re = new RegExp("\\$\\{" + propertyId + "\\}", "g");
      htmlFragment.innerHTML = htmlFragment.innerHTML.replace(
        re,
        encodeURI(value)
      );
    }
  },

  /*
   * Profile property place holders can be included in the HTML like this:
   *  ${property_id}
   */
  _getPropertiesFromPlaceholders: function (html) {
    var regex = /\$\{([a-zA-Z\-_0-9]+)\}/g;
    var result = [];
    var match;
    // eslint-disable-next-line no-cond-assign
    while ((match = regex.exec(html))) {
      result.push(match[1]);
    }

    return result;
  },

  /**
   * Function call to retrieve parameter.
   *
   * @param   {string} key - Key of the parameter to retrieve.
   * @returns {object | string} Parameter - found paramter for given key or null if not found.
   */
  getParameter: function (key) {
    return this.parameters[key] && this.parameters[key][0]
      ? this.parameters[key][0]
      : null;
  },

  /**
   * Function call to retrieve parameters.
   *
   * @param   {string} key - Key of the parameter to retrieve.
   * @returns {object[] | string[]} Parameters - found paramters for given key or null if not found.
   */
  getParameters: function (key) {
    return this.parameters[key] || null;
  },

  /*
   * Handle the javascript part.
   */
  handleJavascript: function () {
    var $ = this.jQuery;
    var javascriptUrls = this.getParameters("javascript_urls");
    var deferreds = [];
    if (javascriptUrls) {
      this.javascriptUrls = javascriptUrls;
      for (var i = 0; i < javascriptUrls.length; i++) {
        deferreds.push(this._getLoadScriptDeferred(javascriptUrls[i]));
      }
    }

    return $.when.apply($, deferreds);
  },

  /*
   * Wraps blueConicClient.util.loadScript into a promise
   */
  _getLoadScriptDeferred: function (url) {
    // eslint-disable-next-line new-cap
    var def = this.jQuery.Deferred();
    var scriptElement = document.createElement("script");
    scriptElement.setAttribute("src", url);
    scriptElement.onload = function () {
      def.resolve();
    };
    scriptElement.onerror = function () {
      def.reject('Url "' + url + "\" couldn't be loaded");
    };
    document.head.appendChild(scriptElement);
    return def;
  },

  /*
   * Handles the styling part.
   */
  handleStyling: function (closeIcon, hoverCloseIcon, callback) {
    var content = this.getParameter("content");
    var urls = [this.baseURL + "frontend/src/lib/fancybox/jquery.fancybox.css"];

    if (!content || content.indexOf("bcLightboxTemplate") === -1) {
      urls.push(this.baseURL + "frontend/src/css/lightbox.css");
    }

    // Load the css for styling the notifier and overlay
    var stylingUrl = this.getParameter("styling_css");
    if (stylingUrl) {
      this.stylingUrl = stylingUrl;
      urls.push(stylingUrl);
    }
    var css = "";

    var customClose = this.getParameter("custom_close") === "true";

    if (customClose && closeIcon) {
      css +=
        ".fancybox-close {background-image: url('" +
        closeIcon +
        "');background-repeat: no-repeat;background-position: center center;background-size: contain;}";
      if (hoverCloseIcon) {
        css +=
          ".fancybox-close:hover {background-image: url('" +
          hoverCloseIcon +
          "');background-repeat: no-repeat;background-position: center center;background-size: contain;}";
      }
    }
    // add position of the close button
    var closePosition = this.getParameter("close_position");
    var closePadding = this.getParameter("close_padding");
    css += this._getClosePositionStyling(closePosition, closePadding);

    var inlineStyling = this.getParameter("styling_css_inline");
    if (inlineStyling) {
      css += inlineStyling.replace(/&#xd;/gi, "");
    }

    if (css) {
      this.inlineCss = this.jQuery("<style>" + css + "</style>");
      this.inlineCss.appendTo(this.jQuery("body"));
    }

    return this._loadCssUrls(urls, callback);
  },

  /**
   * Loads the given CSS urls and calls the callback when all CSS is loaded.
   *
   * @param {string[]} urls - The css urls to load.
   * @param {Function} callback - The callback to call when the CSS is loaded.
   */
  _loadCssUrls: function (urls, callback) {
    urls = urls || [];
    var total = urls.length;
    var count = 0;
    var errorList = [];

    if (total === 0) {
      return callback();
    }

    /**
     * Link onload handler.
     */
    function urlLoaded() {
      count++;
      if (count >= total) {
        return errorList.length > 0 ? callback(errorList) : callback();
      }
    }

    urls.forEach(function (url) {
      if (!document.querySelector('link[href="' + url + '"]')) {
        var link = document.createElement("link");
        link.setAttribute("rel", "stylesheet");
        link.setAttribute("href", url);

        link.onload = urlLoaded;
        link.onerror = function (err) {
          errorList.push(err);
          urlLoaded();
        };

        document.head.appendChild(link);
      } else {
        // Url already loaded
        urlLoaded();
      }
    });
  },

  /**
   * Get close position styling.
   *
   * @param {string} closePosition - (e.g. TOP_RIGHT, TOP_LEFT, BOTTOM_RIGHT).
   * @param {string} closePadding - The amount of padding added to the position.
   */
  _getClosePositionStyling: function (closePosition, closePadding) {
    if (!closePosition) {
      return "";
    }

    // set the default value if the padding is invalid
    if (closePadding === null || closePadding === "NaN") {
      closePadding = "-18";
    }
    var closePositionCss = ".fancybox-close {";

    switch (closePosition) {
      case "TOP_LEFT":
        closePositionCss +=
          "top:" +
          closePadding +
          "px; right: unset; bottom: unset; left:" +
          closePadding +
          "px;";
        break;
      case "BOTTOM_RIGHT":
        closePositionCss +=
          "top: auto; right: " +
          closePadding +
          "px; bottom: " +
          closePadding +
          "px; left: unset;";
        break;
      default:
        closePositionCss +=
          "top: " +
          closePadding +
          "px; right: " +
          closePadding +
          "px; bottom: unset; left: unset;";
        break;
    }
    return (closePositionCss += "}");
  }
});
var a = [];var i='lightboxinteractiontype';a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.4.0/frontend/src/node_modules/@blueconic/jquery-x-jquerymigrate/load_jQuery3_5_X_jQueryMigrate.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.4.0/'},{ id : 'html', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'html/1.0.10/'},{ id : 'image', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'image/1.0.2/'},{ id : 'number', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'number/1.0.2/'},{ id : 'string', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'string/1.0.1/'}]);})();(function(){ var InteractionTypeImpl = InteractionType.extend({
  EVENT_NAME: "adblock_detected",

  init: function (blueConicClient, context) {
    this.blueConicClient = blueConicClient;
    this.context = context;
  },

  getPreloadProperties: function () {
    var parameters = this.context.getParameters();
    var propertyStr = parameters.property
      ? parameters.property[0]
      : parameters.property;

    if (!propertyStr) {
      return [];
    }

    return [propertyStr];
  },

  /**
   * @description Main function of the interaction. Makes use of the just-detect-adblock library:
   * https://github.com/wmcmurray/just-detect-adblock.
   */
  onLoad: function () {
    var listener = this;
    var profile = this.context.getProfile();
    var parameters = this.context.getParameters();
    var propertyId = parameters.property
      ? parameters.property[0]
      : parameters.property;

    if (!propertyId) {
      propertyId = this.EVENT_NAME;
    }

    var adBlockNotDetected = function () {
      // Persist when a change is detected
      if (profile.getValue(propertyId) !== "no") {
        // Store the value in the profile
        profile.setValue(propertyId, "no");

        // Persist the profile
        listener.blueConicClient.profile.updateProfile();
      }
    };

    var adBlockDetected = function () {
      // Persist when a change is detected
      if (profile.getValue(propertyId) !== "yes") {
        // Store the value in the profile
        profile.setValue(propertyId, "yes");

        // Persist the profile
        listener.blueConicClient.profile.updateProfile();
      }
      listener.blueConicClient.createEvent(listener.EVENT_NAME);
    };

    var userAgent = window.navigator.userAgent;
    var userAgentIsIE = /MSIE|Trident/.test(userAgent);

    // Since the ad blocker detection library is promise-based which isn't supported in IE
    if (!userAgentIsIE) {
      justDetectAdblock.detectAnyAdblocker().then(function (detected) {
        if (detected) {
          adBlockDetected();
        } else {
          adBlockNotDetected();
        }
      });
    } else {
      adBlockNotDetected();
    }
  }
});
var a = [];var i='listener_adblock';a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.1.0/frontend/src/lib/just-detect-adblock.min.js', sharing: 'none'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.1.0/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(e,t){this.blueConicClient=e,this.context=t},getPreloadProperties:function(){var e=this.context.getParameters(),t=e.responseProperty?e.responseProperty[0]:e.responseProperty;return t?(this.campaignIdentifierProperty=t,[t]):(this.campaignIdentifierProperty="responded_to_campaigns",["responded_to_campaigns"])},onLoad:function(){var e=this.context.getProfile(),t=this.context.getParameters(),r=this.blueConicClient,n=!1,i=!1,o=t.config?t.config[0]:t.config;if(o){for(var a=this.blueConicClient.json.parse(o),c=0;c<a.length;c++){var p=a[c],l=this.getParameterByName(p.parameter);l&&p.profileProperty&&(e.addValue(p.profileProperty,l),n=!0,p.isCampaignIdentifier&&!i&&(this._bindHandlers(l),i=!0))}n&&r.profile.updateProfile()}},_bindHandlers:function(e){var t=this,r=this.context.getProfile(),n=this.blueConicClient,i=document.querySelectorAll("a");Array.prototype.forEach.call(i,(function(i){i.addEventListener("click",(function(){r.addValue(t.campaignIdentifierProperty,e),n.profile.updateProfile()}))}));i=document.querySelectorAll("form");Array.prototype.forEach.call(i,(function(i){i.addEventListener("submit",(function(){r.addValue(t.campaignIdentifierProperty,e),n.profile.updateProfile()}))}))},getParameterByName:function(e){if(!e)return"";e=e.replace(/[[]/,"\\[").replace(/[\]]/,"\\]");var t=new RegExp("[\\?&#]"+e+"=([^&#]*)").exec(this.getLocationHref());return null===t?"":decodeURIComponent(t[1].replace(/\+/g," "))},getLocationHref:function(){return window.location.href}});var a = [];var i='listener_campaign_tracker';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.1.0/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({PARAMETERS:{ENGAGEMENT_PROPERTY:"engagementProperty",ENGAGEMENT_SCORE_PROPERTY:"engagementScoreProperty",DECAY:"decay",ENGAGEMENT_ON_CHANNEL:"engagementOnChannel"},DEFAULTS:{ENGAGEMENT:"engagement",ENGAGEMENT_SCORE:"engagement_score",VISITS:"visits",CLICKCOUNT:"clickcount"},SCORES:{LOW:"low",MEDIUM:"medium",HIGH:"high"},DEFAULT_DECAY:50,init:function(e,t){this.blueConicClient=e,this.context=t,this.parameters=t.getParameters(),this._channelId=e.getChannelId();var i="true"===this.getParameterValue(this.PARAMETERS.ENGAGEMENT_ON_CHANNEL)&&this._channelId;this.properties={engagement:this.getParameterValue(this.PARAMETERS.ENGAGEMENT_PROPERTY,this.DEFAULTS.ENGAGEMENT),engagementScore:this.getParameterValue(this.PARAMETERS.ENGAGEMENT_SCORE_PROPERTY,this.DEFAULTS.ENGAGEMENT_SCORE),engagementObject:"_"+this.getParameterValue(this.PARAMETERS.ENGAGEMENT_PROPERTY,this.DEFAULTS.ENGAGEMENT),visits:this.DEFAULTS.VISITS+(i?"_"+this._channelId:""),clickcount:this.DEFAULTS.CLICKCOUNT+(i?"_"+this._channelId:"")};var r=new Date(2015,0,1,0,0,0,0),n=(new Date).getTime()-r.getTime();this.days=Math.floor(n/864e5),this.weekNr=Math.floor(this.days/7),this.decay=parseInt(this.getParameterValue(this.PARAMETERS.DECAY))||this.DEFAULT_DECAY},getPreloadProperties:function(){return[this.properties.engagementObject,this.properties.visits,this.properties.clickcount]},onLoad:function(){var e=this.context.getProfile(),t=e.getValue(this.properties.clickcount)?parseInt(e.getValue(this.properties.clickcount)):0,i=e.getValue(this.properties.visits)?parseInt(e.getValue(this.properties.visits)):0,r=e.getValues(this.properties.engagementObject).map(function(e){return this.blueConicClient.json.parse(e)||{}}.bind(this)),n=this._clearInvalidValues(r,i),s=n.cleanedValues,a=this._sumInternalValues(s),h=this._addCurrentWeek(a,t,i),o=this._getCalculated(a,i,t),c=this._calculateScore(o);isNaN(c)||((h||s.length>1||n.removedValues)&&e.setValue(this.properties.engagementObject,JSON.stringify(a)),this._setEngagement(e,c))},getParameterValue:function(e,t){return this.parameters&&this.parameters[e]&&this.parameters[e][0]?this.parameters[e][0]:t},_clearInvalidValues:function(e,t){var i=!1;return e.forEach(function(e){var r=Object.keys(e).filter(function(e){return-1!==e.indexOf("v")}).map(function(e){return parseInt(e.substring(1))});r.sort(function(e,t){return t-e}),r.forEach(function(r){(i||e["v"+r]>t||e["v"+r]<0)&&(delete e["v"+r],delete e["c"+r],i=!0)})},this),{removedValues:i,cleanedValues:e}},_sumInternalValues:function(e){var t={};return e.forEach(function(e){Object.keys(e).forEach(function(i){t[i]=(t[i]||0)+e[i]})}),t},_setEngagement:function(e,t){var i=this.context.getParameters(),r=parseInt(i.lowTreshold?i.lowTreshold[0]:i.lowTreshold),n=parseInt(i.highTreshold?i.highTreshold[0]:i.highTreshold),s=this.SCORES.MEDIUM;t<r?s=this.SCORES.LOW:t>n&&(s=this.SCORES.HIGH),e.setValue(this.properties.engagementScore,t),e.setValue(this.properties.engagement,s),this.blueConicClient.profile.updateProfile()},_addCurrentWeek:function(e,t,i){var r=!1;return e["v"+this.weekNr]||(e["v"+this.weekNr]=i,r=!0),e["c"+this.weekNr]||(e["c"+this.weekNr]=t,r=!0),r},_calculateScore:function(e){for(var t=0,i=0;i<e.length;i++){var r=this._getWeight(i+1,this.decay),n=e[i];t+=(n.clickCount+5*n.visits)*r}return t=Math.floor(t)},_getWeight:function(e,t){return e<=.1*t?1:e<=.2*t?.8:e<=.4*t?.5:e<=t?.3:.1},_getCalculated:function(e,t,i){for(var r=[],n=this.weekNr;n>0;n--){var s=0;e["v"+n]&&(t-=s=Math.max(t-e["v"+n],0));var a=0;e["c"+n]&&(i-=a=Math.max(i-e["c"+n],0)),r.push({week:n,visits:s,clickCount:a})}return r}});var a = [];var i='listener_engagement';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.1.0/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(e,t){this.blueConicClient=e,this.context=t||null,this.POLLING_TIMEOUT=1e3,this.parameters=t.getParameters()},getPreloadProperties:function(){return["funnel_timestamp","funnel_busy_with","funnel_steps","funnel_laststep","funnel_lastfield"]},_setLastFocus:function(e){this.context.getProfile().setValue("funnel_lastfield",this._funnelName+" - "+this._currentStepId+": "+e),this.blueConicClient.profile.updateProfile()},_addBindings:function(){var e=this,t=["button","hidden","reset","submit"],inputEvtHandler=function(n){var r=n.target.type;-1===t.indexOf(r)&&e._setLastFocus(e._getFieldName(n.target))},selectAndTextareaEvtHandler=function(t){e._setLastFocus(e._getFieldName(t.target))},n=document.querySelectorAll("input"),r=document.querySelectorAll("select"),i=document.querySelectorAll("textarea");Array.prototype.forEach.call(n,(function(e){e.removeEventListener("focus",inputEvtHandler),e.addEventListener("focus",inputEvtHandler)})),Array.prototype.forEach.call(r,(function(e){e.removeEventListener("focus",selectAndTextareaEvtHandler),e.addEventListener("focus",selectAndTextareaEvtHandler)})),Array.prototype.forEach.call(i,(function(e){e.removeEventListener("focus",selectAndTextareaEvtHandler),e.addEventListener("focus",selectAndTextareaEvtHandler)}))},_getFieldName:function(e){return e.getAttribute("name")||e.getAttribute("id")||e.getAttribute("autocomplete")||"Unnamed form field"},_urlsMatches:function(e,t){var n=this;return e.urlMatching.filter((function(e){return n._urlMatches(e,t)})).length>0},_urlMatches:function(e,t){var n=this._normalizeUrl(t),r=this._normalizeUrl(e.url),i=this._escapeRegularExpressionCharacters(r);try{return new RegExp(i,"i").test(n)}catch(a){return!1}},_escapeRegularExpressionCharacters:function(e){if(e){return e=(e=e.replace(/\.(?!\*)|[\\?]/g,(function(e){return"\\"+e}))).replace(/(\.\*|\*)/g,".*")}return""},_stepIsVisible:function(e,t){var n=this;return e.urlMatching.filter((function(e){return n._urlMatches(e,t)&&(!e.word||n._wordIsVisible(e.word))})).length>0},_wordIsVisible:function(e){return e=e.toLowerCase(),Array.prototype.filter.call(Array.prototype.filter.call(document.getElementsByTagName("*"),(function(t){return-1!==t.innerText.toLowerCase().indexOf(e)})),(function(e){return e.offsetWidth>0&&e.offsetHeight>0})).length>0},_convertStepMapping:function(e,t){var n=this,r=t.map((function(e){return e.name}));return e.filter((function(e){return 0===e.indexOf(n._funnelName)})).map((function(e){var t,n=e.match(/'(.*)' to '(.*)'/);if(n&&n[1]&&n[2]&&-1!==r.indexOf(n[1])&&-1!==r.indexOf(n[2]))t={source:n[1],target:n[2]};else{var i=e.match(/started at '(.*)'/);i&&i[1]&&-1!==r.indexOf(i[1])&&(t={start:i[1]})}return t})).filter((function(e){return e}))},_getFollowedStepsMapping:function(e,t){var n=this.context.getProfile(),r=this._convertStepMapping(n.getValues("funnel_steps"),t),i=null,a=(t.slice(0,t.indexOf(e)),!1);return t.forEach((function(t){var n=t.name;(a=a||n===e)||r.filter((function(e){return e.start===n||e.target===n})).length>0&&(i=n)})),i?this._funnelName+" : '"+i+"' to '"+e+"'":this._funnelName+" : started at '"+e+"'"},_checkWordMatch:function(e){var t=this;setTimeout((function(){var n=!1;t._queue.forEach((function(r){t._stepIsVisible(r,e)&&(n=!0)})),n?t._onLoad():t._checkWordMatch(e)}),this.POLLING_TIMEOUT)},onLoad:function(){this.blueConicClient.event.subscribe(this.blueConicClient.event.onUrlChange,this,(function(){this._onLoad()})),this._onLoad()},_handleEndReached:function(){var e=this.context.getProfile(),t=e.getValues("funnel_busy_with"),n=t.indexOf(this._funnelName);-1!==t.indexOf(this._funnelName)&&(t.splice(n,1),e.setValues("funnel_busy_with",t))},_getUrl:function(){return document.location.origin+document.location.pathname+document.location.search+document.location.hash},_getSteps:function(){var e=this.parameters.steps?this.parameters.steps[0]:this.parameters.steps;return e?this.blueConicClient.json.parse(e):[]},_normalizeUrl:function(e){return e=this._removeUrlPart(e,"http://"),e=this._removeUrlPart(e,"https://"),e=this._removeUrlPart(e,"www.")},_removeUrlPart:function(e,t){return 0===e.indexOf(t)&&(e=e.substring(t.length)),e},_onLoad:function(e){var t=this,n=this.context.getProfile();this._funnelName=this.parameters.funnelName?this.parameters.funnelName[0]:this.parameters.funnelName;var r=this._getSteps();if(0!==r.length){e=e||this._getUrl();var i=r.filter((function(n){return t._urlsMatches(n,e)}));this._queue=[];var a=null;if(i.forEach((function(n){t._stepIsVisible(n,e)?a=n:t._queue.push(n)})),this._queue.length>0&&this._checkWordMatch(e),null!==a){this._currentStepId=a.name,this._addBindings(),n.setValue("funnel_laststep",this._funnelName+" - "+this._currentStepId);var s=this._getFollowedStepsMapping(this._currentStepId,r);n.addValue("funnel_steps",s);var u=!1,l=r.filter((function(e){return(u=u||e.name===a.name)&&e.name!==a.name})),o=n.getValues("funnel_steps"),c=this._funnelName;l.forEach((function(e){o=o.filter((function(t){return 0!==t.indexOf(c+" :")||-1===t.indexOf("started at '"+e.name+"'")&&-1===t.indexOf("to '"+e.name+"'")}))})),n.setValues("funnel_steps",o),n.setValue("funnel_lastfield",""),this._currentStepId===r[r.length-1].name?this._handleEndReached():n.addValue("funnel_busy_with",this._funnelName);var f=this.blueConicClient.getCurrentDate().getTime();n.setValue("funnel_timestamp",f),this.blueConicClient.profile.updateProfile()}}}});var a = [];var i='listener_funnel';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.0/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.context=b},getPreloadProperties:function(){return[]},onLoad:function(){}});var a = [];var i='listener_geolocation';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.0.12/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.context=b;var c=this.context.getParameters();this.property=c.property&&c.property[0]?c.property[0]:"incognito_detected"},getPreloadProperties:function(){return[this.property]},onLoad:function(){this.checkIncognitoMode(function(a){var b=this.blueConicClient.profile.getProfile(),c=b.getValue(this.property),d=a?"on":"off";c!==d&&(b.setValue(this.property,d),this.blueConicClient.profile.updateProfile()),a&&this.blueConicClient.createEvent("incognito_detected")}.bind(this))},_isIE10OrLater:function(){var a=window.navigator.userAgent.toLowerCase();if(0===a.indexOf("msie")&&0===a.indexOf("trident"))return!1;var b=/(?:msie|rv:)\s?([\d.]+)/.exec(a);if(b&&10<=parseInt(b[1],10))return!0;var c=/edge/.exec(a);return!!(c&&"edge"===c[0])},checkIncognitoMode:function(a){var b=window.RequestFileSystem||window.webkitRequestFileSystem;if(b)b(window.PERSISTENT,1,a.bind(this,!1),a.bind(this,!0));else if(window.indexedDB&&/Firefox/.test(window.navigator.userAgent))try{var c=window.indexedDB.open("test");c.onerror=a.bind(this,!0),c.onsuccess=a.bind(this,!1)}catch(b){return a(!0)}else{if(this._isIE10OrLater()){try{if(!window.indexedDB)return a(!0)}catch(b){return a(!0)}return a(!1)}if(window.localStorage&&/Safari/.test(window.navigator.userAgent)){if(window.openDatabase)try{window.openDatabase(null,null,null,null)}catch(b){return a(!0)}try{var d=this.context.getInteractionId();window.localStorage.setItem(d,"test"),window.localStorage.removeItem(d)}catch(b){return a(!0)}return a(!1)}}}});var a = [];var i='listener_incognito';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/listener_incognito/ts_c14c55dd62b53c40f7fe95ce4f3ebfc5/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.context=b},getPreloadProperties:function(){return['ip_address']},onLoad:function(){var a=this.context.getProfile(),b=a.getValue('ipAddress'),c=this.blueConicClient.getIPAddress();c!==b&&(a.setValue('ip_address',c),this.blueConicClient.profile.updateProfile())}});var a = [];var i='listener_ip_address';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/listener_ip_address/ts_02dbcaa258a21885238ee896ca3b52a4/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.context=b;var c=new Date(2017,8,1,0,0,0,0),d=this.blueConicClient.getCurrentDate().getTime(),e=d-c.getTime();this.days=Math.floor(e/86400000)},getPreloadProperties:function(){return[]},onLoad:function(){var a=this.context.getProfile(),b=this.context.getParameters(),c=b.property?b.property[0]:b.property;if(c){var d=this.blueConicClient.util.array.ensureArray(b.excludedKeywords),e=this.blueConicClient.json.parse(c)[0].profileproperty,f=[],g=document.getElementsByTagName("meta");if(g)for(var h=!1,j=0,k=g.length;j<k;j++)if("news_keywords"===g[j].name.toLowerCase()){var l=g[j].content.split(",");0===l.length||1===l.length&&""===l[0]||(f=l,h=!0)}else h||0!==f.length||"keywords"!==g[j].name.toLowerCase()||(f=g[j].content.split(","));if(0<f.length){for(var m,n={TIME:new Date().getTime(),days:this.days,points:1,keywords:[]},o=0;o<f.length;o++)m=this._trim(f[o]),""!==m&&-1===this.blueConicClient.util.array.indexOfArray(d,m)&&n.keywords.push(m);0<n.keywords.length&&(a.addValue("_hl_"+e,this.blueConicClient.json.stringify(n)),this.blueConicClient.profile.updateProfile())}}},_trim:function(a){return a.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}});var a = [];var i='listener_meta_keywords_ranker';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.6/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.context=b;var c=new Date(2017,8,1,0,0,0,0),d=this.blueConicClient.getCurrentDate().getTime(),e=d-c.getTime();this.days=Math.floor(e/86400000)},getPreloadProperties:function(){return[]},onLoad:function(){var a=this.context.getProfile(),b=this.context.getParameters(),c=b.property?b.property[0]:b.property;if(c){var d=this.blueConicClient.json.parse(c)[0].profileproperty,e=this.blueConicClient.getCurrentDate(),f=this._getTimeFrame(e.getHours(),b.locale[0]),g={TIME:new Date().getTime(),data:[]};g.data.push({n:f,p:1,d:this.days}),a.addValue("_hl_"+d,this.blueConicClient.json.stringify(g)),this.blueConicClient.profile.updateProfile()}},_getTimeFrame:function(a,b){return this._getHour(a,b)+" - "+this._getHour(a+1,b)},_getHour:function(a,b){if("en-us"===b){var c=12<=a?"PM":"AM";return a%=12,a=0===a?12:a,a+" "+c}return a=10>a?"0"+a:a,a+":00"}});var a = [];var i='listener_preferred_hour';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.2.4/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({SESSION_TIMEOUT_MINUTES:30,LAST_SUBSCRIPTION_HISTORY_SYNC_COOKIE:'bc_lshs',LOCAL_STORAGE_KEY:'hnp_subs',SESSION_FOUND_EVENT:'bc_session_found',init:function(a,b){this.blueConicClient=a,this.context=b,this.parameters=this.context.getParameters();var c=this;window.treg&&window.treg.registerEvent&&window.treg.event&&window.treg.event.onSessionFound&&window.treg.registerEvent(window.treg.event.onSessionFound,function(){c.blueConicClient.event.publish(c.SESSION_FOUND_EVENT)})},_getSubscriptions:function(a,b){var c=this.parameters.serviceURL&&this.parameters.serviceURL[0]?this.parameters.serviceURL[0]:'https://identity.sfchronicle.com/propensityToSubscribe';this.jQuery.ajax({url:c+'?subscriber_id='+a,dataType:'json'}).done(function(a){if(a&&a.data&&a.data.subscriptions)return b(a.data.subscriptions)}).fail(this.jQuery.proxy(function(a,b){this.blueConicClient.util.log('[ERROR] '+b)},this))},_getSubscriberId:function(){if(window.HDN&&window.HDN.dataLayer&&window.HDN.dataLayer.identity&&window.HDN.dataLayer.identity.edbUserId)return window.HDN.dataLayer.identity.edbUserId;var a=this.blueConicClient.util.cookie.getCookie('at');if(!a)return null;var b=a.match(/&sLId=(\d+)/);return b&&b[1]?b[1]:null},_shouldSync:function(){var a=this.blueConicClient.getCurrentDate().getTime(),b=this.blueConicClient.util.cookie.getCookie(this.LAST_SUBSCRIPTION_HISTORY_SYNC_COOKIE);if(!b||isNaN(b))return!0;var c=new Date(parseInt(b));return c.setMinutes(c.getMinutes()+this.SESSION_TIMEOUT_MINUTES),!!(a>c)||!window.localStorage.getItem(this.LOCAL_STORAGE_KEY)},_storeSubscriptions:function(a){try{var b=this.blueConicClient.json.stringify(a);window.localStorage.setItem(this.LOCAL_STORAGE_KEY,b);var c=this.blueConicClient.getCurrentDate().getTime();this.blueConicClient.util.cookie.setCookie(this.LAST_SUBSCRIPTION_HISTORY_SYNC_COOKIE,c)}catch(a){this.blueConicClient.util.log('[BC][ERROR] while storing subscriptions: '+a.message||a.toString())}},_synchronizeSubscriptions:function(){var a=this._getSubscriberId();return a?void(!this._shouldSync(a)||this._getSubscriptions(a,this.jQuery.proxy(this._storeSubscriptions,this))):void this.blueConicClient.util.log('[WARN] No subscriber id found')},onLoad:function(){var a;this._getSubscriberId()?this._synchronizeSubscriptions():(a=setTimeout(this.jQuery.proxy(this._synchronizeSubscriptions,this),1e4),this.blueConicClient.event.subscribe(this.SESSION_FOUND_EVENT,this,function(){a&&clearTimeout(a),setTimeout(this.jQuery.proxy(this._synchronizeSubscriptions,this),1e4)}))}});var a = [];var i='listener_subscription_history';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/listener_subscription_history/ts_5ec9d3b33b6c80ebeaa819b4f5847f88/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.context=b;var c=new Date(2012,0,1,0,0,0,0),d=new Date,e=d.getTime()-c.getTime();this.days=Math.floor(e/86400000)},getPreloadProperties:function(){return[]},onLoad:function(){var a=this.context.getParameters(),b=a.config?a.config[0]:a.config;if(b){var c=this.blueConicClient.json.parse(b),d=document.location.href;(0<=d.indexOf("#")||0<=d.indexOf("?"))&&(d=d.substring(0,d.indexOf("#"))||d.substring(0,d.indexOf("?")));var e,f=d.split("/"),g=!1;for(e=0;e<c.length;e++){var h=c[e],i=f[e+3];h.checked&&h.profileProperty&&!g&&(this._storeEngagement(h.profileProperty,this._getValue(i)),i&&30<i.length&&h.checked&&(g=!0))}this.blueConicClient.profile.updateProfile()}},_getValue:function(a){return a?30<a.length?null:(0<=a.indexOf(".")&&(a=a.substring(0,a.indexOf("."))),isNaN(a)&&"index"!==a&&0!==a.indexOf("index.")?a:null):null},_storeEngagement:function(a,b){if(b){var c=this.context.getProfile(),d={TIME:new Date().getTime()};d[b]={},d[b]["p"+this.days]=1,c.addValue("_"+a,this.blueConicClient.json.stringify(d))}}});var a = [];var i='listener_url_structure';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.0.18/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({blueConicClient:null,context:null,_profile:null,_userLanguage:null,_systemLanguage:null,_language:null,_referrer:null,_hostName:null,_currentUrl:null,_domain:null,ORIGIN_TYPES:{WEB:"web",MOBILE_WEB:"mobile_web",CONNECTION:"connection",MOBILE:"mobile_app"},CONSTANTS:{THIRTY_MINUTES_IN_MS:18e5,UNKNOWN:""},PROFILE_PROPERTIES:{CLICKCOUNT:"clickcount",VISITS:"visits",VISITCLICKS:"visitclicks",LASTVISITDATE:"lastvisitdate",VISITEDSITES:"visitedsites",VISITEDDOMAIN:"visiteddomain",ENTRYPAGE:"entrypage",REFERRERHOST:"referrerhost",REFERRERHOSTS:"referrerhosts",HOSTENTRYPAGE:"hostentrypage",HOSTAVERAGETIME:"hostaveragetime",LASTREFERRERAVERAGE:"lastreferreraverage",AVERAGETIME:"averagetime",TOTALVISITTIME:"totalvisittime",RESOLUTION:"resolution",CURRENTRESOLUTION:"currentresolution",CURRENTSCREENWIDTH:"currentscreenwidth",CURRENTSCREENHEIGHT:"currentscreenheight",ORIGIN_TYPE:"origin_type",ORIGIN_SOURCE:"origin_source",ORIGIN_DETAIL:"origin_detail",DEVICETYPE:"devicetype",RECEIVED_FROM_SYSTEM:"received_from_system",RECEIVED_FROM_CONNECTION:"received_from_connection",MOBILE_APP_ID:"mobile_app_id",MOBILE_APP_NAMEVERSION:"mobile_app_nameversion",LANGUAGE:"language",KEYWORDS:"keywords",CURRENTKEYWORDS:"currentkeywords",CURRENT_UTM_SOURCE:"current_utm_source",CURRENT_UTM_MEDIUM:"current_utm_medium",CURRENT_UTM_TERM:"current_utm_term",CURRENT_UTM_CONTENT:"current_utm_content",CURRENT_UTM_CAMPAIGN:"current_utm_campaign",UTM_SOURCE:"utm_source",UTM_MEDIUM:"utm_medium",UTM_TERM:"utm_term",UTM_CONTENT:"utm_content",UTM_CAMPAIGN:"utm_campaign"},PROFILE_PROPERTIES_FOR_CHANNEL:{},init:function(e,t){this.blueConicClient=e,this.context=t,this._profile=e.profile.getProfile(),this._channelId=e.getChannelId(),this._referrer=document.referrer,this._hostName=window.location.hostname,this._currentUrl=window.location.href,this._domain=document.domain,this._userLanguage=window.navigator.userLanguage,this._systemLanguage=navigator.systemLanguage,this._language=window.navigator.language,this.PROFILE_PROPERTIES_FOR_CHANNEL={CLICKCOUNT:this.PROFILE_PROPERTIES.CLICKCOUNT+"_"+this._channelId,VISITS:this.PROFILE_PROPERTIES.VISITS+"_"+this._channelId,VISITCLICKS:this.PROFILE_PROPERTIES.VISITCLICKS+"_"+this._channelId,LASTVISITDATE:this.PROFILE_PROPERTIES.LASTVISITDATE+"_"+this._channelId}},onPrepare:function(){this._profile&&(this._setLanguageProperties(),this._setResolutionProperties(),this._setReferrerProperties(),this._setCampaignProperties())},onLoad:function(){this._profile&&(this._setReferrerHostOnLoad(),this._setVisitProperties(),this._setOriginProperties(),this.blueConicClient.profile.updateProfile())},getPreloadProperties:function(){return[this.PROFILE_PROPERTIES.CLICKCOUNT,this.PROFILE_PROPERTIES.VISITS,this.PROFILE_PROPERTIES.VISITCLICKS,this.PROFILE_PROPERTIES.LASTVISITDATE,this.PROFILE_PROPERTIES.VISITEDSITES,this.PROFILE_PROPERTIES.ENTRYPAGE,this.PROFILE_PROPERTIES.HOSTENTRYPAGE,this.PROFILE_PROPERTIES.HOSTAVERAGETIME,this.PROFILE_PROPERTIES.LASTREFERRERAVERAGE,this.PROFILE_PROPERTIES.AVERAGETIME,this.PROFILE_PROPERTIES.TOTALVISITTIME,this.PROFILE_PROPERTIES.RESOLUTION,this.PROFILE_PROPERTIES.DEVICETYPE,this.PROFILE_PROPERTIES.ORIGIN_TYPE,this.PROFILE_PROPERTIES.ORIGIN_SOURCE,this.PROFILE_PROPERTIES.ORIGIN_DETAIL,this.PROFILE_PROPERTIES.RECEIVED_FROM_SYSTEM,this.PROFILE_PROPERTIES.RECEIVED_FROM_CONNECTION,this.PROFILE_PROPERTIES.VISITEDDOMAIN,this.PROFILE_PROPERTIES.MOBILE_APP_ID,this.PROFILE_PROPERTIES.MOBILE_APP_NAMEVERSION,this.PROFILE_PROPERTIES_FOR_CHANNEL.CLICKCOUNT,this.PROFILE_PROPERTIES_FOR_CHANNEL.VISITS,this.PROFILE_PROPERTIES_FOR_CHANNEL.VISITCLICKS,this.PROFILE_PROPERTIES_FOR_CHANNEL.LASTVISITDATE]},_setLanguageProperties:function(){var e=this._userLanguage||this._systemLanguage||this._language,t=this._normalizeLocale(e).split("-")[0];t&&this._profile.setValue(this.PROFILE_PROPERTIES.LANGUAGE,t)},_normalizeLocale:function(e){return e&&e.replace("_","-").toLowerCase()},_setResolutionProperties:function(){var e=screen.width,t=screen.height;this._profile.setValue(this.PROFILE_PROPERTIES.CURRENTSCREENWIDTH,e),this._profile.setValue(this.PROFILE_PROPERTIES.CURRENTSCREENHEIGHT,t);var i=e+"x"+t;this._profile.setValue(this.PROFILE_PROPERTIES.CURRENTRESOLUTION,i),this._profile.addValue(this.PROFILE_PROPERTIES.RESOLUTION,i)},_setReferrerProperties:function(){this._setReferrerKeywords(),this._setReferrerHost()},_setReferrerKeywords:function(){var e=this.HELPER.decodeReferrer(this._referrer)||[];e.length>0&&(this._addProfileValues(this.PROFILE_PROPERTIES.KEYWORDS,e),this._profile.setValues(this.PROFILE_PROPERTIES.CURRENTKEYWORDS,e))},_addProfileValues:function(e,t){(Array.isArray(t)?t:[t]).forEach(function(t){this._profile.addValue(e,t)},this)},_setReferrerHost:function(){var e=this._getReferrerHost();e!==this._hostName&&(this._profile.setValue(this.PROFILE_PROPERTIES.ENTRYPAGE,this._currentUrl),e&&(this._profile.setValue(this.PROFILE_PROPERTIES.REFERRERHOST,e),this._profile.addValue(this.PROFILE_PROPERTIES.REFERRERHOSTS,e)))},_setReferrerHostOnLoad:function(){var e=this._getReferrerHost();e!==this._hostName&&this._setHostEntryPageProperty(),this._setHostTotalAndAverageTimeProperty(this._hostName,e)},_getReferrerHost:function(){return this._referrer.replace(/http[s]?:\/\/(.*?)(:|\?|\/|$).*/,"$1")},_setCampaignProperties:function(){[this.PROFILE_PROPERTIES.UTM_SOURCE,this.PROFILE_PROPERTIES.UTM_MEDIUM,this.PROFILE_PROPERTIES.UTM_TERM,this.PROFILE_PROPERTIES.UTM_CONTENT,this.PROFILE_PROPERTIES.UTM_CAMPAIGN].forEach(function(e){var t=this._removeHashPart(this.HELPER._getParameterByName(this._currentUrl,e));t&&(this._profile.setValue("current_"+e,t),this._profile.addValue(e,t))},this)},_setHostEntryPageProperty:function(){this._profile.setValue(this.PROFILE_PROPERTIES.ENTRYPAGE,this._currentUrl);var e=this._getHostEntryPageMapping();e[this._hostName]={entrypage:this._currentUrl},this._profile.setValue(this.PROFILE_PROPERTIES.HOSTENTRYPAGE,JSON.stringify(e))},_getHostEntryPageMapping:function(){return this._safeJSONParse(this._profile.getValue(this.PROFILE_PROPERTIES.HOSTENTRYPAGE))},_safeJSONParse:function(e){try{var t=e.replace(/'/g,'"');return JSON.parse(t)||{}}catch(e){return{}}},_setHostTotalAndAverageTimeProperty:function(e,t){var i=this._safeJSONParse(this._profile.getValue(this.PROFILE_PROPERTIES.HOSTAVERAGETIME));i[e]||(i[e]=this._createNewVisitData());var s=this.blueConicClient.getCurrentDate().getTime(),E=this._profile.getValue(this.PROFILE_PROPERTIES.LASTREFERRERAVERAGE),r=0,R=0,I=0;Object.keys(i).map(function(e){return e.toString()}).forEach(function(_){var n=i[_];this._isSessionExpired(n.enddate)?this._addVisit(n,n.enddate-n.startdate):_===e?n.enddate=s:_===t&&E!==t&&(n.enddate=s,this._profile.setValue(this.PROFILE_PROPERTIES.LASTREFERRERAVERAGE,t)),0!==n.averageTime&&(R++,r+=n.averageTime,I+=n.averageTime*n.visits)},this),this._profile.setValue(this.PROFILE_PROPERTIES.HOSTAVERAGETIME,JSON.stringify(i)),this._profile.setValue(this.PROFILE_PROPERTIES.TOTALVISITTIME,I);var _=R>0?Math.round(r/R):0;this._profile.setValue(this.PROFILE_PROPERTIES.AVERAGETIME,_)},_addVisit:function(e,t){if(t>0){var i=e.averageTime*e.visits+t/1e3;e.visits++,e.averageTime=Math.round(i/e.visits)}var s=this.blueConicClient.getCurrentDate().getTime();e.startdate=s,e.enddate=s},_createNewVisitData:function(){var e=this.blueConicClient.getCurrentDate().getTime();return{startdate:e,enddate:e,averageTime:0,visits:0}},_setPropertyIfEmpty:function(e,t,i){void 0===e[t]&&(e[t]=i)},_setVisitProperties:function(){this._addVisitedDomain(this._domain),this._increaseClickCount(),this._increaseVisits(this.PROFILE_PROPERTIES.VISITS,this.PROFILE_PROPERTIES.VISITCLICKS,this.PROFILE_PROPERTIES.LASTVISITDATE),this._channelId&&this._increaseVisits(this.PROFILE_PROPERTIES_FOR_CHANNEL.VISITS,this.PROFILE_PROPERTIES_FOR_CHANNEL.VISITCLICKS,this.PROFILE_PROPERTIES_FOR_CHANNEL.LASTVISITDATE)},_increaseVisits:function(e,t,i){e=e||this.PROFILE_PROPERTIES.VISITS,t=t||this.PROFILE_PROPERTIES.VISITCLICKS,i=i||this.PROFILE_PROPERTIES.LASTVISITDATE,this._isNewSession(e,i)?(this._resetPageViewsCurrentSession(t),this._increaseSessionCount(e)):this._increasePageViewsCurrentSession(t),this._setLastVisitDate(i,this.blueConicClient.getCurrentDate().getTime())},_setLastVisitDate:function(e,t){e=e||this.PROFILE_PROPERTIES.LASTVISITDATE,this._profile.setValue(e,t)},_addVisitedDomain:function(e){this._hasVisitedDomain(e)||this._profile.addValue(this.PROFILE_PROPERTIES.VISITEDSITES,e)},_hasVisitedDomain:function(e){var t=this._profile.getValues(this.PROFILE_PROPERTIES.VISITEDSITES)||[];return t.length>0&&-1!==t.indexOf(e)},_increaseClickCount:function(){var e=this._getNumberProperty(this.PROFILE_PROPERTIES.CLICKCOUNT);if(this._profile.setValue(this.PROFILE_PROPERTIES.CLICKCOUNT,e+1),this._channelId){var t=this._getNumberProperty(this.PROFILE_PROPERTIES_FOR_CHANNEL.CLICKCOUNT);this._profile.setValue(this.PROFILE_PROPERTIES_FOR_CHANNEL.CLICKCOUNT,t+1)}},_isNewSession:function(e,t){e=e||this.PROFILE_PROPERTIES.VISITS,t=t||this.PROFILE_PROPERTIES.LASTVISITDATE;var i=this._getNumberProperty(e),s=this._getNumberProperty(t)||0;return 0===i||this._isSessionExpired(s)},_isSessionExpired:function(e){return this.blueConicClient.getCurrentDate().getTime()>e+this.CONSTANTS.THIRTY_MINUTES_IN_MS},_resetPageViewsCurrentSession:function(e){e=e||this.PROFILE_PROPERTIES.VISITCLICKS,this._profile.setValue(e,1)},_increasePageViewsCurrentSession:function(e){e=e||this.PROFILE_PROPERTIES.VISITCLICKS;var t=this._getNumberProperty(e);this._profile.setValue(e,t+1)},_increaseSessionCount:function(e){e=e||this.PROFILE_PROPERTIES.VISITS;var t=this._getNumberProperty(e);this._profile.setValue(e,t+1)},_setOriginProperties:function(){var e=this._getOriginCount();e>1?this._mergeOriginProperties():0===e&&this._resolveOriginProperties()},_getOriginCount:function(){var e=this._profile.getValues(this.PROFILE_PROPERTIES.ORIGIN_TYPE)||[],t=this._profile.getValues(this.PROFILE_PROPERTIES.ORIGIN_SOURCE)||[],i=this._profile.getValues(this.PROFILE_PROPERTIES.ORIGIN_DETAIL)||[];return Math.max(e.length,t.length,i.length)},_mergeOriginProperties:function(){this._mergePropertyToUnknown(this.PROFILE_PROPERTIES.ORIGIN_TYPE),this._mergePropertyToUnknown(this.PROFILE_PROPERTIES.ORIGIN_SOURCE),this._mergePropertyToUnknown(this.PROFILE_PROPERTIES.ORIGIN_DETAIL)},_mergePropertyToUnknown:function(e){var t=this._profile.getValues(e)||[];this._profile.setValue(e,1===t.length?t[0]:this.CONSTANTS.UNKNOWN)},_resolveOriginProperties:function(){this._isVisitorOriginFromWeb()?this._resolveOriginForWebVisitor():this._isVisitorOriginFromConnection()?this._resolveOriginForProfileComingFromConnection():this._isVisitorOriginFromMobileApp()&&this._resolveOriginForMobileAppVisitor()},_isVisitorOriginFromWeb:function(){var e=this._profile.getValues(this.PROFILE_PROPERTIES.RECEIVED_FROM_SYSTEM)||[],t=this._profile.getValues(this.PROFILE_PROPERTIES.MOBILE_APP_ID)||[];return 0===e.length&&0===t.length},_isVisitorOriginFromMobileApp:function(){var e=this._profile.getValues(this.PROFILE_PROPERTIES.RECEIVED_FROM_SYSTEM)||[],t=this._profile.getValues(this.PROFILE_PROPERTIES.MOBILE_APP_ID)||[],i=this._getNumberProperty(this.PROFILE_PROPERTIES.VISITS);return t.length>0&&0===e.length&&0===i},_isVisitorOriginFromConnection:function(){var e=this._profile.getValues(this.PROFILE_PROPERTIES.RECEIVED_FROM_SYSTEM),t=this._profile.getValues(this.PROFILE_PROPERTIES.MOBILE_APP_ID),i=this._getNumberProperty(this.PROFILE_PROPERTIES.VISITS);return e&&e.length>0&&t&&0===t.length&&i<=0},_resolveOriginForWebVisitor:function(){var e="",t=this._profile.getValues(this.PROFILE_PROPERTIES.VISITEDSITES)||[],i=this._profile.getValue(this.PROFILE_PROPERTIES.DEVICETYPE)||"",s=this._profile.getValues(this.PROFILE_PROPERTIES.ENTRYPAGE)||[];i&&(e="PC"===i?this.ORIGIN_TYPES.WEB:this.ORIGIN_TYPES.MOBILE_WEB);var E=1===t.length?t[0]:this.CONSTANTS.UNKNOWN,r=1===s.length?s[0]:this.CONSTANTS.UNKNOWN;this._setOriginProfileProperties(e,E,r)},_resolveOriginForProfileComingFromConnection:function(){var e=this._profile.getValues(this.PROFILE_PROPERTIES.RECEIVED_FROM_SYSTEM)||[],t=this._profile.getValues(this.PROFILE_PROPERTIES.RECEIVED_FROM_CONNECTION)||[],i=1===e.length?e[0]:this.CONSTANTS.UNKNOWN,s=1===t.length?t[0]:this.CONSTANTS.UNKNOWN;this._setOriginProfileProperties(this.ORIGIN_TYPES.CONNECTION,i,s)},_resolveOriginForMobileAppVisitor:function(){var e=this._profile.getValues(this.PROFILE_PROPERTIES.MOBILE_APP_ID)||[],t=this._profile.getValues(this.PROFILE_PROPERTIES.MOBILE_APP_NAMEVERSION)||[],i=1===e.length?e[0]:this.CONSTANTS.UNKNOWN,s=1===t.length?t[0]:this.CONSTANTS.UNKNOWN;this._setOriginProfileProperties(this.ORIGIN_TYPES.MOBILE,i,s)},_setOriginProfileProperties:function(e,t,i){this._profile.setValue(this.PROFILE_PROPERTIES.ORIGIN_TYPE,e),this._profile.setValue(this.PROFILE_PROPERTIES.ORIGIN_SOURCE,t),this._profile.setValue(this.PROFILE_PROPERTIES.ORIGIN_DETAIL,i)},_removeHashPart:function(e){if(e){var t=e.indexOf("#");if(-1!==t)return e.substring(0,t)}return e},HELPER:{search_engines:[["google\\.","q"],["bing\\.","q"],["search\\.yahoo\\.","p"],["search\\.aol\\.","q"],["duckduckgo\\.","q"],["baidu\\.","wd"],["ask\\.com","q"],["search\\.lycos\\.","q"],["dogpile\\.com","q"]],substringToHash:function(e){if(e){var t=e.indexOf("#");if(-1!==t)return e.substring(0,t)}return e},decodeReferrer:function(e){for(var t=new RegExp(""),i=0;i<this.search_engines.length;i++){var s=this.search_engines[i];t.compile("^http(s?)://(www\\.)?"+s[0],"i");var E=e.match(t);if(E){var r;if(r=isNaN(s[1])?this._getParameterByName(e,s[1]):E[s[1]+1])return r=decodeURIComponent(r),s.length>2&&s[2]&&(r=decodeURIComponent(r)),r=(r=(r=r.replace(/'|"/g,"")).split(/[\s,+.]+/)).filter(function(e){return e});break}}return null},_getParameterByName:function(e,t){if(!t)return"";t=t.replace(/[[]/,"\\[").replace(/[\]]/,"\\]");var i=new RegExp("[\\?&#]"+t+"=([^&#]*)").exec(e);return null===i?"":decodeURIComponent(i[1].replace(/\+/g," "))}},_getNumberProperty:function(e){var t=this._profile.getValue(e);if(!t)return 0;try{t=parseInt(t),isNaN(t)&&(t=0)}catch(e){t=0}return t}});var a = [];var i='listenerinteractiontype';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.1.14/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.context=b,this.rotationStateProperty=this.context.getInteractionId()+"_rotation",this.orchestratorProperty=this.context.getInteractionId()+"_orchestrator",this.profile=this.blueConicClient.profile.getProfile(),this.parameters=this.context.getParameters(),this.rules=this.blueConicClient.json.parse(this.parameters.rules[0])||[],this.rotationEvents=this.parameters.rotation&&this.parameters.rotation[0]?this.blueConicClient.json.parse(this.parameters.rotation[0]):[],this.rotationEvents.sort(function(c,a){return c.priority>a.priority}),this.rotationInterval=this.parameters.rotationInterval&&this.parameters.rotationInterval[0]?parseInt(this.parameters.rotationInterval[0]):0,this.skipFailedEvents=!!(this.parameters.skipFailed&&this.parameters.skipFailed[0])&&"true"===this.parameters.skipFailed[0],this.blueConicClient.event.subscribe(this.blueConicClient.event.onUrlChange,this,function(){this.onLoad()})},getPreloadProperties:function(){return[this.rotationStateProperty,this.orchestratorProperty]},onLoad:function(){var a=this.profile.getValue(this.orchestratorProperty);try{this.profileEvents=a?this.blueConicClient.json.parse(a):{}}catch(a){this.profileEvents={}}for(var b,c={},d=[],e=0;e<this.rules.length;e++)if(b=this.rules[e],"click"===b.type&&this._setClickBindings(b,!0),"orchestrator"===b.type){c[b.id]=b.orchestratorEvents;for(var f=0;f<b.orchestratorEvents.length;f++)-1===d.indexOf(b.orchestratorEvents[f])&&d.push(b.orchestratorEvents[f])}else this._createEvent(b);var g=!!(this.parameters.useRotation&&this.parameters.useRotation[0])&&"true"===this.parameters.useRotation[0];g&&0<this.rotationEvents.length&&this._rotateEvents(),this._orchestratorEvents(d)},_compareArray:function(c,a){if(c.length>a.length)return!1;for(var b=0;b<c.length;b++)if(-1===a.indexOf(c[b]))return!1;return!0},_createEvent:function(a){var b=a.area.selectedoption,c=!1;if("selector"===b&&a.area.selector?a.words&&this._contentMatchesWords(this._getContentForSelector(a),a.containsmatches,a.words)?c=!0:a.anyWord&&this._getContentForSelector(a)&&(c=!0):"variable"===b&&a.area.variable?a.words&&this._contentMatchesWords(this._getVariableValue(a.area.variable),a.containsmatches,a.words)?c=!0:a.anyWord&&this._getVariableValue(a.area.variable)&&(c=!0):"customjs"===b&&a.area.customjs&&(a.words&&this._contentMatchesWords(this._getCustomJsValue(a.area.customjs),a.containsmatches,a.words)?c=!0:a.anyWord&&this._getCustomJsValue(a.area.customjs)&&(c=!0)),c){var d=0;a.delay&&!isNaN(parseInt(a.delay))&&(d=parseInt(a.delay));var e=this.jQuery;setTimeout(e.proxy(function(){this.blueConicClient.createEvent(a.event.id)},this),d)}},_orchestratorEvents:function(a){for(key in a){var b=a[key];this.blueConicClient.event.subscribe(b,this,function(a){for(var b=0;b<this.rules.length;b++){var c=this.rules[b],d=c.orchestratorEvents.filter(function(a){return a&&"string"==typeof a}).map(function(a){return a.toLowerCase()});d&&-1!==d.indexOf(a)&&(this.profileEvents[c.id]=this.profileEvents[c.id]||[],-1===this.profileEvents[c.id].indexOf(a)&&this.profileEvents[c.id].push(a));var e=this.profileEvents[c.id]||[];if(this._compareArray(d,e)){var f=0;c.delay&&!isNaN(parseInt(c.delay))&&(f=parseInt(c.delay)),setTimeout(function(){this.blueConicClient.createEvent(c.event.id)},f),this.profileEvents[c.id]=[]}}"multiplePageviews"===c.multiplePageviews&&(this.profile.setValue(this.orchestratorProperty,this.blueConicClient.json.stringify(this.profileEvents)),this.blueConicClient.profile.updateProfile())})}},_rotateEvents:function(){var a=this.profile.getValue(this.rotationStateProperty),b=null;b=a?this.blueConicClient.json.parse(a):{lastEvent:{},failedEvents:[]};var c=this.parameters.sourceEvent&&this.parameters.sourceEvent[0]?this.parameters.sourceEvent[0]:"PAGEVIEW";"PAGEVIEW"===c?this._doRotation(b):this.blueConicClient.event.subscribe(c,this,function(){this._doRotation(b)})},_doRotation:function(a){var b=this._getCurrentEvent(a);b&&this.blueConicClient.createEvent(b.id,null,this,function(c){0===c.length&&this.skipFailedEvents?(a.failedEvents.push(b.id),this._doRotation(a)):(a.lastEvent.id=b.id,a.lastEvent.dt=this._getTodayInMs(),this.profile.setValue(this.rotationStateProperty,this.blueConicClient.json.stringify(a)),this.blueConicClient.profile.updateProfile())})},_getCurrentEvent:function(a){return a.lastEvent.id?this.skipFailedEvents&&a.failedEvents&&a.failedEvents.length===this.rotationEvents.length?(this.profile.setValue(this.rotationStateProperty,this.blueConicClient.json.stringify(a)),this.blueConicClient.profile.updateProfile(),null):0===this.rotationInterval||this._intervalHasPassed(a.lastEvent.dt)?this._getNextEvent(a.lastEvent,a):null:this.rotationEvents[0].event},_getNextEvent:function(a,b){for(var c=0;c<this.rotationEvents.length;c++)if(this.rotationEvents[c].event.id===a.id){var d=c+1<=this.rotationEvents.length-1?c+1:0;return this.skipFailedEvents&&-1!==b.failedEvents.indexOf(this.rotationEvents[d].event.id)?this._getNextEvent(this.rotationEvents[d].event,b):this.rotationEvents[d].event}},_intervalHasPassed:function(a){var b=24*(60*(60*(1e3*this.rotationInterval)));return!!(a+b<=this._getTodayInMs())},_getTodayInMs:function(){var a=this.blueConicClient.getCurrentDate();return new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime()},_setClickBindings:function(a,b){if(a.clickarea.selector){var c=this.jQuery,d=null;try{d=c(a.clickarea.selector)}catch(a){return void this.blueConicClient.util.log("Invalid click selector: "+a)}0===d.length?this.blueConicClient.position.subscribe(a.clickarea.selector,this,function(){this._setClickBindings(a,!1)}):d.off("click."+a.id).on("click."+a.id,{clickRule:a},this.jQuery.proxy(function(a){this.lastEvent=a;try{this._createEvent(a.data.clickRule)}catch(a){}},this)),b&&c(document).on("click",a.clickarea.selector,{clickRule:a},c.proxy(function(a){if(!this.lastEvent||this.lastEvent.originalEvent!==a.originalEvent)try{this._createEvent(a.data.clickRule)}catch(a){}},this))}},_contentMatchesWords:function(a,b,c){if(!a)return!1;for(var d=0;d<c.length;d++)if("contains"===b){if(-1!==a.indexOf(c[d].toLowerCase()))return!0;}else if(a===c[d].toLowerCase())return!0;return!1},_getContentForSelector:function(rule){var selector=rule.area.selector,contentArea=null;if(-1!==selector.indexOf("jQuery("))contentArea=function(selector,jQuery){return eval("var jQuery = arguments[1]"),eval(selector)}(selector,this.jQuery);else try{contentArea=this.jQuery(selector)}catch(a){this.blueConicClient.util.log("Invalid content selector: "+a)}if(contentArea&&contentArea instanceof this.jQuery&&0<contentArea.length){var contentArr=[];return this.jQuery.each(contentArea,this.jQuery.proxy(function(a,b){var c=this.jQuery(b);c.attr("content")?contentArr.push(this._normalizeText(c.attr("content"))):c.attr("src")?contentArr.push(this._normalizeText(c.attr("src"))):contentArr.push(this._normalizeText(c.text()))},this)),contentArr.join().toLowerCase()}"content"===rule.type&&this.blueConicClient.position.subscribe(selector,this,function(){this._createEvent(rule)})},_getVariableValue:function(a){try{for(var b=a.replace("[",".").replace("]","").replace("\"\"",""),c=b.split("."),d=window[c.shift()];0<c.length;)d=d[c.shift()];return d instanceof Array?d.join().toLowerCase():"object"==typeof d||"function"==typeof d?this._stringify(d):d?(""+d).toLowerCase():null}catch(a){return null}},_getCustomJsValue:function(customjs){try{var value=function(customjs,jQuery,$){return eval("var jQuery = arguments[1]"),eval("var $ = arguments[2]"),eval(customjs)}(customjs,this.jQuery,this.jQuery);return value&&value instanceof Object&&(value=this._stringify(value)),value?(""+value).toLowerCase():null}catch(a){return null}},_stringify:function(a){try{return this.blueConicClient.json.stringify(a)}catch(a){var b=[];return JSON.stringify(obj,function(a,c){if("object"==typeof c&&null!==c){if(-1!==b.indexOf(c))return;b.push(c)}return c})}},_normalizeText:function(a){return a?this.jQuery.trim(a).replace(/\r\n+|\r+|\n+/gi,"").replace(/\s+/gi," "):a}});var a = [];var i='neweventtrigger';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/neweventtrigger/ts_a2d18b59dc2bff36c178faadb9600b87/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({
    init: function(a,b){


        var market_links = {}; 
        var campaign;
        var flag = {};
        if((document.URL.indexOf('houstonchronicle') > -1 || document.URL.indexOf('chron.com') > -1)) {
            flag = {
                enabled: true,
                value: 'ENDS SOON'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    paywallHard: 'https://subscription.houstonchronicle.com/checkout/360/773/?origin=paywall&ipid=hard&variant=aprilflash',
                    footer: 'https://subscription.houstonchronicle.com/checkout/360/773/?origin=toaster&ipid=footer&variant=aprilflash', 
                    inline: 'https://subscription.houstonchronicle.com/checkout/360/773/?origin=inline&variant=aprilflash',  
                };    
            }
            else{
                market_links = {
                    paywallHard: 'https://subscription.houstonchronicle.com/checkout/360/773/?origin=paywall&ipid=hard&variant=aprilflash',
                    footer: 'https://subscription.houstonchronicle.com/checkout/360/773/?origin=toaster&ipid=footer&variant=aprilflash', 
                    inline: 'https://subscription.houstonchronicle.com/checkout/360/773/?origin=inline&variant=aprilflash', 
                }; 
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                //turn all subscription. links into QA links 
            }
            var testGroup = window.blueConicClient.profile.getProfile().getValue('testgroup');
            if((parseInt(testGroup) % 2 == 0)) {
                HDN.dataLayer.bc_abtest = {};
                HDN.dataLayer.bc_abtest.experimentId = ['hcAbondonmentApr2021_C'];
            }
            else if ((parseInt(testGroup) % 2 == 1)) {
                HDN.dataLayer.bc_abtest = {};
                HDN.dataLayer.bc_abtest.experimentId = ['hcAbondonmentApr2021_V1'];
            }
        }

        else if(document.URL.indexOf('expressnews.com') > -1 || document.URL.indexOf('mysanantonio.com') > -1) {
            flag = {
                enabled: true,
                value: 'ENDS SOON'
            }            
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.expressnews.com/checkout/373/790/?origin=paywall&variant=aprilflash',
                    paywallHard: 'https://subscription.expressnews.com/checkout/373/790/?origin=paywall&ipid=hard&variant=aprilflash',
                    button: 'https://subscription.expressnews.com/checkout/373/790/?origin=button&variant=aprilflash',
                    inline: 'https://subscription.expressnews.com/checkout/373/790/?origin=inline&variant=aprilflash',
                    footer: 'https://subscription.expressnews.com/checkout/373/790/?origin=toaster&ipid=footer&variant=aprilflash'
                };    
            }
            else {
                market_links = {
                    paywall: 'https://subscription.expressnews.com/checkout/373/790/?origin=paywall&variant=aprilflash',
                    paywallHard: 'https://subscription.expressnews.com/checkout/373/790/?origin=paywall&ipid=hard&variant=aprilflash',
                    button: 'https://subscription.expressnews.com/checkout/373/790/?origin=button&variant=aprilflash',
                    inline: 'https://subscription.expressnews.com/checkout/373/790/?origin=inline&variant=aprilflash',
                    footer: 'https://subscription.expressnews.com/checkout/373/790/?origin=toaster&ipid=footer&variant=aprilflash'
                }
            }
        }
        else if(document.URL.indexOf('sfchronicle.com') > -1) {
            campaign = 'aprilflash';
            flag = {
                enabled: true,
                value: 'ENDS SOON'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    button: 'https://subscription.sfchronicle.com/checkout/476/927/?siteID=SFC&origin=button&variant=aprilflash',
                    inline: 'https://subscription.sfchronicle.com/checkout/476/927/?siteID=SFC&origin=inline&variant=aprilflash',
                    footer: 'https://subscription.sfchronicle.com/checkout/476/927/?siteID=SFC&origin=toaster&ipid=footer&variant=aprilflash',
                    paywall: 'https://subscription.sfchronicle.com/checkout/476/927/?siteID=SFC&origin=paywall&variant=aprilflash',
                    paywallHard: 'https://subscription.sfchronicle.com/checkout/476/927/?siteID=SFC&origin=paywall&ipid=hard&variant=aprilflash'
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    button: 'https://subscription.sfchronicle.com/checkout/476/927/?siteID=SFC&origin=button&variant=aprilflash',
                    inline: 'https://subscription.sfchronicle.com/checkout/476/927/?siteID=SFC&origin=inline&variant=aprilflash',
                    footer: 'https://subscription.sfchronicle.com/checkout/476/927/?siteID=SFC&origin=toaster&ipid=footer&variant=aprilflash',
                    paywall: 'https://subscription.sfchronicle.com/checkout/476/927/?siteID=SFC&origin=paywall&variant=aprilflash',
                    paywallHard: 'https://subscription.sfchronicle.com/checkout/476/927/?siteID=SFC&origin=paywall&ipid=hard&variant=aprilflash'
                }
            }
        }
        else if(document.URL.indexOf('timesunion.com') > -1) {
            campaign = 'aprilflash';
            flag = {
                enabled: true,
                value: 'ENDS SOON'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.timesunion.com/checkout/416/850/?origin=paywall&variant=aprilflash',
                    paywallHard: "https://subscription.timesunion.com/checkout/416/850/?origin=paywall&ipid=hard&variant=aprilflash",
                    button: 'https://subscription.timesunion.com/checkout/416/850/?origin=button&variant=aprilflash',
                    masthead: "https://subscription.timesunion.com/checkout/416/850/?origin=header&variant=aprilflash",
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.timesunion.com/checkout/416/850/?origin=paywall&variant=aprilflash',
                    paywallHard: "https://subscription.timesunion.com/checkout/416/850/?origin=paywall&ipid=hard&variant=aprilflash",
                    button: 'https://subscription.timesunion.com/checkout/416/850/?origin=button&variant=aprilflash',
                    masthead: "https://subscription.timesunion.com/checkout/416/850/?origin=header&variant=aprilflash",
                }
            }

            //populate test group ID 
            // var testGroup = window.blueConicClient.profile.getProfile().getValue('testgroup');
            // if((parseInt(testGroup) % 2 == 0)) {
            //     HDN.dataLayer.abtest = {};
            //     HDN.dataLayer.abtest.experimentId = ['atuMeterJan2020_C'];
            // }
            // else if ((parseInt(testGroup) % 2 == 1)) {
            //     HDN.dataLayer.abtest = {};
            //     HDN.dataLayer.abtest.experimentId = ['atuMeterJan2020_V1'];
            // }
        }
        else if(document.URL.indexOf('ctpost') > -1) {
            campaign = 'aprilflash';
            flag = {
                enabled: true,
                value: 'ENDS SOON'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/403/839?siteid=CT_PO&origin=paywall&variant=aprilflash',
                    button: 'https://subscription.hearstmediact.com/checkout/403/839?siteid=CT_PO&origin=button&variant=aprilflash',
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/403/839?siteid=CT_PO&origin=paywall&variant=aprilflash',
                    button: 'https://subscription.hearstmediact.com/checkout/403/839?siteid=CT_PO&origin=button&variant=aprilflash',
                }
            }
        }
        else if(document.URL.indexOf('newstimes') > -1) {
            campaign = 'aprilflash';
            flag = {
                enabled: true,
                value: 'ENDS SOON'
            }
            if(document.URL.indexOf('cmf.qa') > -1){

                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/401/838?siteid=CT_NT&origin=paywall&variant=aprilflash',
                    button: 'https://subscription.hearstmediact.com/checkout/401/838?siteid=CT_NT&origin=button&variant=aprilflash',
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/401/838?siteid=CT_NT&origin=paywall&variant=aprilflash',
                    button: 'https://subscription.hearstmediact.com/checkout/401/838?siteid=CT_NT&origin=button&variant=aprilflash',
                }
            }
        }
        else if(document.URL.indexOf('stamfordadvocate') > -1) {
            campaign = 'aprilflash';
            flag = {
                enabled: true,
                value: 'ENDS SOON'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/397/836?siteid=CT_HR&origin=paywall&variant=aprilflash',
                    button: 'https://subscription.hearstmediact.com/checkout/397/836?siteid=CT_HR&origin=button&variant=aprilflash',
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/397/836?siteid=CT_HR&origin=paywall&variant=aprilflash',
                    button: 'https://subscription.hearstmediact.com/checkout/397/836?siteid=CT_HR&origin=button&variant=aprilflash',
                }
            }
        }
        else if(document.URL.indexOf('greenwichtime') > -1) {
            campaign = 'aprilflash';
            flag = {
                enabled: true,
                value: 'ENDS SOON'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/395/835?siteid=CT_GT&origin=paywall&variant=aprilflash',
                    button: 'https://subscription.hearstmediact.com/checkout/395/835?siteid=CT_GT&origin=button&variant=aprilflash',
                    
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/395/835?siteid=CT_GT&origin=paywall&variant=aprilflash',
                    button: 'https://subscription.hearstmediact.com/checkout/395/835?siteid=CT_GT&origin=button&variant=aprilflash',
                }
            }
        }
        else if(document.URL.indexOf('thehour') > -1) {
            campaign = 'aprilflash';
            flag = {
                enabled: true,
                value: 'ENDS SOON'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/397/836?siteid=CT_HR&origin=paywall&variant=aprilflash',
                    button: 'https://subscription.hearstmediact.com/checkout/397/836?siteid=CT_HR&origin=button&variant=aprilflash',
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/397/836?siteid=CT_HR&origin=paywall&variant=aprilflash',
                    button: 'https://subscription.hearstmediact.com/checkout/397/836?siteid=CT_HR&origin=button&variant=aprilflash',
                }
            }
        }
        else if(document.URL.indexOf('nhregister') > -1) {
            campaign = 'aprilflash';
            flag = {
                enabled: true,
                value: 'ENDS SOON'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/399/837?siteid=CT_NHR&origin=paywall&variant=aprilflash',
                    button: 'https://subscription.hearstmediact.com/checkout/399/837?siteid=CT_NHR&origin=button&variant=aprilflash',
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/399/837?siteid=CT_NHR&origin=paywall&variant=aprilflash',
                    button: 'https://subscription.hearstmediact.com/checkout/399/837?siteid=CT_NHR&origin=button&variant=aprilflash',
                }
            }
        }
        //set the links in the HDN
        window.HDN.dataLayer.offerLinks = market_links;
        window.HDN.dataLayer.campaignCode = campaign;
        window.HDN.dataLayer.offerFlag = flag;
        //window.HDN.dataLayer.standardOfferLinks = standard_offer_links;
    }
});var a = [];var i='sub_links';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/sub_links/ts_c988e8a65827c086d8c62366206069db/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({open:!1,data:{},nrOfTries:0,closeButtonWidth:10,borderWidth:1,BASE_CSS_ID_PREFIX:"bcBaseStyle_",INLINE_CSS_ID_PREFIX:"bcInlineStyle_",EXTERNAL_CSS_ID_PREFIX:"bcExternalStyle_",html:{nl:{content:"<p>Inhoud</p>"},"default":{content:"<p>Content</p>"}},init:function(e,t){this.blueConicClient=e,this.context=t,this.parameters=this.context.getParameters(),this._variantId=this.context.getInteractionId(),this._viewEventThrown=!1,this._manuallyClosed=!1,this.baseURL=this.blueConicClient.getBaseURL(this.context.getInteractionTypeId())+"frontend/src/",this.customCssUrls=[],this.customJsUrls=[],this.inlineCss=null,this.inlineJs=null,this._timestamp=null,this._observer=null,this._eventListenerFunction=null,this.isInEditMode=this.blueConicClient.isInEditMode(),this.clickTrigger=!1,this.blueConicClient._renderedInteractions=this.blueConicClient._renderedInteractions||[],this.blueConicClient.event.subscribe(this.blueConicClient.event.onUrlChange,this,(function(){if(this.open){this._getToasterNode().remove(),this._removeToasterStyling();var e=this.blueConicClient.util.array.indexOfArray(this.blueConicClient._renderedInteractions,this.context.getInteractionId());this.blueConicClient._renderedInteractions.splice(e,1),this.open=!1}}))},getPreloadProperties:function(){for(var e,t=this.context.getParameters().content+"",i=/data-bc-preload="([^"]*)"/g,s=[];null!==(e=i.exec(t));)for(var o=e[1].split(","),n=0;n<o.length;n++)s.push(o[n]);return s||[]},onMessageReceived:function(e){this.blueConicClient.event.publish("toaster.messageReceived",e)},onSave:function(){return this._getNodeWithinToaster(".bcToasterContent").html()},onLoad:function(e){"function"!=typeof e&&(e=function(){}),window.bc=window.bc||{},window.bc.jQuery=this.jQuery,window.bc.$=this.jQuery;var t=this,i=this.jQuery,s=this.getParameter("content"),o=s&&-1!==s.indexOf("bcToasterTemplate")?"_clean":"",n=this.getParameter("version"),r="";r=o||"3"!==n?"css/toaster"+o:"css/toaster_v3",r+=".css";var a=i('<link type="text/css" id="'+this.BASE_CSS_ID_PREFIX+this._variantId+'" href="'+this.baseURL+r+'" rel="stylesheet" />'),c=this.getParameter("template");this.template=c,a.on("load",(function(){t.handleStyling(t.getParameter("close_icon"),t.getParameter("close_icon_hover"),(function(i){if(i&&(console.error(i.message),!t.isInEditMode))return t._removeUrls(),e(i.message);t.handleJavascript((function(i){return i&&(console.error(i.message),!t.isInEditMode)?(t._removeUrls(),e(i.message)):(t.loadToaster(),e())}))}))})),i("head").append(a)},loadToaster:function(){var e=this.context.getParameters(),t=this.jQuery;if(!this._getToasterNode().hasClass("bcToasterOpen")){this._getToasterNode().length&&this._getToasterNode().remove();var i=this.getParameter("close_icon");i&&(this._closeIcon=i);var s=this.getParameter("close_icon_hover");s&&(this._closeIconHover=s);var o=this;if(this._addContent(e,t),this._getNodeWithinToaster(".bcClose").click((function(){o._manuallyClosed=!0,o._hideToaster()})),this.emptyElementsWithAttribute(this._getToasterNode().get(0),"div","data-bc-external"),this.handleComplexElements(this._getToasterNode().get(0)),this.positionDivs(),this.isInEditMode)o._showToaster();else{var n=[],r=0,a=this.getParameter("triggerWhen");a?(r=100,n.push(this._convertWhenSettingPreviousToasterVersion(a))):(n=e.selected_when&&0!==e.selected_when.length?e.selected_when:["onPageLoad"],r=e.scroll_depth&&e.scroll_depth[0]&&!isNaN(e.scroll_depth[0])?parseInt(e.scroll_depth[0]):0);for(var c=this.getParameter("click_selector"),h=this.getParameter("content_condition"),l=0;l<n.length;l++)switch(n[l]){case"click_selector":this._addClickTriggerBindings(c);break;case"content_condition":this._addContentPolling(h);break;case"scroll_depth":this._addScrollBinding(r);break;case"triggerOn":this._addScrollOn(o);break;default:o._checkDelayBeforeTrigger()}this._setupFrontEndBindings()}}},_setupFrontEndBindings:function(){var e=this.jQuery(".bcToasterDontShowAgainLink"),t=this.jQuery(".bcToasterCloseButton");e.length>0&&e.off("click.dontShowAgainLinks").on("click.dontShowAgainLinks",this.jQuery.proxy((function(e){e.preventDefault(),this.blueConicClient.doNotShowAgain(this.context.getInteractionId()),this._hideToaster()}),this)),t.length>0&&t.off("click.closeButtons").on("click.closeButtons",this.jQuery.proxy((function(){this._hideToaster()}),this)),this._addCloseEventHandler()},_convertWhenSettingPreviousToasterVersion:function(e){switch(e){case"scroll":return"triggerOn";case"reachedBottom":return"scroll_depth";default:return"onPageLoad"}},_addCloseEventHandler:function(){this.blueConicClient.event.subscribe("closeoverlay",this,(function(e,t){t instanceof Array&&t[0]===this.context.getInteractionId()&&this._hideToaster()}))},_addScrollOn:function(e){(0,this.jQuery)(window).scroll((function(){e._checkDelayBeforeTrigger()}))},_checkScrollCondition:function(e){this.jQuery(window).scrollTop()/(this.jQuery(document).height()-window.innerHeight)*100>=e&&this._checkDelayBeforeTrigger()},_addScrollBinding:function(e){this._checkScrollCondition(e),this.jQuery(window).scroll(this.jQuery.proxy((function(){this._checkScrollCondition(e)}),this))},_addClickTriggerBindings:function(e){try{var t=this.jQuery(e);this.clickTrigger=!0,t.length>0?t.off("click.toaster").on("click.toaster",this.jQuery.proxy((function(){this._getToasterNode().get(0)?this._checkDelayBeforeTrigger(!0):this.open||this._setupToasterBeforeToShow()}),this)):this.blueConicClient.position.subscribe(e,this,this.jQuery.proxy(this._addClickTriggerBindings,this,e))}catch(i){}},_setupToasterBeforeToShow:function(){this.handleStyling(this.getParameter("close_icon"),this.getParameter("close_icon_hover"),(function(){})),this.handleJavascript((function(){})),this._addContent(null,this.jQuery);var e=this;this._getNodeWithinToaster(".bcClose").click((function(){e._hideToaster()})),this.clickTrigger=!0,this._checkDelayBeforeTrigger()},_getNodeWithinToaster:function(e){return this.jQuery("#"+this._variantId+" "+e)},_getToasterNode:function(){return this.jQuery("#"+this._variantId)},_addContentPolling:function(e){this._checkContentCondition(e);var t=this,i=document.getElementsByTagName("body")[0];if(window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver)this._observer=new MutationObserver((function(){t._observeContentChanges(e)})),this._observer.observe(i,{childList:!0,subtree:!0});else if(window.addEventListener)this._eventListenerFunction=function(){t._observeContentChanges(e)},i.addEventListener("DOMNodeInserted",this._eventListenerFunction,!1);else var s=setInterval((function(){t.open?clearInterval(s):t._checkContentCondition(e)}),500)},_observeContentChanges:function(e){if(this.open){this._observer?this._observer.disconnect():document.getElementsByTagName("body")[0].removeEventListener("DOMNodeInserted",this._eventListenerFunction,!1)}else{var t=this,i=(new Date).getTime();this._timestamp=i,setTimeout((function(){t._timestamp!==i||t.open||t._checkContentCondition(e)}),250)}},_checkContentCondition:function(e){this.jQuery(e).length>0&&this.jQuery(e).html()&&this.jQuery(e).html().length>0&&this._checkDelayBeforeTrigger()},_addContent:function(e,t){var i=this.getParameter("content");if(i&&-1!==i.indexOf("<body></body>")&&(i=""),!i){var s="nl"===this.context.getLocale()?"nl":"default";i=this.html[s].content}var o=t(i=this.template?'<div class="bcToaster" id="'+this._variantId+'" style="visibility:hidden;"><div class="bcCloseWrapper"><div class="bcClose"><div></div></div></div><div class="bcToasterContent bcTemplateContent">'+i+"</div></div>":'<div class="bcToaster" id="'+this._variantId+'" style="visibility:hidden;"><div class="bcCloseWrapper"><div class="bcClose"><div></div></div></div><div class="bcToasterContent">'+i+"</div></div>"),n=this.getParameter("close_icon");"true"===this.getParameter("custom_close")&&n?o.removeClass("bcDefaultClose"):o.addClass("bcDefaultClose");try{o.appendTo(t("body"))}catch(r){this.isInEditMode&&console.error("Error caught: "+r)}},handleComplexElements:function(e){for(var t=this.getElementsWithAttribute(e,"div","data-bc-pluginid"),i=0;i<t.length;i++){var s=t[i],o=s.getAttribute("data-bc-pluginid"),n=s.getAttribute("data-bc-config");if(n)try{var r=n.replace(/\n/g,"\\\\n").replace(/\r/g,"\\\\r").replace(/\t/g,"\\\\t");n=this.blueConicClient.json.parse(r)}catch(a){n=null}this.blueConicClient.event.publish("bcComplexObject",{plugin:o,config:n,node:s,interactionId:this.context.getInteractionId()}),this.isInEditMode||(s.removeAttribute("data-bc-pluginid"),s.removeAttribute("data-bc-config"))}},emptyElementsWithAttribute:function(e,t,i){for(var s=this.getElementsWithAttribute(e,t,i),o=0,n=s.length;o<n;o++){s[o].innerHTML=""}},getElementsWithAttribute:function(e,t,i){for(var s=[],o=e.getElementsByTagName(t),n=0,r=o.length;n<r;n++){var a=o[n];a.getAttribute(i)&&s.push(a)}return s},_positionFromPerpendicularEdge:function(){this.jQuery;var e=this.getParameter("location")||"right",t=this.getParameter("pixelsFrom")?this.getParameter("pixelsFrom"):"",i=this.getParameter("locationFrom")?this.getParameter("locationFrom"):"left_or_top";if(this.getParameter("locationFrom")||this.getParameter("version")||(i="right_or_bottom"),t||0===t){var s="left"===e||"right"===e?"left_or_top"===i?"top":"bottom":"left_or_top"===i?"left":"right";this._getToasterNode().css(s,t+"px"),this._getToasterNode().css(e,0)}else{var o=this._getNodeWithinToaster(".bcToasterContent").get(0).getBoundingClientRect();if("left"===e||"right"===e){var n=window.innerHeight||document.documentElement.clientHeight,r=o.height||o.bottom-o.top;this._getToasterNode().css("top",Math.max((n-r)/2,0)+"px"),this._getToasterNode().css("left"===e?"left":"right",0)}else{var a=window.innerWidth||document.documentElement.clientWidth,c=o.width||o.right-o.left;this._getToasterNode().css("left",Math.max((a-c)/2,0)+"px"),this._getToasterNode().css("top"===e?"top":"bottom",0)}}},positionDivs:function(){var e=this.jQuery,t=this.getParameter("location")||"right",i=this._getShowClose();this._positionFromPerpendicularEdge(),"left"===t?this._getToasterNode().removeClass("bcRight").removeClass("bcTop").removeClass("bcBottom").addClass("bcLeft"):"right"===t?this._getToasterNode().removeClass("bcLeft").removeClass("bcTop").removeClass("bcBottom").addClass("bcRight"):"top"===t?(this._getNodeWithinToaster(".bcToasterContent").after(e(".bcToaster .bcCloseWrapper")),this._getToasterNode().removeClass("bcRight").removeClass("bcBottom").removeClass("bcLeft").addClass("bcTop")):this._getToasterNode().removeClass("bcRight").removeClass("bcTop").removeClass("bcLeft").addClass("bcBottom"),i?this._getToasterNode().addClass("bcShowClose"):this._getToasterNode().removeClass("bcShowClose")},handleStyling:function(e,t,i){var s=this.jQuery,o="",n=[];if(this._getShowClose()?this._getToasterNode().addClass("bcShowClose"):this._getToasterNode().removeClass("bcShowClose"),"true"===this.getParameter("custom_close")&&e){this._getToasterNode().removeClass("bcDefaultClose"),o+=".bcToaster .bcClose > div { background-image: none;}";var r=".bcToaster .bcClose {background-image: url('"+e+"');background-repeat: no-repeat;background-color: transparent;",a=".bcToaster .bcClose:hover {background-image: url('"+t+"');";"3"===this.getParameter("version")?(o+=r+"background-position: center center;background-size: contain;}",t&&(o+=a+"}")):(o+=r+"}",t?o+=a+"background-position: 0px 0px;}":s(".bcToaster .bcClose:hover").css("background-position",""))}else this._getToasterNode().addClass("bcDefaultClose");var c=this.getParameter("close_position"),h=this.getParameter("close_padding");o+=this._addClosePositionStyling(c,h);var l=this.getParameter("styling_css");l&&(this.stylingUrl=l,this.customCssUrls.push(l),n.push(l));var d=this.getParameter("styling_css_inline");d&&(o+=d.replace(/&#xd;/gi,"")),o&&(this.inlineCss=s("<style id='"+this.INLINE_CSS_ID_PREFIX+this._variantId+"'>"+o+"</style>"),this.inlineCss.appendTo(s("head"))),this._loadCss(n,i)},_loadCss:function(e,t){var i=(e=e||[]).length,s=0,o=[];if(this.errorList=null,void 0===t&&(t=function(){}),0===i)return t();function urlLoaded(e){if(++s>=i)return o.length>0?t({message:"Error occured when loading the file "+e,error:o}):t()}e.forEach((function(e){if(document.querySelector('link[href="'+e+'"]'))urlLoaded();else{var t=document.createElement("link");t.setAttribute("href",e),t.setAttribute("rel","stylesheet"),t.setAttribute("type","text/css"),t.onload=urlLoaded,t.onerror=function(t){o.push(t),urlLoaded(e)},document.head.appendChild(t)}}))},_loadJs:function(e,t){var i=(e=e||[]).length,s=0,o=[];if(this.errorList=null,void 0===t&&(t=function(){}),0===i)return t();function urlLoaded(e){if(++s>=i)return o.length>0?t({message:"Error occured when loading the file "+e,error:o}):t()}e.forEach((function(e){if(document.querySelector('script[src="'+e+'"]'))urlLoaded();else{var t=document.createElement("script");t.setAttribute("src",e),t.setAttribute("type","text/javascript"),t.onload=urlLoaded,t.onerror=function(t){o.push(t),urlLoaded(e)},document.head.appendChild(t)}}))},_removeUrls:function(){this.customCssUrls.forEach((function(e){e&&document.querySelector('link[href="'+e+'"]').remove()})),this.customJsUrls.forEach((function(e){e&&document.querySelector('script[src="'+e+'"]').remove()}))},handleJavascript:function(e){var t=this.getParameters("javascript_urls");this.customJsUrls=t,null===this.customJsUrls&&(this.customJsUrls=[]),this._loadJs(this.customJsUrls,e)},_getShowClose:function(){var e=!1,t=this.getParameter("show_close");return"true"===t||"false"===t||!0===t||!1===t?"true"===t||!0===t:(e=!!this.getParameter("close")&&"showClose"===this.getParameter("close"),this.getParameter("showClose")&&(e=!0),e)},_hideToaster:function(){if(!this.isInEditMode){var e=this.blueConicClient.util.array.indexOfArray(this.blueConicClient._renderedInteractions,this.context.getInteractionId());this.blueConicClient._renderedInteractions.splice(e,1);var t="true"===this.getParameter("hide_after_close"),i=(this.jQuery,this._getNodeWithinToaster(".bcToasterContent").get(0).getBoundingClientRect()),s=this.getParameter("location")||"right",o=this._getShowClose(),n="left"===s||"right"===s?i.width:i.height;this._setToasterEffect(!0,o,n),t&&this.blueConicClient.doNotShowAgain(this.context.getInteractionId()),window.setTimeout(function(){this._removeToasterStyling(),this._getToasterNode().removeClass("bcToasterOpen"),this.clickTrigger&&(this.open=!1)}.bind(this),501)}},_removeToasterStyling:function(){this._getBaseCssReference().remove(),this._getInlineCssReference().remove(),this._externalStylesheetReference&&this._externalStylesheetReference.remove()},_getBaseCssReference:function(){return this.jQuery("#"+this.BASE_CSS_ID_PREFIX+this._variantId)},_getInlineCssReference:function(){return this.jQuery("#"+this.INLINE_CSS_ID_PREFIX+this._variantId)},_checkDelayBeforeTrigger:function(e){var t=this.context.getParameters(),i=t.delay&&t.delay[0]&&!isNaN(t.delay[0])?1e3*parseInt(t.delay[0]):0;i>0?window.setTimeout(this.jQuery.proxy((function(){this._showToaster(e)}),this),i):this._showToaster(e)},_showToaster:function(e){var t=this,i=this.jQuery;if(!this._manuallyClosed||this.isInEditMode||e){if(0===this._getNodeWithinToaster(".bcToasterContent").width()&&!e){if(this.nrOfTries>10)return;return this.nrOfTries++,void setTimeout((function(){t._showToaster(e)}),500)}if(!this.open){if(-1!==this.blueConicClient.util.array.indexOfArray(this.blueConicClient._renderedInteractions,this.context.getInteractionId()))return;this.blueConicClient._renderedInteractions.push(this.context.getInteractionId()),this.isInEditMode||this._viewEventThrown||(this._viewEventThrown=!0,this.blueConicClient.createEvent("VIEW",this.context.getInteractionId()));var s=this._getShowClose();this.positionDivs(),this._getToasterNode().css("visibility","visible"),this._getToasterNode().css("display","block"),this._getToasterNode().addClass("bcToasterOpen"),i(window).resize(i.proxy((function(){this.positionDivs()}),this));var o=this.getParameter("click_event_selector");if(o){this.jQuery("body").one("click",o,this.jQuery.proxy((function(e){this.lastClickEvent&&this.lastClickEvent.originalEvent===e.originalEvent||this._logClickEvent(e)}),this));try{this.jQuery(o).one("click",this.jQuery.proxy((function(e){this.lastClickEvent=e,this._logClickEvent(e)}),this))}catch(a){}}this._setToasterEffect(!1,s);var n=t.getParameter("javascript");if(this.inlineJs=n,n&&!t.isInEditMode){n=n.replace(/(^|\W)blueConicVariantId(\W|$)/g,'$1"'+t.context.getInteractionId()+'"$2');var r=t.jQuery("<script>"+n+"<\/script>");try{r.appendTo(t.jQuery("body"))}catch(c){console.error(c)}}this.open=!0,this.isInEditMode&&this.blueConicClient.event.publish("toaster.interactionLoaded",{interaction:this})}}},_logClickEvent:function(e){e&&e.originalEvent&&e.originalEvent._blueConicLoggedClickEvent===this.context.getInteractionId()||(e&&e.target&&e.target.pathname&&e.target.hostname&&0===e.target.pathname.indexOf("/s/")&&-1!==e.target.hostname.indexOf("blueconic")||(e.originalEvent&&(e.originalEvent._blueConicLoggedClickEvent=this.context.getInteractionId()),this.blueConicClient.createEvent("CLICK",this.context.getInteractionId())))},_setToasterEffect:function(e,t,i){this.jQuery;var s={},o=this.getParameter("location")||"right",n=t?this.closeButtonWidth+this.borderWidth:this.borderWidth,r=this.getParameter("effect");r||this.getParameter("version")||(r="slideIn");var a=this.getParameter("effect_slide_direction")||"left";s[o]="-"+(i+n)+"px";var c=r+"_"+a===this._effect;this.isInEditMode&&c&&(r="noEffect");var h=this;if(r&&"noEffect"!==r)if("fadeIn"!==r||e)if("fadeIn"===r&&e)this._getToasterNode().fadeOut(500);else if("slideIn"!==r||e)"slideIn"===r&&e&&this._getToasterNode().animate(s,500,(function(){h._getToasterNode().css("display","none")}));else{s[o]="0px";var l=this._getNodeWithinToaster(".bcToasterContent").get(0).getBoundingClientRect(),d="left"===o||"right"===o?l.width:l.height;this._getToasterNode().css(o,"-"+(d+n)+"px"),this._getToasterNode().animate(s,500,(function(){h._getToasterNode().addClass("bcToasterOpen")}))}else this._getToasterNode().hide(),this._getToasterNode().fadeIn(500,(function(){h._getToasterNode().addClass("bcToasterOpen")}));else e&&this._getToasterNode().css("display","none")},_addClosePositionStyling:function(e,t){var i="3"===this.getParameter("version");if(!e||!i)return"";null!==t&&"NaN"!==t||(t="5");var s=".bcToaster .bcClose {";switch(e){case"TOP_LEFT":s+="top:"+t+"px; right: unset; bottom: unset; left:"+t+"px;";break;case"BOTTOM_RIGHT":s+="top: unset; right: "+t+"px; bottom: "+t+"px; left: unset;";break;default:s+="top: "+t+"px; right: "+t+"px; bottom: unset; left: unset;"}return s+"}"},getParameter:function(e){return this.parameters[e]&&this.parameters[e][0]?this.parameters[e][0]:null},getParameters:function(e){return this.parameters[e]||null}});var a = [];var i='toaster';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.0.2/'},{ id : 'html', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'html/1.0.10/'},{ id : 'image', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'image/1.0.2/'},{ id : 'number', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'number/1.0.2/'},{ id : 'string', baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + 'string/1.0.1/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({fallbackLabels:{article:{noStore:{nl:{name:"Titel van het artikel (Bron nog niet geselecteerd)",description:"Beschrijving van het artikel (Bron nog niet geselecteerd)"},"default":{name:"Title of the article (source not yet selected)",description:"Description of the article (source not yet selected)"}},noItems:{nl:{name:"Titel van het artikel (aanbevolen artikelen nog niet beschikbaar)",description:"Beschrijving van het artikel (aanbevolen artikelen nog niet beschikbaar)"},"default":{name:"Title of the article (recommended articles not yet available)",description:"Description of the article (recommended articles not yet available)"}}},product:{noStore:{nl:{name:"Titel van het product (Bron nog niet geselecteerd)",description:"Beschrijving van het product (Bron nog niet geselecteerd)"},"default":{name:"Title of the product (source not yet selected)",description:"Description of the product (source not yet selected)"}},noItems:{nl:{name:"Titel van het product (aanbevolen producten nog niet beschikbaar)",description:"Beschrijving van het product (aanbevolen producten nog niet beschikbaar)"},"default":{name:"Title of the product (recommended products not yet available)",description:"Description of the product (recommended products not yet available)"}}}},init:function(e,t){this.blueConicClient=e,this.profile=e.profile.getProfile(),this._templatesLoaded=[],this.baseURL=this.blueConicClient.getBaseURL(t.getInteractionTypeId()),this.context=t,this.locale=t.getLocale(),this.pluginId=t.getInteractionTypeId();var i=this;this.blueConicClient.event.subscribe("bcComplexObject",this,(function(e,t){t&&t.plugin===i.pluginId&&(t.config.interactionId=t.interactionId,this.blueConicClient.isInEditMode()||(t.config.id=(new Date).getTime()+Math.round(1e3*Math.random())),this.type="toolbar_content_recommendations"===t.plugin?"article":"product",i._setUniqueId(t.node,t.config.id),i._applyTemplate(t))})),this.blueConicClient.isInEditMode()&&this._subscribeEditModeEvents()},_subscribeEditModeEvents:function(){this.blueConicClient.event.subscribe("recommendations.updateTemplate",this,(function(e,t){if(t.message.pluginId===this.pluginId){var i=this._createTemplateObject(t.message.template);this._addTemplateToCache(i),this._applyTemplate({update:!0})}})),this.blueConicClient.event.subscribe("recommendations.updateConfig",this,(function(e,t){if(t.message.pluginId===this.pluginId){var i=this._migration(t.message.config);(i=i||{}).settings=i.settings||{};var n=this._getProperties(i);i["data-bc-template-id"]=i.settings.templateId||"";var a='[data-bc-pluginid="'+this.pluginId+'"][data-bc-config*="'+i.id+'"]';if(document.querySelector(a).setAttribute("data-bc-config",JSON.stringify(i)),n.length>0)document.querySelector(a).setAttribute("data-bc-preload",n.join(","));var r=document.querySelector(".bcComplexObject"+i.id);if(this.profile.loadValues(n,this,(function(){this._applyTemplate({config:i,node:r})})),window.CKEDITOR&&window.CKEDITOR.instances&&Object.keys(window.CKEDITOR.instances).length>0)window.CKEDITOR.instances[Object.keys(window.CKEDITOR.instances)[0]].fire("change")}})),this.blueConicClient.event.subscribe("editorClosed",this,(function(){this._sendMessage("recommendations.closeConfigurator")}))},_getProperties:function(e){return e&&e.rules?e.rules.reduce((function(e,t){return t&&t.metaDataFilters&&(e=e.concat(Array.prototype.map.call(Array.prototype.filter.call(t.metaDataFilters,(function(e){return e.property})),(function(e){return e.property})))),e}),[]):[]},_setUniqueId:function(e,t){if(e&&t){var i="bcComplexObject"+t;e.className=[e.className,i].join(" ")}},_applyTemplate:function(e){var t=this._migration(e.config);(t=t||{}).settings=t.settings||{};var i=t.settings.templateId;if(i){var n=".bcComplexObject"+t.id;document.querySelector(n).innerHTML="";var a=this;this._loadTemplate(i,(function(t){e.update||a._loadHTML(e,t)}))}},_getLabelObject:function(e){return"nl"===this.locale?this.fallbackLabels[this.type][e].nl:this.fallbackLabels[this.type][e]["default"]},_getFallbackData:function(e,t){for(var i=this._getLabelObject(e),n=[],a=0;a<t;a++)n.push({name:[i.name],description:[i.description],image:[this.baseURL+"frontend/src/node_modules/@blueconic/frontend-recommendations-rendering/images/fallback600x600.png?"]});return n},_initMetaDataService:function(e){var t=null;if(e){var i=this.context.getConnection(e);if(i){var n=i.getParameters().metadata;t=n?this.blueConicClient.json.parse(n):null}}this._metaDataService=new window.BlueConicMetaDataService(this.jQuery,t,this.type),this._metaDataService.blueConicClient=this.blueConicClient},_getItems:function(e){var t=this.jQuery;this._initMetaDataService(e.settings.connectionId||e["data-bc-connection-id"]);var i=t.Deferred(),n=this._getCount(e),a=this._getQueryStringParametersForRecommendations(e);return a.storeId?this.blueConicClient.recommendation.getRecommendations(a,function(e){var t=e.getItems();(t=t.slice(0,n))&&0!==t.length||!this.blueConicClient.isInEditMode()?i.resolve(t):i.resolve(this._getFallbackData("noItems",n))}.bind(this)):i.resolve(this._getFallbackData("noStore",n)),i},_loadHTML:function(e,t){if(t){var i=e.node,n=this._migration(e.config);this._handleStyling(n,t);var a=this._getWidthClass(i),r=document.createElement("div");return r.className=a,r.setAttribute("data-bc-external","true"),r.setAttribute("data-bc-id",n.id),this._getItems(n).then(function(e){return this._handleItems(e,n,t,r)}.bind(this))}},_handleItems:function(e,t,i,n){if(0!==e.length){var a=this._getDataObject(e,t.interactionId);this._renderTemplate(a,i,n);var r=this._addItemNodes(n,e,t);r&&r.appendChild(n),this.blueConicClient.isInEditMode()||this._bindClicks(n,e[0].recommendationId,t),this._addImageErrorHandler(n,t),this._addJavaScript(i);var s=document.querySelector(".bcComplexObject"+t.id);this._addOnResizeHandler(s,n)}else for(var o=document.querySelector(".bcComplexObject"+t.id);o.firstChild;)o.removeChild(n.firstChild)},_renderTemplate:function(e,t,i){if(e&&t&&window.Mustache){for(var n=t.getHtml().replace(/<img\s+src=(['"]{{image}}['"])/,"<img data-bc-src=$1"),a=window.Mustache.to_html(n,e);i.firstChild;)i.removeChild(i.firstChild);var r=document.createElement("div");r.innerHTML=a,i.appendChild(r),Array.prototype.forEach.call(i.querySelectorAll("img[data-bc-src]"),function(e){var t=e.getAttribute("data-bc-src"),i=e.getAttribute("width");isNaN(i)||null===i||(t+="&width="+i);var n=e.getAttribute("height");isNaN(n)||null===n||(t+="&height="+n),e.setAttribute("src",t),e.removeAttribute("data-bc-src")}.bind(this))}},_addItemNodes:function(e,t,i){var n=document.querySelector(".bcComplexObject"+i.id);if(n&&n.firstChild)for(;n.firstChild;)n.removeChild(n.firstChild);for(var a=0;a<t.length;a++)if(t[a].ID&&t[a].URL)for(var r=e.querySelectorAll('a[href^="'+t[a].URL+'"]'),s=0;s<r.length;s++)r[s].setAttribute("data-bc-item-id",t[a].ID);return n},_addJavaScript:function(e){var t=e.getJavaScript();if(t){var i=document.createElement("script");i.type="text/javascript",i.appendChild(document.createTextNode(t));var n=document.getElementsByTagName("head")[0]||document.documentElement;try{n.insertBefore(i,n.firstChild)}catch(a){console.error(a)}}},_addOnResizeHandler:function(e,t){var i=function(){if(e&&t){for(var i=t.getAttribute("class").split(" "),n=this._getWidthClass(e),a=[n],r="",s=0;s<i.length;s++)-1===i[s].search("^bcp.*Width$")?a.push(i[s]):r=i[s];r!==n&&(t.className=a.join(" "))}}.bind(this);window.addEventListener("resize",(function(){i()}))},_addImageErrorHandler:function(e,t){(t=t||{}).settings=t.settings||{};var i=t.settings.storeId;e.addEventListener("error",function(e){if("IMG"===e.target.tagName){var t=e.target,n=t.getAttribute("src");if(t.style.display="none",!n)return;var a=this.blueConicClient.getHostname();if(-1===n.indexOf(a+"/rest/contentStores/"+i+"/items/"))return;Element.prototype.closest=function(e){var t=this;if(!document.documentElement.contains(this))return null;do{if(t.matches(e))return t;t=t.parentElement}while(null!==t);return null};var r=t.closest("a[data-bc-item-id]");if(0===r.length)return;var s=r.getAttribute("data-bc-item-id"),o=r.getAttribute("href");if(!s||!o)return;var l=encodeURIComponent(encodeURIComponent(s));if(-1===n.indexOf("/items/"+l+"/image"))return;this.blueConicClient.recommendation.createEvent({itemId:s,url:o,storeId:i,lastmodified:(new Date).getTime()})}}.bind(this),!0)},_getWidthClass:function(e){return e?e.clientWidth<=480?"bcpSmallWidth":e.clientWidth>=1024?"bcpMaxWidth":"bcpDefaultWidth":""},_getUrl:function(){var e=document.querySelector('meta[property="og:url"]'),t=document.querySelector('link[rel="canonical"]');return(e.getAttribute("content")||t.getAttribute("href")||window.location.protocol+"//"+window.location.host+window.location.pathname).split("?")[0]},_getQueryStringParametersForRecommendations:function(e){(e=e||{}).settings=e.settings||{};var t={},i=e.settings.storeId;if(!i)return t;t.storeId=i,"No profile present and will not be created."!==this.profile.getId()&&(t.profileId=this.profile.getId());var n=this._getSettings(e);n.debug&&(t.debug=n.debug),n.frequencyCap&&(t.frequencyCap=n.frequencyCap);var a=this._metaDataService.getItemId(document.location.toString());return a&&(t.itemId=a),t.request=this._getRules(e),t},_getSettings:function(e){var t=e.settings||{};return{debug:Boolean(t.debug),frequencyCap:!t.useFrequencyCap||isNaN(t.frequencyCap)||this.blueConicClient.isInEditMode()?null:t.frequencyCap}},_getRules:function(e){return e.rules=e.rules||[],e.rules.map((function(e){return{id:e.isFallback?"default":e.id,filters:this._getRuleFilters(e),boosts:this._getBoostFilters(e),count:e.isFallback?null:e.amount}}),this)},_getCount:function(e){return(e=e||{}).rules=e.rules||[],Array.prototype.filter.call(e.rules,(function(e){return!e.isFallback})).map((function(e){return e.amount||0})).reduce((function(e,t){return e+t}),0)},_getRuleFilters:function(e){var t=[];if(Array.isArray(e.filters)){var i=e.filters.map((function(e){var t="SHOW"===e.filterType&&"IN_STOCK"!==e.id?"_ONLY":"";return e.id+t}));t=t.concat(i)}return Array.isArray(e.metaDataFilters)&&e.metaDataFilters.forEach((function(e){t=t.concat(this._handleFilterRules(e,this._metaDataService)||[])}),this),t},_getBoostFilters:function(e){return e.algorithms.map((function(e){return e.rampUp||delete e.rampUp,e}))},_handleFilterRules:function(e,t){var i=[];switch(e.operatorSetting){case"MUSTNOTBEEMPTY":i.push("hasproperty:"+e.metaDataField);break;case"MUSTBEEMPTY":i.push("!hasproperty:"+e.metaDataField);break;case"CONTAINS":case"DOESNOTCONTAIN":case"CONTAINSALL":case"DOESNOTCONTAINALL":var n=this._handleListRules(e,t);i=i.concat(n);break;case"AFTER":case"BEFORE":case"BETWEEN":var a=this._handleDateRules(e);i=i.concat(a)}return i},_handleListRules:function(e,t){var i=this._getValues(e,t,t.getMetaDataFields());if(0===i.length)return[];var n=[];switch(e.operatorSetting){case"CONTAINS":n=[e.metaDataField+':"'+i.join('","')+'"'];break;case"DOESNOTCONTAINALL":n=["!"+e.metaDataField+':"'+i.join('","')+'"'];break;case"DOESNOTCONTAIN":n=i.map((function(t){return"!"+e.metaDataField+':"'+t+'"'}));break;case"CONTAINSALL":n=i.map((function(t){return e.metaDataField+':"'+t+'"'}))}return n},_handleDateRules:function(e){if(!e.dateValue&&"BETWEEN"!==e.operatorSetting||!e.dateBetweenValue&&"BETWEEN"===e.operatorSetting)return[];var t=[];if("BETWEEN"!==e.operatorSetting){var i=new Date;switch(e.valueType){case"DAYS":"BEFORE"===e.operatorSetting?(i.setDate(i.getDate()-parseInt(e.dateValue)),t.push(e.metaDataField+"<="+i.toISOString())):(i.setDate(i.getDate()-parseInt(e.dateValue)),t.push(e.metaDataField+">="+i.toISOString()));break;case"HOURS":"BEFORE"===e.operatorSetting?(i.setHours(i.getHours()-parseInt(e.dateValue)),t.push(e.metaDataField+"<="+i.toISOString())):(i.setHours(i.getHours()-parseInt(e.dateValue)),t.push(e.metaDataField+">="+i.toISOString()));break;case"DATE":i=new Date(e.dateValue),t.push("BEFORE"===e.operatorSetting?e.metaDataField+"<="+i.toISOString():e.metaDataField+">="+i.toISOString())}}else{var n=e.dateBetweenValue.start,a=e.dateBetweenValue.end;t.push(e.metaDataField+">="+("string"==typeof n?n:n.toISOString())),t.push(e.metaDataField+"<="+("string"==typeof a?a:a.toISOString()))}return t},_getValues:function(e,t,i){if("values"===e.valueType&&e.values.length>0)return e.values;if("property"===e.valueType)return this.profile.getValues(e.property);if(!i)return t.getFieldValues({fieldId:e.metaDataField,type:"default"});for(var n=0;n<i.length;n++)if(i[n].fieldId===e.metaDataField)return t.getFieldValues(i[n]);return[]},_handleEvent:function(e,t,i,n,a,r,s,o,l){if(n){if(!i)return void(document.location.href=t);var c={storeId:n,action:e,itemId:i,url:t};if("No profile present and will not be created."!==this.profile.getId()&&(c.profileId=this.profile.getId()),s&&r&&(c.debug=!0,c.recommendationId=r),"click"===e){if(l&&l.originalEvent&&l.originalEvent._blueConicLoggedClickEvent===a)return;l&&l.originalEvent&&(l.originalEvent._blueConicLoggedClickEvent=a),this.blueConicClient.createEvent("CLICK",a)}this.blueConicClient.recommendation.createEvent(c,(function(){"click"===e&&(o&&"_blank"!==o?window.open(t,o):o&&"_blank"===o||(document.location.href=t))}))}},_bindClicks:function(e,t,i){(i=i||{}).settings=i.settings||{};var n=i.settings.storeId,a=i.settings.debug,r=i.interactionId,s=function(e,i){e.preventDefault();var s=i.getAttribute("href"),o=i.getAttribute("target");o&&"_blank"===o&&window.open(s,o),this._handleEvent("click",s,i.getAttribute("data-bc-item-id"),n,r,t,a,o,e)}.bind(this);Array.prototype.forEach.call(e.querySelectorAll("a[data-bc-item-id]"),function(e){e.addEventListener("click",(function(t){t.currentTarget.dataset.triggered||s(t,e)}))}.bind(this))},_getDataObject:function(e,t){var i=e.length;e=e.map((function(e,t){return e.isFirstItem=0===t,e.isLastItem=t===i-1,e.index=t,e.id&&!e.ID&&(e.ID=e.id),e.url&&!e.URL&&(e.URL=e.url),e.customProperties&&Object.keys(e.customProperties).forEach((function(t){e[t]=e.customProperties[t]})),e}));var n=null;t&&(n=this.blueConicClient.getInteractionNamesById(t)||{id:t});var a={},r=this._metaDataService.getMetaDataFields(),s=this._metaDataService.getItemType(r);return r&&s===this.type&&r.forEach((function(e){var t=e.fieldId;"url"!==t&&"id"!==t||(t=t.toUpperCase()),a[t]=this._metaDataService.getFieldValues(e)}),this),{interaction:n,current:a,recommendations:e}},_sendMessage:function(e,t){this.blueConicClient.fn.postMessage&&this.blueConicClient.fn.postMessage(e,t)},_handleStyling:function(e,t){(e=e||{}).settings=e.settings||{},e.settings.styling=e.settings.styling||{},this._appendTemplateCss(t,e.id),this._setCssUrl(e),this._appendCustomCss(e)},_appendTemplateCss:function(e,t){var i=this.jQuery,n="bcTemplateCss"+t,a=document.querySelector("."+n);a&&a.parentNode.removeChild(a);var r="";if(e&&e.getCss()){var s=i("<style>"+(r+=e.getCss())+"</style>");s.addClass(n),s.appendTo(i("head"))}},_appendCustomCss:function(e){(e=e||{}).settings=e.settings||{},e.settings.styling=e.settings.styling||{};var t=this.jQuery,i="bcCustomCss"+e.id,n=document.querySelector("."+i);if(n&&n.parentNode.removeChild(n),e.settings.styling.customCSS){var a=t("<style>"+e.settings.styling.customCSS+"</style>");a.addClass(i),a.appendTo(t("head"))}},_setCssUrl:function(e){if((e=e||{}).settings=e.settings||{},e.settings.styling=e.settings.styling||{},!this.blueConicClient.isInEditMode&&e.settings.styling.cssURL)this.blueConicClient.util.loadCSS(e.settings.styling.cssURL);else{var t="bcCssUrl"+e.id,i=document.querySelector("#"+t);if(i&&i.parentNode.removeChild(i),e.settings.styling.cssURL){var n=document.createElement("LINK");n.id=t,n.rel="stylesheet",n.type="text/css",n.href=e.settings.styling.cssURL,document.querySelector("head").appendChild(link)}}},_loadTemplate:function(e,t){if(!this.blueConicClient.isInEditMode)return this.blueConicClient.getTemplate(e,t);var i=this._getTemplateFromCache(e);if(i)return t(i);var n=this;this.blueConicClient.getTemplate(e,(function(e){return n._templatesLoaded.push(e),t(e)}))},_getTemplateFromCache:function(e){for(var t=0;t<this._templatesLoaded.length;t++)if(this._templatesLoaded[t].getId()===e)return this._templatesLoaded[t];return null},_addTemplateToCache:function(e){for(var t=e.getId(),i=0;i<this._templatesLoaded.length;i++)if(this._templatesLoaded[i].getId()===t)return void(this._templatesLoaded[i]=e);this._templatesLoaded.push(e)},_createTemplateObject:function(e){return{_css:(e.css||"").replace(/&#xd;/gi,""),_html:(e.html||"").replace(/&#xd;/gi,""),_id:e.id,_javascript:(e.javaScript||"").replace(/&#xd;/gi,""),_precompiledTemplate:e.precompiledTemplate,getHtml:function(){return this._html},getCss:function(){return this._css},getJavaScript:function(){return this._javascript},getId:function(){return this._id}}},_migration:function(e){if(!e||5===e.version)return e;var t=parseInt(e.version||1);return e.strategy&&e.strategy.boostLevels&&!Array.isArray(e.strategy.boostLevels)&&(e=this._migrateV1(e)),t<2&&(e=this._migrationV2(e)),t<3&&(e=this._migrationV3(e)),t<4&&(e=this._migrationV4(e)),t<5&&(e=this._migrationV5(e)),e},_migrateV1:function(e){var t=Object.keys(e.strategy.boostLevels).map((function(t){return{algorithm:t,value:e.strategy.boostLevels[t]}}));return e.strategy.boostLevels=t,e},_migrationV2:function(e){var t={id:(e=this._normalizeMigratedData(e)).id,interactionId:e.interactionId,version:2,settings:{useFrequencyCap:e.exceptions.useFrequencyCap,frequencyCap:e.exceptions.frequencyCap,templateId:e.styling.templateId,storeId:e.sources,connectionId:e["data-bc-connection-id"],debug:e.debug||!1,styling:{cssURL:e.styling.cssURLNode,customCSS:e.styling.customCSS}},rules:[{id:(new Date).getTime(),amount:e.styling.amount||4,algorithms:e.strategy.boostLevels.map((function(e){return e.algorithm=e.algorithm.replace(/_n$/,"").toUpperCase(),e.rampup&&(e.rampUp=e.rampup,delete e.rampup),"string"==typeof e.value&&(e.value=parseFloat(e.value.replace(",","."))),e})),filters:e.exceptions.filters.map((function(e){return{id:e.replace("instock","in_stock").replace("only","").toUpperCase(),filterType:-1!==e.indexOf("only")?"SHOW":"HIDE"}})),metaDataFilters:e.exceptions.filterRules}],"data-bc-connection-id":e["data-bc-connection-id"],"data-bc-template-id":e["data-bc-template-id"]};return e.exceptions.hideReadArticles&&(t.rules[0].filters.some((function(e){return e.id="VIEWED"}))||t.rules[0].filters.push({id:"VIEWED",filterType:"HIDE"}),delete e.exceptions.hideReadArticles),t},_migrationV3:function(e){if(e)return e.settings&&e.settings.storeId&&(e.sources=e.settings.storeId),e.rules&&(e.rules=e.rules.map((function(e){return e&&e.algorithms&&(e.algorithms=e.algorithms.map((function(e){return e&&"CATEGORY"===e.algorithm&&(e.algorithm="SAME_CATEGORY"),e}))),e}))),e},_migrationV4:function(e){if(e)return e.settings&&e.settings.connectionId&&(e["data-bc-connection-id"]=e.settings.connectionId),e},_migrationV5:function(e){return this._migrationV4(e)},_normalizeMigratedData:function(e){return(e=e||{}).styling=e.styling||{},e.strategy=e.strategy||{},e.strategy.boostLevels=e.strategy.boostLevels||[],e.exceptions=e.exceptions||{},e.exceptions.filters=e.exceptions.filters||[],e.exceptions.filterRules=e.exceptions.filterRules||[],e}});var a = [];var i='toolbar_content_recommendations';a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.3.2/frontend/src/node_modules/@blueconic/jquery-x-jquerymigrate/load_jQuery3_5_X_jQueryMigrate.js', sharing: 'local'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.3.2/frontend/src/node_modules/@blueconic/frontend-recommendations-rendering/lib/mustache-2.2.1.min.js', sharing: 'local'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.3.2/frontend/src/node_modules/@blueconic/frontend-metadataservice/metaDataService.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/2.3.2/'}]);})();(function(){ var InteractionTypeImpl = InteractionType.extend({
  blueConicClient: null,
  context: null,
  profile: null,
  parameters: null,
  objectName: null,

  //constants
  DEFAULT_TRACKER_NAME: "ga",
  DEFAULT_EVENT_NAME: "BlueConic",
  SENT_TO_SYSTEM_PROPERTY: "sent_to_system",
  SENT_TO_CONNECTION_PROPERTY: "sent_to_connection",
  PF_PROPERTY_PREFIX: "uapf",

  _LAST_PUSH_PROPERTY: null,
  _VARIABLE_STATE_PUSH_PROPERTY: null,

  _goalParams: null,
  _preloadProperties: null,
  _hasSynchronized: false,
  _visitorSegmentIds: [],

  init: function(blueConicClient, context) {
    this.blueConicClient = blueConicClient;
    this.context = context;
    this.profile = this.context.getProfile();
    this.parameters = this.context.getParameters();
    this._LAST_PUSH_PROPERTY =
      this.PF_PROPERTY_PREFIX + "lt" + this.context.getInteractionId();
    this._VARIABLE_STATE_PUSH_PROPERTY =
      this.PF_PROPERTY_PREFIX + "st" + this.context.getInteractionId();

    // Migrate
    this.parameters = this._migrateParameters(this.parameters);

    // Find tracker name to communicate with Universal Analytics
    this.objectName =
      (this.parameters.trackerName && this.parameters.trackerName[0]) ||
      this.DEFAULT_TRACKER_NAME;
    this._visitorSegmentIds = this._getVisitorSegmentIds();

    // Fill goals with parsed parameters
    this._goalParams = this._parseGoalParams(this.parameters.goalParameters);

    this._fillPreloadProperties();
  },

  /**
   * Returns visitor segment id's
   * @returns array of visitor segment ids, or empty array [] if none exist
   */
  _getVisitorSegmentIds: function() {
    return (
      this.blueConicClient.getSegments().map(function(segment) {
        return segment.id;
      }) || []
    );
  },

  /**
   * Parses the goal params and returns the resulting goal params.
   * The returned params are filtered from invalid and inactive values.
   * @param goalParameters Array of goal parameters to be parsed.
   * @returns an array of goal parameters (which are filtered from invalid and inactive goals).
   */
  _parseGoalParams: function(goalParameters) {
    // 1. parse JSON goal parameters
    // 2. filter out inactive goals and goals without parameters
    // 3. parse export mapping and map to the goal parameters
    return goalParameters
      .map(function(goal) {
        return goal && this.blueConicClient.json.parse(goal);
      }, this)
      .filter(function(goal) {
        return goal && goal.active && goal.parameters;
      })
      .map(function(goal) {
        goal.parameters.id = goal.id;
        goal.parameters.exportMapping = this._parseExportMapping(
          goal.parameters.exportMapping
        );
        return goal.parameters;
      }, this);
  },

  /**
   * Parses export mapping and removes invalid export mappings.
   * @param {Array} exportMapping The unparsed export mapping provided
   * @returns array containing valid export mappings.
   */
  _parseExportMapping: function(exportMapping) {
    var parsedMappings =
      (exportMapping && this.blueConicClient.json.parse(exportMapping[0])) ||
      [];
    return parsedMappings.filter(function(mapping) {
      return this._isValidExportMapping(mapping);
    }, this);
  },

  /**
   * Checks the validity of an export mapping. An export mapping is valid
   * when it maps from a property to a field id. If any or both are missing,
   * then the export mapping is marked invalid.
   * @param  {object} exportMapping A single export mapping to resolve validity for.
   * @returns {boolean} Export mapping validity
   */
  _isValidExportMapping: function(exportMapping) {
    var isComplete =
      exportMapping &&
      exportMapping.from &&
      exportMapping.to &&
      exportMapping.to.values &&
      exportMapping.to.values[0] &&
      exportMapping.to.values[0].id;

    // If it's a property, then the from rule must have an ID
    var isCompleteAndValidType =
      isComplete &&
      (exportMapping.from.typeId !== "property" ||
        (exportMapping.from.values &&
          exportMapping.from.values[0] &&
          exportMapping.from.values[0].id));

    return Boolean(isCompleteAndValidType);
  },

  /**
   * Preloads the properties in a preload list
   */
  _fillPreloadProperties: function() {
    this._preloadProperties = [
      this.SENT_TO_SYSTEM_PROPERTY,
      this.SENT_TO_CONNECTION_PROPERTY
    ];

    this._goalParams.forEach(function(goal) {
      this._preloadProperties.push(this._LAST_PUSH_PROPERTY + "_" + goal.id);
      this._preloadProperties.push(
        this._VARIABLE_STATE_PUSH_PROPERTY + "_" + goal.id
      );

      // loop though export mapping properties
      goal.exportMapping.forEach(function(mapping) {
        var propertyValue =
          mapping.from &&
          mapping.from.typeId === "property" &&
          mapping.from.values &&
          mapping.from.values[0] &&
          mapping.from.values[0].id;

        // only add when property is defined and does not exist in _preloadProperties
        if (
          propertyValue &&
          this._preloadProperties.indexOf(propertyValue) === -1
        ) {
          this._preloadProperties.push(mapping.from.values[0].id);
        }
      }, this);
    }, this);
  },

  /**
   * Returns a list of preloaded properties
   * @returns the array of preloaded property names
   */
  getPreloadProperties: function() {
    return this._preloadProperties;
  },

  /**
   * Checks if Univeral Analytics is available on the window
   */
  onLoad: function() {
    this.bcConnectionUtil.md5Lib = window.md5;
    var me = this;
    var recursionCounter = 0;

    /**
     * Check whether Universal Analytics is available on the window scope.
     * When ready, it triggers the handling of goals for this connection.
     */
    function tagReady() {
      if (window[me.objectName]) {
        me._handleGoals();
      } else {
        // wait max 5 seconds for Universal Analytics to load
        if (recursionCounter > 20) {
          return;
        }
        recursionCounter++;
        window.setTimeout(tagReady, 250);
      }
    }
    tagReady.call(this);
  },

  /**
   * Push all events to Universal Analytics
   */
  _handleGoals: function() {
    // For each goal, check if segment is valid and apply goal
    this._goalParams.forEach(function(goal) {
      if (this._isSegmentValid(goal.exportSegment)) {
        this._applyGoal(goal);
      }
    }, this);
  },

  /**
   * Decides if segment is a valid segment.
   * A segment is considered valid, when it is present in the list of visitor segment id's, or when it is empty.
   * @param segments Segment to check validity for
   * @returns whether a segment is valid or not. True for valid, false otherwise.
   */
  _isSegmentValid: function(segments) {
    var isEmpty = !segments || segments.length === 0;
    var isPresentInList =
      segments &&
      segments[0] &&
      this._visitorSegmentIds.indexOf(segments[0]) !== -1;
    return isEmpty || isPresentInList;
  },

  /**
   * Applies a goal (e.g. export data to Google Analytics)
   * @param goal A single export goal (to export)
   */
  _applyGoal: function(goal) {
    var connectionContext = this._createConnectionContext(goal);

    this._pushProfileValues(goal, connectionContext);

    // subscribe to selected trigger event
    if (goal.triggerEvent && goal.triggerEvent[0]) {
      this.blueConicClient.event.subscribe(
        goal.triggerEvent[0],
        this,
        function() {
          this._doPush(goal, connectionContext);
        }
      );
    }

    var eventName = this._getEventNameForGoal(goal);
    var trackerName = this._getTrackerNameForGoal(goal);
    if (goal.push_interactions && goal.push_interactions[0] === "true") {
      this._subscribeToInteractionViews(trackerName, eventName);
    }

    if (goal.passOnEvents && goal.passOnEvents[0] === "true") {
      this._subscribeToPassOnEvents(trackerName, eventName);
    }
  },

  /**
   * Pushes profile values to Universal Analytics, but only when situation allows.
   * This depends on the goal parameters (for example, the user might have set a certain push frequency)
   * @param goal Goal parameters
   */
  _pushProfileValues: function(goal, connectionContext) {
    if (this.bcConnectionUtil.doPush(connectionContext)) {
      this._doPush(goal, connectionContext);
    } else if (connectionContext.push_frequency === "plc") {
      // only push when the permission level changes
      this.blueConicClient.event.subscribe(
        this.blueConicClient.event.onProfilePermissionChange,
        this,
        function() {
          this._doPush(goal, connectionContext);
        }
      );
    }
  },

  /**
   * Pushes profile values mapped to dimension names (of Universal Analytics) to Universal Analytics
   * @param goal Goal parameters for goal to push profile values for
   * @returns True when profile values are pushed, false it nothing is exported.
   */
  _doPush: function(goal, connectionContext) {
    var exportMappings = goal.exportMapping;

    if (exportMappings.length === 0) {
      return false;
    }

    var dimensionObject = {
      nonInteraction: 1,
      userId: this.profile.getId()
    };

    var hasValues = false;
    exportMappings.forEach(function(exportMapping) {
      var variableValue = this.bcConnectionUtil.getVariableValue(
        exportMapping.from,
        connectionContext,
        true
      );
      if (variableValue) {
        dimensionObject[exportMapping.to.values[0].id] = variableValue.join(
          ","
        );
        hasValues = true;
      }
    }, this);

    if (hasValues) {
      var eventName = this._getEventNameForGoal(goal);
      var trackerName = this._getTrackerNameForGoal(goal);
      this._pushUA(trackerName, eventName, "Profile", dimensionObject);
    }
    return hasValues;
  },

  /**
   * Creates a connection context for the goal parameters provided.
   * @param goal Goal parameters
   * @returns The connection context specific for this goal
   */
  _createConnectionContext: function(goal) {
    var connectionContext = {
      LAST_PUSH_PROPERTY: this._LAST_PUSH_PROPERTY + "_" + goal.id,
      VARIABLE_STATE_PUSH_PROPERTY:
        this._VARIABLE_STATE_PUSH_PROPERTY + "_" + goal.id,
      profile: this.profile,
      // eslint-disable-next-line camelcase
      push_frequency:
        goal.push_frequency && goal.push_frequency[0]
          ? goal.push_frequency[0]
          : null,
      variables: variables,
      SENT_TO_SYSTEM_PROPERTY: this.SENT_TO_SYSTEM_PROPERTY,
      SENT_TO_CONNECTION_PROPERTY: this.SENT_TO_CONNECTION_PROPERTY
    };

    // retrieve variables from goal
    var variables = [];
    goal.exportMapping.forEach(function(exportMapping) {
      var variable = exportMapping.from;
      var variableValue = this.bcConnectionUtil.getVariableValue(
        variable,
        connectionContext
      );

      // if export mapping contains a variable value
      if (variableValue) {
        variable.key = exportMapping.to.values[0].id;
        variables.push(variable);
      }
    });

    connectionContext.variables = variables;
    return connectionContext;
  },

  /**
   * Gets the event name set by the user for this goal (or default)
   * @param goal Goal parameters
   * @returns the event name for the goal
   */
  _getEventNameForGoal: function(goal) {
    return (goal.eventname && goal.eventname[0]) || this.DEFAULT_EVENT_NAME;
  },

  /**
   * Get the tracker name for the goal, use global setting if not set
   * @param {object} goal Goal parameters
   * @returns {string} The tracker name to use, empty if no special tracker name is specified
   */
  _getTrackerNameForGoal: function(goal) {
    if (goal.trackerName && goal.trackerName[0]) {
      return goal.trackerName[0] + ".";
    }
    return "";
  },

  /**
   * Subscribes to interaction views, so that when an interaction view event
   * occurs, then the interaction views are pushed to Universal Analytics.
   * @param trackerName Name of Analytics tracker this event gets sent to
   * @param eventName event name to use when sending event to Universal Analytics
   */
  _subscribeToInteractionViews: function(trackerName, eventName) {
    this.blueConicClient.event.subscribe(
      "VIEW",
      this,
      this._pushInteractionViews.bind(this, trackerName, eventName)
    );
  },

  /**
   * Pushes to universal analytics and synchronizes BlueConic after it (if required)
   * @param trackerName Name of Analytics tracker this event gets sent to
   * @param eventCategory Event category
   * @param eventAction Event action
   * @param eventLabel Event label (optional)
   * @param eventValue Event value (optional)
   */
  _pushUA: function(
    trackerName,
    eventCategory,
    eventAction,
    eventLabel,
    eventValue
  ) {
    window[this.objectName](
      trackerName + "send",
      "event",
      eventCategory,
      eventAction,
      eventLabel,
      eventValue
    );
    this._syncProperties();
  },

  /**
   * Pushes interaction views to Universal Analytics
   * @param trackerName Name of Analytics tracker this event gets sent to
   * @param eventName Event name used to send to Universal Analytics
   */
  _pushInteractionViews: function(trackerName, eventName) {
    this.blueConicClient
      .getInteractions()
      .map(function(interaction) {
        return interaction.variantName
          ? interaction.name + " / " + interaction.variantName
          : interaction.name;
      })
      .forEach(function(interactionName) {
        // Events influence bounce rates, by sending 'nonInteraction'
        // we tell GA that the event should not influence the bounce rate.
        this._pushUA(
          trackerName,
          eventName,
          "Interaction View",
          interactionName,
          {
            nonInteraction: 1,
            userId: this.profile.getId()
          }
        );
      }, this);
  },

  /**
   * Subscribes to BlueConic events so that the respective BlueConic events
   * are sent directly and seperately to Universal Analytics.
   * @param trackerName Name of Analytics tracker this event gets sent to
   * @param eventName event name to use when sending pass on events
   */
  _subscribeToPassOnEvents: function(trackerName, eventName) {
    this.blueConicClient.event.subscribe(
      "inactivity",
      this,
      this.onEventPublished.bind(this, trackerName, eventName, "Inactivity")
    );
    this.blueConicClient.event.subscribe(
      "exitintent",
      this,
      this.onEventPublished.bind(this, trackerName, eventName, "Exit Intent")
    );
    this.blueConicClient.event.subscribe(
      "cm_firstview",
      this,
      this.onEventPublished.bind(
        this,
        trackerName,
        eventName,
        "Content Meter View 1"
      )
    );
    this.blueConicClient.event.subscribe(
      "cm_exceeded",
      this,
      this.onEventPublished.bind(
        this,
        trackerName,
        eventName,
        "Content Meter View " + "Content Meter Exceeded"
      )
    );

    for (var x = 2; x < 10; x++) {
      this.blueConicClient.event.subscribe("cm_view_" + x, this, function(
        event
      ) {
        var view = event.split("_")[2];
        this.onEventPublished(
          trackerName,
          eventName,
          "Content Meter View " + view
        );
      });
    }
  },

  /**
   * Called when an event is published. This event is pushed to Universal Analytics.
   * @param trackerName Name of Analytics tracker this event gets sent to
   * @param eventName event name to send to Universal Analytics.
   * @param eventCategory category name of event (Content)
   */
  onEventPublished: function(trackerName, eventName, eventCategory) {
    var nonInteractionObject = {
      nonInteraction: 1,
      userId: this.profile.getId()
    };

    this._pushUA(trackerName, eventName, eventCategory, nonInteractionObject);
  },

  /**
   * var BlueConic synchronize it's data to represent the latest exports.
   */
  _syncProperties: function() {
    if (!this._hasSynchronized) {
      this.bcConnectionUtil.setSyncProperties(this.context, this.profile, [
        this.SENT_TO_SYSTEM_PROPERTY,
        this.SENT_TO_CONNECTION_PROPERTY
      ]);
      this._hasSynchronized = true;
    }
  },

  /**
   * Migrates/Transforms the parameters to the latest parameters format (if necessary)
   * @param parameters The parameters to migrate (if necessary)
   * @returns The new parameters (if migration is needed), otherwise original parameters.
   */
  _migrateParameters: function(parameters) {
    return parameters.goalParameters
      ? parameters
      : this._migrateToV2(parameters);
  },

  /**
   * Migration from Universal Analytics to Connection 2.0
   * @param oldParams The old parameters
   * @returns Migrated parameters to version 2.
   */
  _migrateToV2: function(oldParams) {
    var getValue = function(key, defaultValue) {
      return oldParams[key] || defaultValue;
    };

    // Migrate export mappings
    var exportMappings = [];
    var dimensions = getValue("dimensions");

    var parsedDimensions =
      dimensions && dimensions[0] ? JSON.parse(dimensions[0]) : [];
    parsedDimensions.forEach(function(dimension) {
      var mapping = {
        id: dimension.id,
        from: {
          type: dimension.type === "pm" ? "permission" : dimension.type,
          property: dimension.property,
          segments: dimension.segments,
          fieldLabel: dimension.type === "text" ? dimension.text : undefined,
          fieldId: dimension.text
        },
        to: {
          type: "text",
          fieldLabel: "Dimension " + dimension.index,
          fieldId: "dimension" + dimension.index
        },
        mergeRule: "set"
      };

      exportMappings.push(mapping);
    });

    var profileProperties = getValue("profileproperties");

    var goalParams = {
      exportSegment: [""],
      exportMapping: [this.blueConicClient.json.stringify(exportMappings)],
      properties_out: Array.isArray(profileProperties)
        ? profileProperties
        : [profileProperties],
      segments: [],
      push_frequency: getValue("push_frequency") || [""],
      triggerEvent: getValue("triggerEvent") || [""],
      eventname: [this.DEFAULT_EVENT_NAME],
      push_interactions: ["true"],
      passOnEvents: ["false"],
      saved: ["true"]
    };

    // Migrated export goal
    return {
      trackerName: [getValue("custom_tracker") || this.DEFAULT_TRACKER_NAME],
      goalParameters: [
        JSON.stringify({
          id: "1",
          type: "export",
          name: "Export data into Universal Analytics",
          active: true,
          parameters: goalParams
        })
      ]
    };
  }
});
var a = [];var i='uaconnection';a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.3.3/frontend/src/node_modules/@blueconic/connection_lib/connection_lib.js', sharing: 'local'});a.push({url: blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.3.3/frontend/src/lib/md5.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwarePluginsRepositoryUrl(ps, pf) + i + '/1.3.3/'}]);})();(function(){ 
var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a;this.context=b},onLoad:function(){window.bcUrlListenerActive||(window.bcUrlListenerActive=!0,window.history&&window.history.pushState&&(window.history.pushState=function(a,b){return function(){b.handlePageView();a.apply(this,arguments)}}(window.history.pushState,this.blueConicClient)))}});
var a = [];var i='urllistenerinteractiontype_hearst';blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : blueConic.fn.getBCHostnameAwareLocalPluginsUrl() + '/plugins/urllistenerinteractiontype_hearst/ts_81e3a5301a9dcbbcce5b0186a790881c/'}]);})();})(blueConicClient);