(function( blueConic, undefined ) {var p='http://plugins.blueconic.net/';var ps='https://plugins.blueconic.net/';(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 : 'https://hearst.blueconic.net/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 : 'https://hearst.blueconic.net/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 a(){if(t._bcDatalayerUtil.getDataLayer())t._handleGoals();else{if(e>20)return;e++,window.setTimeout(a,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){window[this.objectName]&&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),s=0;s<o.length;s++)o[s].to.values.length>0&&t.push(o[s].to.values[0].id)}return t}});var a = [];var i='connection_datalayer';a.push({url: p + i + '/2.2.2/frontend/src/node_modules/@blueconic/connection_lib/connection_lib.js', sharing: 'local'});a.push({url: p + i + '/2.2.2/frontend/src/node_modules/@blueconic/datalayer_lib/datalayer_lib.js', sharing: 'local'});a.push({url: p + i + '/2.2.2/frontend/src/lib/jsonpath.min.js', sharing: 'local'});a.push({url: p + i + '/2.2.2/frontend/src/lib/md5.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/2.2.2/'}]);})();(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(t,e){this.blueConicClient=t,this.context=e,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 t=this._getFrontendGoals(this.parameters).reduce(function(t,e){var n=JSON.parse(e.parameters.exportMapping[0]).filter(function(t){return"property"===t.from.dataType&&t.from.values&&t.from.values.length>0}).map(function(t){return t.from.values[0].id});return t.concat(n)},[]).concat(this.goals.reduce(function(t,e){return t.push(e.context.LAST_PUSH_PROPERTY),t.push(e.context.VARIABLE_STATE_PUSH_PROPERTY),t},[]));return t.push(this.SENT_TO_CONNECTION_PROPERTY),t.push(this.SENT_TO_SYSTEM_PROPERTY),t},onLoad:function(){if(0!==this.goals.length&&this.pixelId){this._addVariablesToGoals(),this._createFacebookScript(),window.fbq("init",this.pixelId);for(var t=0;t<this.goals.length;t++)this._handleGoal(this.goals[t].goal,this.goals[t].context)}},_addVariablesToGoals:function(){this.goals.forEach(function(t){var e=[];t.goal.exportMapping.forEach(function(n){if(t.goal.pushFrequency===PUSH_FREQUENCY_TYPES.ONLY){var i=n.from;this.bcConnectionUtil.getVariableValue(i,t.context)&&(i.key=n.to.values[0].id,e.push(i))}}),t.context.variables=e})},_parseGoals:function(){var t=this._getFrontendGoals(this.parameters);if(0===t.length||!this.pixelId)return[];for(var e=[],n=0;n<t.length;n++)if(this._shouldGoalExecute(t[n])){var i=this._parseGoal(t[n]);e.push({goal:i,context:this._createGoalContext(i)})}return e},_getFrontendGoals:function(t){return t.frontendGoals.map(JSON.parse)},_createFacebookScript:function(){var t,e,n,i,r,a;t=window,e=document,n="script",t.fbq||(i=t.fbq=function(){i.callMethod?i.callMethod.apply(i,arguments):i.queue.push(arguments)},t._fbq||(t._fbq=i),i.push=i,i.loaded=!0,i.version="2.0",i.queue=[],(r=e.createElement(n)).async=!0,r.src="https://connect.facebook.net/en_US/fbevents.js",(a=e.getElementsByTagName(n)[0]).parentNode.insertBefore(r,a))},_parseGoal:function(t){var e=t.parameters;return e.exportMapping=JSON.parse(this._getValue("exportMapping",e)),e.pushFrequency=this._getValue("pushFrequency",e),e.exportSegment=this._getValue("exportSegment",e),e.eventName=this._getValue("eventName",e),e.events=[],e.triggerEvent&&e.events.push(e.triggerEvent),e.pushFrequency===PUSH_FREQUENCY_TYPES.PLC&&e.events.push(this.blueConicClient.event.onProfilePermissionChange),e},_getValue:function(t,e){return e[t]&&e[t][0]||null},_getValues:function(t,e){return e[t]?e[t]:[]},_handleGoal:function(t,e){if(!1!==this._validSegment(t.exportSegment)){var n=this;t.events.forEach(function(i){n.blueConicClient.event.subscribe(i,n,function(){setTimeout(function(){n.profile.loadValues(n.preloadProperties,n,function(){n._pushGoalData(t,e)})},200)})}),this.bcConnectionUtil.doPush(e)&&this._pushGoalData(t,e)}},_pushGoalData:function(t,e){for(var n={},i=!1,r=0;r<t.exportMapping.length;r++){var a=t.exportMapping[r];if(a.from){var s=this.bcConnectionUtil.getVariableValue(a.from,e,!0).filter(function(t){return null!=t});s&&s.length>0&&(n[a.to.values[0].id]=1===s.length?s[0]:s,i=!0)}}if(i){var o=t.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(t){if(t===this.MIGRATED_SEGMENT_ID)return!0;for(var e=0;e<this.segments.length;e++)if(this.segments[e].id===t)return!0;return!1},_createGoalContext:function(t){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:t.pushFrequency||null,profile:this.profile,variables:[]}},_shouldGoalExecute:function(t){return this.context.getGoals().some(function(e){return e.getId()===t.id})},_isStandardEvent:function(t){for(var e=0;e<this.STANDARD_EVENTS.length;e++)if(t===this.STANDARD_EVENTS[e])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 t=this.parameters.eventName,e=this.parameters.push_frequency,n=JSON.parse(this.parameters.variables).map(function(t){return{from:{typeId:t.type,values:[{id:t.property}]},to:{typeId:"text",dataType:"text",values:[{id:t.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:t,triggerEvent:null,pushFrequency:e,exportSegment:[this.MIGRATED_SEGMENT_ID]}}))}});var a = [];var i='connection_facebook_ads';a.push({url: p + i + '/4.4.2/frontend/src/node_modules/@blueconic/connection_lib/connection_lib.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/4.4.2/'}]);})();(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: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});a.push({url: p + i + '/1.1.24/frontend/src/scripts/handlerUtil.js', sharing: 'none'});a.push({url: p + i + '/1.1.24/frontend/src/scripts/handleCss.js', sharing: 'none'});a.push({url: p + i + '/1.1.24/frontend/src/scripts/handleContent.js', sharing: 'none'});a.push({url: p + i + '/1.1.24/frontend/src/scripts/handleJavaScript.js', sharing: 'none'});a.push({url: p + i + '/1.1.24/frontend/src/scripts/handleAdvanced.js', sharing: 'none'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/1.1.24/'},{ id : 'html', baseUrl : ps + 'html/1.0.10/'},{ id : 'string', baseUrl : ps + '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 : 'https://hearst.blueconic.net/plugins/contentinteractiontypespecial/ts_25b8fc569d2bb21e2b65eaf5782e7c3a/'},{ id : 'boolean', baseUrl : ps + 'boolean/1.0.1/'},{ id : 'html', baseUrl : ps + 'html/1.0.10/'},{ id : 'string', baseUrl : ps + '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 : 'https://hearst.blueconic.net/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(v),i=(t.contentcandidates||[]).map(JSON.parse).map(v),a={},c={},o={};r.forEach(function(e){u(e,l)}),i.forEach(function(e){u(e,s)})}function u(t,n){var r=function(){n(t);var i=c[t.interactionId],a=o[t.selecterarea];i||a||e.position.subscribe(t.selecterarea,null,r)};e.position.subscribe(t.selecterarea,null,r),n(t)}function l(e){for(var t=d(e),r=n(e.selecterarea),i=0,a=r.length;i<a;i++)r[i].addEventListener("click",t,{once:!0})}function s(e){f(e)&&d(e)()}function f(e){if(c[e.interactionId])return!1;for(var t=n(e.selecterarea),r=0,i=t.length;r<i;r++)if(h(t[r].textContent,e.words))return!0;return!1}function d(t){return a[t.interactionId]||(a[t.interactionId]=function(n,a){var u=c[n],l=o[t.selecterarea];if(!u&&!l){var s=[];s=(s=a instanceof MouseEvent?r.filter(function(e){var t=!c[e.interactionId],n=$(e.selecterarea).is(event.target),r=$(e.selecterarea).find(event.target).length>0;return t&&(n||r)}):i.filter(function(e){return f(e)})).filter(function(e){return e.interactionId!==t.interactionId}),o[t.selecterarea]=!0,o[t.interactionId]=!0,s.forEach(function(e){o[e.selecterarea]=!0,c[e.interactionId]=!0});var d=s.map(function(e){return e.interactionId});e.createEvent("CONVERSION",n,null,function(){e.util.log("CONVERSION event registred. Interaction: ["+n+"]")},{losingInteractions:d})}}.bind(null,t.interactionId)),a[t.interactionId]}function h(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(),i=0,a=n.length;i<a;i++)if(r.indexOf(n[i])>=0)return!0;return!1}function v(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: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/1.1.8/'}]);})();(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 : 'https://hearst.blueconic.net/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: p + i + '/1.2.23/frontend/src/scripts/enumsAndConstants.js', sharing: 'none'});a.push({url: p + i + '/1.2.23/frontend/src/scripts/elementModifier.js', sharing: 'none'});a.push({url: p + i + '/1.2.23/frontend/src/scripts/domModifier.js', sharing: 'none'});a.push({url: p + i + '/1.2.23/frontend/src/scripts/notificationBar.js', sharing: 'none'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/1.2.23/'},{ id : 'html', baseUrl : ps + 'html/1.0.10/'},{ id : 'image', baseUrl : ps + 'image/1.0.2/'},{ id : 'number', baseUrl : ps + 'number/1.0.2/'},{ id : 'string', baseUrl : ps + '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: p + i + '/6.3.1/js/engagement_service/engagementService.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/6.3.1/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.interaction=b,this.parameters=this.interaction.getParameters();var c=this.parameters.propertyRules&&this.parameters.propertyRules[0]?this.parameters.propertyRules[0]:null;if(c){c=a.json.parse(c),this.preLoadProperties=[];for(var d,e=0,f=0;f<c.length;f++)d=c[f],d.profileproperty&&d.decay&&(this.preLoadProperties.push(d.profileproperty),d.decay>e&&(e=d.decay,this.property=d.profileproperty))}else{var g=this.parameters.property?this.parameters.property[0]:this.parameters.property;g&&(this.property=this.blueConicClient.json.parse(g)[0].profileproperty,this.preLoadProperties=[this.property])}},getPreloadProperties:function(){return this.preLoadProperties},onLoad:function(){if(0<this.preLoadProperties.length){var a=this.interaction.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=new this.BlueConicEngagement(this.blueConicClient,a,this.property,!1,"",this.jQuery);if(c.applyEngagementRules(b),c.isChanged())c.save();else{for(var d,e=!1,f=0;f<this.preLoadProperties.length;f++)d=this.preLoadProperties[f],a.getValue(d)||(a.setValue(d,"0"),e=!0);e&&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: p + i + '/6.3.1/js/engagement_service/engagementService.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/6.3.1/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.context=b},getPreloadProperties:function(){return this.preloadProperties=[],this.context&&(this.preloadProperties=this.getProfilePropertiesFromParameters(this.context.getParameters())),this.preloadProperties},onLoad:function(){var a=this.context.getProfile(),b=this.context.getParameters(),c=b.listener_rules?b.listener_rules[0]:b.listener_rules;if(c){c=this.blueConicClient.json.parse(c);var d=new this.RuleService(this.blueConicClient,a,this.jQuery);d.applyRules(c),d.save()}},getProfilePropertiesFromParameters:function(a){var b=[],c=a.listener_rules?a.listener_rules[0]:a.listener_rules;if(!c)return b;c=this.blueConicClient.json.parse(c);for(var d,e=0;e<c.rules.length;e++)d=c.rules[e],d.profileproperty&&("set_if_empty"===d.addset||"merge"===d.addset)&&b.push(d.profileproperty[0].profileproperty);return b}});var a = [];var i='enrichprofilebyvisitorbehavior';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});a.push({url: p + 'enrichProfileByVisitorBehavior/5.3.1/js/ruleService.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + 'enrichProfileByVisitorBehavior/5.3.1/'}]);})();(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: p + i + '/1.0.17/js/connection_lib/connection_lib.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + 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 : 'https://hearst.blueconic.net/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: p + i + '/2.0.5/js/ouibounce.js', sharing: 'none'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/2.0.5/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){if(this.blueConicClient=a,this.context=b?b: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 c=this.parameters.positions;if(c)for(var d,e=0;e<c.length;e++)d=c[e],this.blueConicClient.position.subscribe(d,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(a){this._isViewEventPublished()||this.blueConicClient.isInEditMode()||(this._setViewEventPublished(!0),this.blueConicClient.createEvent("VIEW",this.context.getInteractionId()));var b=this;try{var c="bcCtrl"+this.context.getInteractionId();if(this.jQuery(a+" a").off("click."+c).on("click."+c,function(){b._handleClick()}),this.jQuery(document).off("click."+c).on("click."+c,a+" a",function(){b._handleClick()}),this.jQuery(document).off("submit."+c).on("submit."+c,a+" form",function(){b._handleClick()}),0<this.jQuery(a).find("iframe").length){window.focus();var d=!1,e=this.jQuery(this.jQuery(a).find("iframe"));e.off("mouseenter."+c).on("mouseenter."+c,function(){d=!0}),e.off("mouseleave."+c).on("mouseleave."+c,function(){d=!1}),this.jQuery(window).off("blur."+c).on("blur."+c,this.jQuery.proxy(function(){d&&this._handleClick()},this))}}catch(a){}},onLoad:function(){if(this.parameters){var a=this.parameters.positions;if(a)for(var b,c=0;c<a.length;c++)b=a[c],0<this.jQuery(b).length&&this._handlePosition(b)}},_isViewEventPublished:function(){return!!window._bcp.publishedEvents.viewEvent[this.context.getInteractionId()]},_setViewEventPublished:function(a){window._bcp.publishedEvents.viewEvent[this.context.getInteractionId()]=a},_isClickEventPublished:function(){return!!window._bcp.publishedEvents.clickEvent[this.context.getInteractionId()]},_setClickEventPublished:function(a){window._bcp.publishedEvents.clickEvent[this.context.getInteractionId()]=a}});var a = [];var i='globallistener_controlgroup';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/1.0.9/'}]);})();(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;
    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();
    }
    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 : 'https://hearst.blueconic.net/plugins/hearst_login_entitlement_listener/ts_7337c8d95bb8f171d53333c94695b06a/'}]);})();(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);
        //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");
        }
        
        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();
        }
        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.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 : 'https://hearst.blueconic.net/plugins/hearstprelistener/ts_16a476fd52b833b4f08e1760cdf8a909/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({_timeout:null,_timestamp:null,_interval:200,init:function(a,b){this.blueConicClient=a,this.context=b||null},onLoad:function(){var a=this.jQuery,b=this;this.blueConicClient.event.subscribe(this.blueConicClient.event.onUrlChange,this,function(){this._setTimestamp(),clearTimeout(b._timeoutID),b._timeoutID=setTimeout(function(){b._checkTimeout()},b._interval)}),this._setTimestamp();var c,d=this.context.getParameters(),e="true"===d.clicks[0],f="true"===d.inputs[0],g=d.scrolling;c=!g||"true"===d.scrolling[0],this._timeout=d.timeout[0],this._timeout?!isNaN(parseInt(this._timeout))&&(this._timeout=1e3*parseInt(this._timeout)):this._timeout=60000;(e||f||c)&&(e&&a(document).on("click","*",function(){b._setTimestamp()}),f&&(a("input").on("keyup",function(){b._setTimestamp()}),a("textarea").on("keyup",function(){b._setTimestamp()}),a("select").on("change",function(){b._setTimestamp()}),a("input").on("change",function(){b._setTimestamp()})),c&&a(window).scroll(function(){b._setTimestamp()}),this._timeoutID=setTimeout(function(){b._checkTimeout()},b._interval))},_handleInactivity:function(){this.blueConicClient.createEvent("inactivity")},_checkTimeout:function(){var a=new Date().getTime(),b=this;a-this._timestamp>this._timeout?this._handleInactivity():b._timeoutID=setTimeout(function(){b._checkTimeout()},b._interval)},_setTimestamp:function(){this._timestamp=new Date().getTime()}});var a = [];var i='inactivitylistener';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/1.1.11/'}]);})();(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 : ps + i + '/2.0.8/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(t,e){this.blueConicClient=t,this.context=e,this.parameters=this.context.getParameters(),this.isInEditMode=this.blueConicClient.isInEditMode(),this.fancyBoxLib="frontend/src/lib/fancybox/jquery.fancybox.pack.js";var i=this.context.getInteractionTypeId();this.baseURL=this.blueConicClient.getBaseURL(i);var n=this.parameters.content+"";this.htmlFragment=this.createElement(n),this.profile=t.profile.getProfile(),this.inlineCss=null,this._timestamp=null,this._observer=null,this._eventListenerFunction=null,this._lightboxTriggered=!1,this.blueConicClient._renderedInteractions=this.blueConicClient._renderedInteractions||[],this.blueConicClient.event.subscribe(this.blueConicClient.event.onUrlChange,this,function(){var t=this.blueConicClient.util.array.indexOfArray(this.blueConicClient._renderedInteractions,this.context.getInteractionId());this.blueConicClient._renderedInteractions.splice(t,1)})},getPreloadProperties:function(){for(var t,e=this.context.getParameters().content+"",i=/data-bc-preload="([^"]*)"/g,n=[];null!==(t=i.exec(e));)for(var o=t[1].split(","),r=0;r<o.length;r++)n.push(o[r]);for(var s=this.htmlFragment?this._getPropertiesFromPlaceholders(this.htmlFragment.innerHTML):[],a=0;a<n.length;a++)s.push(n[a]);return s},onMessageReceived:function(t){this.blueConicClient.event.publish("lightbox.messageReceived",t)},onLoad:function(){window.bc=window.bc||{},window.bc.jQuery=this.jQuery,window.bc.$=this.jQuery,window.bcFancyboxLoading?this.blueConicClient.event.subscribe("bcFancyboxLoaded",this,function(){this.onLoad()}):this.blueConicClient._lightboxinteractiontypeFancybox?(this.jQuery.fancybox=this.blueConicClient._lightboxinteractiontypeFancybox,this._onLoadWithLibrary()):(window.bcFancyboxLoading=!0,this.blueConicClient.util.loadScript(this.baseURL+this.fancyBoxLib,this,function(){this.blueConicClient._loadLightboxInteractionTypeFancyBox(window,document,this.jQuery),this.blueConicClient._lightboxinteractiontypeFancybox=this.jQuery.fancybox,delete this.blueConicClient._loadLightboxInteractionTypeFancyBox,this._onLoadWithLibrary(),window.bcFancyboxLoading=!1,this.blueConicClient.event.publish("bcFancyboxLoaded")}))},_onLoadWithLibrary:function(){if(this.isInEditMode)this.showLightbox();else{var t=this.parameters.selected_when||[],e=this.getParameter("click_selector");e&&-1!==this.blueConicClient.util.array.indexOfArray(t,"click_selector")&&this._addClickTriggerBindings(e);var i=this.getParameter("content_condition");i&&-1!==this.blueConicClient.util.array.indexOfArray(t,"content_condition")&&this._addContentPolling(i);var n=this.parameters.scroll_depth&&this.parameters.scroll_depth[0]&&!isNaN(this.parameters.scroll_depth[0])?parseInt(this.parameters.scroll_depth[0]):0;n&&-1!==this.blueConicClient.util.array.indexOfArray(t,"scroll_depth")&&this._addScrollBinding(n),0===t.length&&this.showLightbox(),this._addCloseEventHandler()}},_checkScrollCondition:function(t){this.jQuery(window).scrollTop()/(this.jQuery(document).height()-window.innerHeight)*100>=t&&this.showLightbox()},_addScrollBinding:function(t){this._checkScrollCondition(t),this.jQuery(window).scroll(this.jQuery.proxy(function(){this._checkScrollCondition(t)},this))},_addClickTriggerBindings:function(t){try{var e=this.jQuery(t);e.length>0?e.off("click.lightboxinteractiontype").on("click.lightboxinteractiontype",this.jQuery.proxy(function(){this.showLightbox(!0)},this)):this.blueConicClient.position.subscribe(t,this,this.jQuery.proxy(this._addClickTriggerBindings,this,t))}catch(t){}},_addContentPolling:function(t){this._checkContentCondition(t);var e=this,i=document.getElementsByTagName("body")[0];if(window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver)this._observer=new MutationObserver(function(){e._observeContentChanges(t)}),this._observer.observe(i,{childList:!0,subtree:!0});else if(window.addEventListener)this._eventListenerFunction=function(){e._observeContentChanges(t)},i.addEventListener("DOMNodeInserted",this._eventListenerFunction,!1);else var n=setInterval(function(){e._lightboxTriggered?clearInterval(n):e._checkContentCondition(t)},500)},_observeContentChanges:function(t){if(this._lightboxTriggered){this._observer?this._observer.disconnect():document.getElementsByTagName("body")[0].removeEventListener("DOMNodeInserted",this._eventListenerFunction,!1)}else{var e=this,i=(new Date).getTime();this._timestamp=i,setTimeout(function(){e._timestamp!==i||e._lightboxTriggered||e._checkContentCondition(t)},250)}},_checkContentCondition:function(t){this.jQuery(t).length>0&&this.jQuery(t).html()&&this.jQuery(t).html().length>0&&this.showLightbox()},closeLightbox:function(){this.isInEditMode||this.jQuery.fancybox.close()},_addCloseEventHandler:function(){this.blueConicClient.event.subscribe("closeoverlay",this,function(t,e){e instanceof Array&&e[0]===this.context.getInteractionId()&&this.closeLightbox()})},showLightbox:function(t){if(-1===this.blueConicClient.util.array.indexOfArray(this.blueConicClient._renderedInteractions,this.context.getInteractionId())){this.blueConicClient._renderedInteractions.push(this.context.getInteractionId());this.parameters.selected_when;if(!this._lightboxTriggered||this.isInEditMode||t){var e=this.parameters.delay&&this.parameters.delay[0]&&!isNaN(this.parameters.delay[0])?1e3*parseInt(this.parameters.delay[0]):0;!this.isInEditMode&&e>0?window.setTimeout(this.jQuery.proxy(function(){this._showLightbox()},this),e):this._showLightbox()}}},getSettings:function(){var t=null,e=this.getParameter("width")||null,i=this.getParameter("height")||null,n="true"===this.getParameter("hide_after_close");this.htmlFragment&&(t=this.htmlFragment.innerHTML);var o=!(e||i),r=this.getParameter("show_close"),s=this.getParameter("alternative_close"),a={parent:"body",autoSize:o,autoCenter:!1,autoWidth:!e,autoHeight:!i,closeBtn:"false"!==r,width:e||"auto",height:i||"auto",keys:{close:"false"===s||this.isInEditMode?null:[27]},helpers:{overlay:{locked:!0,closeClick:"false"!==s&&!this.isInEditMode}}};this.getParameter("template")&&(a.padding=0),(t||this.isInEditMode)&&(a.content=" ",a.type="inline");var c=this,l=this.jQuery,h=this.getParameter("effect"),d=this.getParameter("effect_slide_direction")||"left";if(this.isInEditMode&&(h="noEffect"),h&&"noEffect"!==h&&("fadeIn"===h?l.fancybox.transitions.openEffect=function(){var t=l.fancybox._getPosition(!0);t.opacity=0,l.fancybox.wrap.css(t).show().animate({opacity:1},{duration:l.fancybox.current.openSpeed,complete:l.fancybox._afterZoomIn})}:"slideIn"===h&&(l.fancybox.transitions.openEffect=function(){var t,e=l.fancybox._getPosition(!0),i=l(window).height(),n=l(window).width(),o=l(".fancybox-wrap").get(0).getBoundingClientRect(),r="top"===d||"bottom"===d?"top":"left";"top"===d||"bottom"===d?t=i-(i-o.height)/2:"left"!==d&&"right"!==d||(t=n-(n-o.width)/2),e[r]="top"===d||"left"===d?parseInt(e[r])-t+"px":parseInt(e[r])+t+"px";var s={},a="top"===d||"left"===d?"+":"-";s[r]=a+"="+t+"px",l.fancybox.wrap.css(e).show().animate(s,{duration:l.fancybox.current.openSpeed,complete:l.fancybox._afterZoomIn})}),l.fancybox.transitions.openEffect&&(a.openMethod="openEffect",a.openSpeed=1e3)),t)a.afterLoad=function(){c.emptyElementsWithAttribute(c.htmlFragment,"div","data-bc-external");try{l(".fancybox-inner").html(c.htmlFragment.innerHTML)}catch(t){console.error("[BC] Error occured when injecting the HTML in the DOM",t)}c.isInEditMode&&c.blueConicClient.event.publish("lightbox.interactionLoaded",{interaction:c}),c.handleComplexElements(l(".fancybox-inner").get(0));var t=c.getParameter("javascript");if(t&&!c.blueConicClient.isInEditMode()){t=t.replace(/(^|\W)blueConicVariantId(\W|$)/g,'$1"'+c.context.getInteractionId()+'"$2'),c._inlineJs=c.jQuery("<script>"+t+"<\/script>");try{c._inlineJs.appendTo(c.jQuery("body"))}catch(t){console.error(t)}}};else if(c.isInEditMode){a.afterLoad=function(){c.blueConicClient.event.publish("lightbox.interactionLoaded",{interaction:c})}}return this.isInEditMode?a.afterShow=function(){l(".fancybox-close").off("click.fb")}:n&&(a.afterShow=function(){l(".fancybox-close").on("click",l.proxy(function(){this.blueConicClient.doNotShowAgain(this.context.getInteractionId())},this))}.bind(this)),a.afterClose=function(){var t=c.blueConicClient.util.array.indexOfArray(c.blueConicClient._renderedInteractions,c.context.getInteractionId());c.blueConicClient._renderedInteractions.splice(t,1)},a},updateLightbox:function(){this.jQuery.fancybox.update()},getCurrentFancyBox:function(){return this.jQuery.fancybox.current},_showLightbox:function(){this._lightboxTriggered=!0;var t=this.jQuery,e=this.getParameter("close_icon"),i=this.getParameter("close_icon_hover"),n=this;function o(){if(!this.isInEditMode){this.blueConicClient.createEvent("VIEW",this.context.getInteractionId()),!!this.parameters.forceclick&&("true"===this.parameters.forceclick[0]||!0===this.parameters.forceclick[0])&&this.blueConicClient.createEvent("CLICK",this.context.getInteractionId());var e=this.getParameter("click_event_selector");if(e){this.jQuery("body").one("click",e,this.jQuery.proxy(function(t){this.lastClickEvent&&this.lastClickEvent.originalEvent===t.originalEvent||this._logClickEvent(t)},this));try{this.jQuery(e).one("click",this.jQuery.proxy(function(t){this.lastClickEvent=t,this._logClickEvent(t)},this))}catch(t){}}}t(".fancybox-wrap").remove(),t(".fancybox-overlay").remove(),this.highZindex=function(t){var e,i=document.getElementsByTagName(t),n=0,o=0;for(o=0;o<i.length;o++)"auto"!==(e=document.defaultView.getComputedStyle(i[o],null).getPropertyValue("z-index"))&&parseInt(e)>n&&(n=parseInt(e));return n}("*"),this.htmlFragment&&(this.emptyElementsWithAttribute(this.htmlFragment,"div","data-bc-external"),this.isInEditMode||this.handlePlaceholders(this.htmlFragment)),t.fancybox(this.getSettings()),this.highZindex>8e3&&this.highZindex+1030<2147483647&&(t(".fancybox-opened").css("z-index",this.highZindex+1030),t(".fancybox-wrap").css("z-index",this.highZindex+920),t(".fancybox-overlay").css("z-index",this.highZindex+910)),this.highZindex+1030>=2147483647&&(t(".fancybox-opened").css("z-index",2147483647),t(".fancybox-wrap").css("z-index",2147483646),t(".fancybox-overlay").css("z-index",2147483645)),this.isInEditMode||this._setupFrontEndBindings()}this.handleStyling(e,i,function(e){if(!e||(console.error(e),n.isInEditMode))n.handleJavascript().then(function(){o.call(n,t)},function(e){if(console.error("[BC] Loading Javascript urls for the lightbox failed:",e),n.isInEditMode)o.call(n,t);else{var i=n.blueConicClient.util.array.indexOfArray(n.blueConicClient._renderedInteractions,n.context.getInteractionId());n.blueConicClient._renderedInteractions.splice(i,1)}});else{var i=n.blueConicClient.util.array.indexOfArray(n.blueConicClient._renderedInteractions,n.context.getInteractionId());n.blueConicClient._renderedInteractions.splice(i,1)}})},_logClickEvent:function(t){t&&t.originalEvent&&t.originalEvent._blueConicLoggedClickEvent===this.context.getInteractionId()||(t&&t.target&&t.target.pathname&&t.target.hostname&&0===t.target.pathname.indexOf("/s/")&&-1!==t.target.hostname.indexOf("blueconic")||(t.originalEvent&&(t.originalEvent._blueConicLoggedClickEvent=this.context.getInteractionId()),this.blueConicClient.createEvent("CLICK",this.context.getInteractionId())))},_setupFrontEndBindings:function(){var t=this.jQuery(".bcLightboxDontShowAgainLink"),e=this.jQuery(".bcLightboxCloseButton");t.length>0&&t.off("click.dontShowAgainLinks").on("click.dontShowAgainLinks",this.jQuery.proxy(function(t){t.preventDefault(),this.blueConicClient.doNotShowAgain(this.context.getInteractionId()),this.closeLightbox()},this)),e.length>0&&e.off("click.closeButtons").on("click.closeButtons",this.jQuery.proxy(function(){this.closeLightbox()},this))},handleComplexElements:function(t){for(var e=this.getElementsWithAttribute(t,"div","data-bc-pluginid"),i=0;i<e.length;i++){var n=e[i],o=n.getAttribute("data-bc-pluginid"),r=n.getAttribute("data-bc-config");if(r)try{var s=r.replace(/\n/g,"\\\\n").replace(/\r/g,"\\\\r").replace(/\t/g,"\\\\t");r=this.blueConicClient.json.parse(s)}catch(t){r=null}this.blueConicClient.event.publish("bcComplexObject",{plugin:o,config:r,node:n,interactionId:this.context.getInteractionId()}),this.isInEditMode||(n.removeAttribute("data-bc-pluginid"),n.removeAttribute("data-bc-config"))}},emptyElementsWithAttribute:function(t,e,i){for(var n=this.getElementsWithAttribute(t,e,i),o=0,r=n.length;o<r;o++){n[o].innerHTML=""}},getElementsWithAttribute:function(t,e,i){for(var n=[],o=t.getElementsByTagName(e),r=0,s=o.length;r<s;r++){var a=o[r];a.getAttribute(i)&&n.push(a)}return n},createElement:function(t){var e;if(!t)return null;try{(e=document.createElement("div")).innerHTML=t}catch(t){return null}return e},handlePlaceholders:function(t){for(var e=this._getPropertiesFromPlaceholders(t.innerHTML),i=0;i<e.length;i++){var n=e[i],o=this.profile.getValue(n)||"",r=new RegExp("\\$\\{"+n+"\\}","g");t.innerHTML=t.innerHTML.replace(r,encodeURI(o))}},_getPropertiesFromPlaceholders:function(t){for(var e,i=/\$\{([a-zA-Z\-_0-9]+)\}/g,n=[];e=i.exec(t);)n.push(e[1]);return n},getParameter:function(t){return this.parameters[t]&&this.parameters[t][0]?this.parameters[t][0]:null},getParameters:function(t){return this.parameters[t]||null},handleJavascript:function(){var t=this.jQuery,e=this.getParameters("javascript_urls"),i=[];if(e){this.javascriptUrls=e;for(var n=0;n<e.length;n++)i.push(this._getLoadScriptDeferred(e[n]))}return t.when.apply(t,i)},_getLoadScriptDeferred:function(t){var e=this.jQuery.Deferred(),i=document.createElement("script");return i.setAttribute("src",t),i.onload=function(){e.resolve()},i.onerror=function(){e.reject('Url "'+t+"\" couldn't be loaded")},document.head.appendChild(i),e},handleStyling:function(t,e,i){var n=this.getParameter("content"),o=[this.baseURL+"frontend/src/lib/fancybox/jquery.fancybox.css"];n&&-1!==n.indexOf("bcLightboxTemplate")||o.push(this.baseURL+"frontend/src/css/lightbox.css");var r=this.getParameter("styling_css");r&&(this.stylingUrl=r,o.push(r));var s="";"true"===this.getParameter("custom_close")&&t&&(s+=".fancybox-close {background-image: url('"+t+"');background-repeat: no-repeat;background-position: center center;background-size: contain;}",e&&(s+=".fancybox-close:hover {background-image: url('"+e+"');background-repeat: no-repeat;background-position: center center;background-size: contain;}"));var a=this.getParameter("close_position"),c=this.getParameter("close_padding");s+=this._getClosePositionStyling(a,c);var l=this.getParameter("styling_css_inline");return l&&(s+=l.replace(/&#xd;/gi,"")),s&&(this.inlineCss=this.jQuery("<style>"+s+"</style>"),this.inlineCss.appendTo(this.jQuery("body"))),this._loadCssUrls(o,i)},_loadCssUrls:function(t,e){var i=(t=t||[]).length,n=0,o=[];if(0===i)return e();function r(){if(++n>=i)return o.length>0?e(o):e()}t.forEach(function(t){if(document.querySelector('link[href="'+t+'"]'))r();else{var e=document.createElement("link");e.setAttribute("rel","stylesheet"),e.setAttribute("href",t),e.onload=r,e.onerror=function(t){o.push(t),r()},document.head.appendChild(e)}})},_getClosePositionStyling:function(t,e){if(!t)return"";null!==e&&"NaN"!==e||(e="-18");var i=".fancybox-close {";switch(t){case"TOP_LEFT":i+="top:"+e+"px; right: unset; bottom: unset; left:"+e+"px;";break;case"BOTTOM_RIGHT":i+="top: unset; right: "+e+"px; bottom: "+e+"px; left: unset;";break;default:i+="top: "+e+"px; right: "+e+"px; bottom: unset; left: unset;"}return i+"}"}});var a = [];var i='lightboxinteractiontype';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/2.2.20/'},{ id : 'html', baseUrl : ps + 'html/1.0.10/'},{ id : 'image', baseUrl : ps + 'image/1.0.2/'},{ id : 'number', baseUrl : ps + 'number/1.0.2/'},{ id : 'string', baseUrl : ps + 'string/1.0.1/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({EVENT_NAME:"adblock_detected",init:function(a,b){this.blueConicClient=a,this.context=b},getPreloadProperties:function(){var a=this.context.getParameters(),b=a.property?a.property[0]:a.property;return b?[b]:[]},onLoad:function(){var a=this,b=this.context.getProfile(),c=this.context.getParameters(),d=c.property?c.property[0]:c.property;d||(d=this.EVENT_NAME);var e=function(){"no"!==b.getValue(d)&&(b.setValue(d,"no"),a.blueConicClient.profile.updateProfile())},f=function(){"yes"!==b.getValue(d)&&(b.setValue(d,"yes"),a.blueConicClient.profile.updateProfile()),a.blueConicClient.createEvent(a.EVENT_NAME)};window.blockAdBlock?(window.blockAdBlock.on(!1,e),window.blockAdBlock.on(!0,f),window.blockAdBlock.check()):e()}});var a = [];var i='listener_adblock';a.push({url: p + i + '/1.0.16/lib/blockadblock.min.js', sharing: 'none'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/1.0.16/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({init:function(a,b){this.blueConicClient=a,this.context=b},getPreloadProperties:function(){var a=this.context.getParameters(),b=a.responseProperty?a.responseProperty[0]:a.responseProperty;return b?(this.campaignIdentifierProperty=b,[b]):(this.campaignIdentifierProperty="responded_to_campaigns",["responded_to_campaigns"])},onLoad:function(){var a=this.context.getProfile(),b=this.context.getParameters(),c=this.blueConicClient,d=!1,e=!1,f=b.config?b.config[0]:b.config;if(f){for(var g=this.blueConicClient.json.parse(f),h=0;h<g.length;h++){var i=g[h],j=this.getParameterByName(i.parameter);j&&i.profileProperty&&(a.addValue(i.profileProperty,j),d=!0,i.isCampaignIdentifier&&!e&&(this._bindHandlers(j),e=!0))}d&&c.profile.updateProfile()}},_bindHandlers:function(a){var b=this,c=this.context.getProfile(),d=this.blueConicClient,e=this.jQuery;e("a").click(function(){c.addValue(b.campaignIdentifierProperty,a),d.profile.updateProfile()}),e("form").submit(function(){c.addValue(b.campaignIdentifierProperty,a),d.profile.updateProfile()})},getParameterByName:function(a){if(!a)return"";a=a.replace(/[[]/,"\\[").replace(/[\]]/,"\\]");var b=new RegExp("[\\?&#]"+a+"=([^&#]*)"),c=b.exec(location.href);return null===c?"":decodeURIComponent(c[1].replace(/\+/g," "))}});var a = [];var i='listener_campaign_tracker';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/1.0.17/'}]);})();(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 : ps + 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.jQuery,t=this,n=this.context.getInteractionId();e(document).off("focus."+n,"input").on("focus."+n,"input",{},function(){var n=e(this).attr("type");"text"!==n&&"radio"!==n&&"checkbox"!==n&&"number"!==n&&"email"!==n&&"tel"!==n&&"date"!==n&&e(this).attr("type")||t._setLastFocus(t._getFieldName(this))}),e(document).off("focus."+n,"select").on("focus."+n,"select",{},function(){t._setLastFocus(t._getFieldName(this))}),e(document).off("focus."+n,"textarea").on("focus."+n,"textarea",{},function(){t._setLastFocus(t._getFieldName(this))})},_getFieldName:function(e){var t=this.jQuery;return t(e).attr("name")||t(e).attr("id")||t(e).attr("autocomplete")||"Unnamed form field"},_urlsMatches:function(e,t){var n=this.jQuery,r=this;return n(e.urlMatching).filter(function(e,n){return r._urlMatches(n,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(e){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(0,this.jQuery)(e.urlMatching).filter(function(e,r){return n._urlMatches(r,t)&&(!r.word||n._wordIsVisible(r.word))}).length>0},_wordIsVisible:function(e){return(0,this.jQuery)(":contains('"+(e=e.toLowerCase())+"')").filter(function(){for(var t=0;t<this.childNodes.length;t++){var n=this.childNodes[t];if(n.nodeValue&&-1!==n.nodeValue.toLowerCase().indexOf(e))return!0}return!1}).filter(":visible").length>0},_convertStepMapping:function(e,t){var n=this.jQuery,r=this,i=n(t).map(function(e,t){return t.name});return n(e).filter(function(e,t){return 0===t.indexOf(r._funnelName)}).map(function(e,t){var r,s=t.match(/'(.*)' to '(.*)'/);if(s&&s[1]&&s[2]&&-1!==n.inArray(s[1],i)&&-1!==n.inArray(s[2],i))r={source:s[1],target:s[2]};else{var a=t.match(/started at '(.*)'/);a&&a[1]&&-1!==n.inArray(a[1],i)&&(r={start:a[1]})}return r}).filter(function(e,t){return t})},_getFollowedStepsMapping:function(e,t){var n=this.jQuery,r=this.context.getProfile(),i=this._convertStepMapping(r.getValues("funnel_steps"),t),s=null,a=(t.slice(0,t.indexOf(e)),!1);return n(t).each(function(t,r){var u=r.name;(a=a||u===e)||n(i).filter(function(e,t){return t.start===u||t.target===u}).length>0&&(s=u)}),s?this._funnelName+" : '"+s+"' to '"+e+"'":this._funnelName+" : started at '"+e+"'"},_checkWordMatch:function(e){var t=this.jQuery,n=this;setTimeout(function(){var r=!1;t(n._queue).each(function(t,i){n._stepIsVisible(i,e)&&(r=!0)}),r?n._onLoad():n._checkWordMatch(e)},this.POLLING_TIMEOUT)},onLoad:function(){this.jQuery.expr[":"].contains=this.jQuery.expr.createPseudo(this.jQuery.proxy(function(e){return this.jQuery.proxy(function(t){return this.jQuery(t).text().toLowerCase().indexOf(e.toLowerCase())>=0},this)},this)),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))},_removeQueryParameter:function(e,t){var n=e.split("?");if(n.length>=2){for(var r=encodeURIComponent(t)+"=",i=n[1].split(/[&;]/g),s=i.length;s-- >0;)-1!==i[s].lastIndexOf(r,0)&&i.splice(s,1);return e=n[0]+(i.length>0?"?"+i.join("&"):"")}return e},_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.jQuery,n=this,r=this.context.getProfile();this._funnelName=this.parameters.funnelName?this.parameters.funnelName[0]:this.parameters.funnelName;var i=this._getSteps();if(0!==i.length){e=e||this._getUrl();var s=t(i).filter(function(t,r){return n._urlsMatches(r,e)});this._queue=[];var a=null;if(t(s).each(function(t,r){n._stepIsVisible(r,e)?a=r:n._queue.push(r)}),this._queue.length>0&&this._checkWordMatch(e),null!==a){this._currentStepId=a.name,this._addBindings(),r.setValue("funnel_laststep",this._funnelName+" - "+this._currentStepId);var u=this._getFollowedStepsMapping(this._currentStepId,i);r.addValue("funnel_steps",u);var o=!1,l=t(i).filter(function(e,t){return(o=o||t.name===a.name)&&t.name!==a.name}),c=r.getValues("funnel_steps"),h=this._funnelName;l.each(function(e,n){c=t(c).filter(function(e,t){return 0!==t.indexOf(h+" :")||-1===t.indexOf("started at '"+n.name+"'")&&-1===t.indexOf("to '"+n.name+"'")}).toArray()}),r.setValues("funnel_steps",c),r.setValue("funnel_lastfield",""),this._currentStepId===i[i.length-1].name?this._handleEndReached():r.addValue("funnel_busy_with",this._funnelName);var f=this.blueConicClient.getCurrentDate().getTime();r.setValue("funnel_timestamp",f),this.blueConicClient.profile.updateProfile()}}}});var a = [];var i='listener_funnel';a.push({url: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/1.1.3/'}]);})();(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 : ps + 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 : 'https://hearst.blueconic.net/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 : 'https://hearst.blueconic.net/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 : ps + 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 : ps + 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 : 'https://hearst.blueconic.net/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 : ps + 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 : ps + i + '/1.1.14/'}]);})();(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: 'Limited-Time Offer'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    paywall: 'https://subscription.qa1.houstonchronicle.com/checkout/363/773/?origin=paywall&variant=election',
                    paywallInDMA: 'https://subscription.qa1.houstonchronicle.com/checkout/358/773/?origin=paywall&ipid=sincere',
                    paywallOutDMA: 'https://subscription.qa1.houstonchronicle.com/checkout/363/773/?origin=paywall&ipid=sincere',
                    button: 'https://offers.houstonchronicle.com/?offerid=358&origin=button&variant=election',
                    buttonFree: 'https://offers.houstonchronicle.com/?offerid=358&origin=button.free&variant=election', 
                    meter: 'https://subscription.qa1.houstonchronicle.com/checkout/287/675/?origin=meter&ipid=labordaysale', 
                    footer: 'https://subscription.qa1.houstonchronicle.com/checkout/358/773/?origin=footer&ipid=sincere', 
                    inline: 'https://subscription.houstonchronicle.com/checkout/358/773/?origin=inline&variant=election', 
                    abandon: 'https://offers.houstonchronicle.com/?offerid=229&origin=adandon.sale&ipid=brand', 
                };    
            }
            else{
                market_links = {
                    paywall: 'https://subscription.houstonchronicle.com/checkout/363/773/?origin=paywall&variant=election',
                    paywallInDMA: 'https://subscription.houstonchronicle.com/checkout/358/773/?origin=paywall&ipid=sincere',
                    paywallOutDMA: 'https://subscription.houstonchronicle.com/checkout/363/773/?origin=paywall&ipid=sincere',
                    button: 'https://offers.houstonchronicle.com/?offerid=358&origin=button&variant=election',
                    buttonFree: 'https://offers.houstonchronicle.com/?offerid=358&origin=button.free&variant=election', 
                    meter: 'https://subscription.houstonchronicle.com/checkout/287/675/?origin=meter&ipid=labordaysale', 
                    footer: 'https://subscription.houstonchronicle.com/checkout/358/773/?origin=footer&ipid=sticksub&variant=election', 
                    inline: 'https://subscription.houstonchronicle.com/checkout/358/773/?origin=inline&variant=election', 
                    abandon: 'https://offers.houstonchronicle.com/?offerid=229&origin=adandon.sale&ipid=brand', 
                }; 
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                //turn all subscription. links into QA links 
            }

        }

        else if(document.URL.indexOf('expressnews.com') > -1 || document.URL.indexOf('mysanantonio.com') > -1) {
            flag = {
                enabled: true,
                value: 'Limited-Time Offer'
            }            
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywallInDMA: 'https://subscription.expressnews.com/checkout/202/501?origin=paywall.sale&ipid=sincere&siteID=SA_SAEN',
                    paywallOutDMA: 'https://subscription.expressnews.com/checkout/202/501?origin=paywall.sale&ipid=sincere',
                    paywall: 'https://subscription.expressnews.com/checkout/371/788/?origin=paywall&variant=election',
                    button: 'https://subscription.expressnews.com/checkout/370/788/?origin=button&ipid=election&variant=election',
                    buttonFree: 'https://subscription.expressnews.com/checkout/370/788/?origin=button.free&ipid=election&variant=election', 
                    meter: 'https://offers.expressnews.com/?offerid=232&origin=meter',
                    abandon: 'https://offers.expressnews.com/test/?offerid=74',
                    inline: 'https://subscription.expressnews.com/checkout/370/788/?origin=inline&variant=election',
                    footer: 'https://subscription.expressnews.com/checkout/370/788/?origin=footer&ipid=sticksub&variant=election'
                };    
            }
            else {
                market_links = {
                    paywallInDMA: 'https://subscription.expressnews.com/checkout/202/501?origin=paywall.sale&ipid=sincere&siteID=SA_SAEN',
                    paywallOutDMA: 'https://subscription.expressnews.com/checkout/202/501?origin=paywall.sale&ipid=sincere',
                    paywall: 'https://subscription.expressnews.com/checkout/371/788/?origin=paywall&variant=election',
                    button: 'https://subscription.expressnews.com/checkout/370/788/?origin=button&ipid=election&variant=election',
                    buttonFree: 'https://subscription.expressnews.com/checkout/370/788/?origin=button.free&ipid=election&variant=election', 
                    meter: 'https://offers.expressnews.com/?offerid=232&origin=meter',
                    abandon: 'https://offers.expressnews.com/test/?offerid=74',
                    inline: 'https://subscription.expressnews.com/checkout/370/788/?origin=inline&variant=election',
                    footer: 'https://subscription.expressnews.com/checkout/370/788/?origin=footer&ipid=sticksub&variant=election'
                }
            }
        }
        else if(document.URL.indexOf('sfchronicle.com') > -1) {
            campaign = 'Election Sale';
            flag = {
                enabled: true,
                value: 'Limited-Time Offer'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywallInDMA: 'https://subscription.sfchronicle.com/checkout/8/23/?origin=paywall&ipid=indma&variant=sincere',
                    paywallOutDMA: 'https://subscription.sfchronicle.com/checkout/8/23/?origin=paywall&ipid=outofdma&variant=sincere',
                    button: 'https://subscription.sfchronicle.com/checkout/429/865/?siteID=SFC&origin=button&variant=election',
                    abandon: 'https://offers.expressnews.com/test/?offerid=74',
                    inline: 'https://subscription.sfchronicle.com/checkout/429/865/?siteID=SFC&origin=inline&ipid=sticksub&variant=election',
                    footer: 'https://subscription.sfchronicle.com/checkout/429/865/?siteID=SFC&origin=footer&ipid=sticksub&variant=election',
                    paywall: 'https://subscription.sfchronicle.com/checkout/429/865/?siteID=SFC&origin=paywall&variant=election',
                    paywallHard: 'https://subscription.sfchronicle.com/checkout/429/865/?siteID=SFC&origin=paywall&ipid=hard&variant=election'
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywallInDMA: 'https://subscription.sfchronicle.com/checkout/8/23/?origin=paywall&ipid=indma&variant=sincere',
                    paywallOutDMA: 'https://subscription.sfchronicle.com/checkout/8/23/?origin=paywall&ipid=outofdma&variant=sincere',
                    button: 'https://subscription.sfchronicle.com/checkout/429/865/?siteID=SFC&origin=button&variant=election',
                    abandon: 'https://offers.expressnews.com/test/?offerid=74',
                    inline: 'https://subscription.sfchronicle.com/checkout/429/865/?siteID=SFC&origin=inline&ipid=sticksub&variant=election',
                    footer: 'https://subscription.sfchronicle.com/checkout/429/865/?siteID=SFC&origin=footer&ipid=sticksub&variant=election',
                    paywall: 'https://subscription.sfchronicle.com/checkout/429/865/?siteID=SFC&origin=paywall&variant=election',
                    paywallHard: 'https://subscription.sfchronicle.com/checkout/429/865/?siteID=SFC&origin=paywall&ipid=hard&variant=election'
                }
            }
        }
        else if(document.URL.indexOf('timesunion.com') > -1) {
            campaign = 'Election Sale';
            flag = {
                enabled: true,
                value: 'Limited-Time Offer'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywallInDMA: 'https://subscription.timesunion.com/checkout/337/730/?origin=paywall&ipid=indma?variant=sincere',
                    paywallOutDMA: 'https://subscription.timesunion.com/checkout/337/730/?origin=paywall&ipid=outofdma?variant=sincere',
                    paywall: 'https://subscription.timesunion.com/checkout/391/781/?origin=paywall&variant=election',
                    paywallHard: "https://subscription.timesunion.com/checkout/391/781/?origin=paywall&ipid=hard&variant=election",
                    button: 'https://subscription.timesunion.com/checkout/391/781/?origin=button&variant=election',
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywallInDMA: 'https://subscription.timesunion.com/checkout/337/730/?origin=paywall&ipid=indma?variant=sincere',
                    paywallOutDMA: 'https://subscription.timesunion.com/checkout/337/730/?origin=paywall&ipid=outofdma?variant=sincere',
                    paywall: 'https://subscription.timesunion.com/checkout/391/781/?origin=paywall&variant=election',
                    paywallHard: "https://subscription.timesunion.com/checkout/391/781/?origin=paywall&ipid=hard&variant=election",
                    button: 'https://subscription.timesunion.com/checkout/391/781/?origin=button&variant=election',
                }
            }
        }
        else if(document.URL.indexOf('ctpost') > -1) {
            campaign = 'Election Sale';
            flag = {
                enabled: true,
                value: 'Limited-Time Offer'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/402/834?siteid=CT_PO&origin=paywall.sale&variant=election.existingsite',
                    button: 'https://subscription.hearstmediact.com/checkout/402/834?siteid=CT_PO&origin=button&variant=election.existingsite',
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/402/834?siteid=CT_PO&origin=paywall.sale&variant=election.existingsite',
                    button: 'https://subscription.hearstmediact.com/checkout/402/834?siteid=CT_PO&origin=button&variant=election.existingsite',
                }
            }
        }
        else if(document.URL.indexOf('newstimes') > -1) {
            campaign = 'Election Sale';
            flag = {
                enabled: true,
                value: 'Limited-Time Offer'
            }
            if(document.URL.indexOf('cmf.qa') > -1){

                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/400/833?siteid=CT_NT&origin=paywall.sale&variant=election',
                    button: 'https://subscription.hearstmediact.com/checkout/400/833?siteid=CT_NT&origin=button&variant=election',
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/400/833?siteid=CT_NT&origin=paywall.sale&variant=election',
                    button: 'https://subscription.hearstmediact.com/checkout/400/833?siteid=CT_NT&origin=button&variant=election',
                }
            }
        }
        else if(document.URL.indexOf('stamfordadvocate') > -1) {
            campaign = 'Election Sale';
            flag = {
                enabled: true,
                value: 'Limited-Time Offer'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/392/826?siteid=CT_AD&origin=paywall.sale&variant=election',
                    button: 'https://subscription.hearstmediact.com/checkout/392/826?siteid=CT_AD&origin=button&variant=election',
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/392/826?siteid=CT_AD&origin=paywall.sale&variant=election',
                    button: 'https://subscription.hearstmediact.com/checkout/392/826?siteid=CT_AD&origin=button&variant=election',
                }
            }
        }
        else if(document.URL.indexOf('greenwichtime') > -1) {
            campaign = 'Election Sale';
            flag = {
                enabled: true,
                value: 'Limited-Time Offer'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/394/830?siteid=CT_GT&origin=paywall.sale&variant=election',
                    button: 'https://subscription.hearstmediact.com/checkout/394/830?siteid=CT_GT&origin=button&variant=election',
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/394/830?siteid=CT_GT&origin=paywall.sale&variant=election',
                    button: 'https://subscription.hearstmediact.com/checkout/394/830?siteid=CT_GT&origin=button&variant=election',
                }
            }
        }
        else if(document.URL.indexOf('thehour') > -1) {
            campaign = 'Election Sale';
            flag = {
                enabled: true,
                value: 'Limited-Time Offer'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/396/831?siteid=CT_HR&origin=paywall.sale&variant=election',
                    button: 'https://subscription.hearstmediact.com/checkout/396/831?siteid=CT_HR&origin=button&variant=election',
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/396/831?siteid=CT_HR&origin=paywall.sale&variant=election',
                    button: 'https://subscription.hearstmediact.com/checkout/396/831?siteid=CT_HR&origin=button&variant=election',
                }
            }
        }
        else if(document.URL.indexOf('nhregister') > -1) {
            campaign = 'Election Sale';
            flag = {
                enabled: true,
                value: 'Limited-Time Offer'
            }
            if(document.URL.indexOf('cmf.qa') > -1){
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/398/832?siteid=CT_NHR&origin=paywall.sale&variant=election',
                    button: 'https://subscription.hearstmediact.com/checkout/398/832?siteid=CT_NHR&origin=button&variant=election',
                };    
            }
            else {
                market_links = {
                    //for CASPER e2e testing
                    paywall: 'https://subscription.hearstmediact.com/checkout/398/832?siteid=CT_NHR&origin=paywall.sale&variant=election',
                    button: 'https://subscription.hearstmediact.com/checkout/398/832?siteid=CT_NHR&origin=button&variant=election',
                }
            }
        }
        //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 : 'https://hearst.blueconic.net/plugins/sub_links/ts_0dd2cee70cc4e52a7ae8d7fbc8e37f3a/'}]);})();(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 n=e[1].split(","),o=0;o<n.length;o++)s.push(n[o]);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"),n=s&&-1!==s.indexOf("bcToasterTemplate")?"_clean":"",o=this.getParameter("version"),r="";r=n||"3"!==o?"css/toaster"+n:"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 n=this;if(this._addContent(e,t),this._getNodeWithinToaster(".bcClose").click(function(){n._manuallyClosed=!0,n._hideToaster()}),this.emptyElementsWithAttribute(this._getToasterNode().get(0),"div","data-bc-external"),this.handleComplexElements(this._getToasterNode().get(0)),this.positionDivs(),this.isInEditMode)n._showToaster();else{var o=[],r=0,a=this.getParameter("triggerWhen");a?(r=100,o.push(this._convertWhenSettingPreviousToasterVersion(a))):(o=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<o.length;l++)switch(o[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(n);break;default:n._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(e){}},_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 n=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>"),o=this.getParameter("close_icon");"true"===this.getParameter("custom_close")&&o?n.removeClass("bcDefaultClose"):n.addClass("bcDefaultClose");try{n.appendTo(t("body"))}catch(e){this.isInEditMode&&console.error("Error caught: "+e)}},handleComplexElements:function(e){for(var t=this.getElementsWithAttribute(e,"div","data-bc-pluginid"),i=0;i<t.length;i++){var s=t[i],n=s.getAttribute("data-bc-pluginid"),o=s.getAttribute("data-bc-config");if(o)try{var r=o.replace(/\n/g,"\\\\n").replace(/\r/g,"\\\\r").replace(/\t/g,"\\\\t");o=this.blueConicClient.json.parse(r)}catch(e){o=null}this.blueConicClient.event.publish("bcComplexObject",{plugin:n,config:o,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),n=0,o=s.length;n<o;n++){s[n].innerHTML=""}},getElementsWithAttribute:function(e,t,i){for(var s=[],n=e.getElementsByTagName(t),o=0,r=n.length;o<r;o++){var a=n[o];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 n=this._getNodeWithinToaster(".bcToasterContent").get(0).getBoundingClientRect();if("left"===e||"right"===e){var o=window.innerHeight||document.documentElement.clientHeight,r=n.height||n.bottom-n.top;this._getToasterNode().css("top",Math.max((o-r)/2,0)+"px"),this._getToasterNode().css("left"===e?"left":"right",0)}else{var a=window.innerWidth||document.documentElement.clientWidth,c=n.width||n.right-n.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,n="",o=[];if(this._getShowClose()?this._getToasterNode().addClass("bcShowClose"):this._getToasterNode().removeClass("bcShowClose"),"true"===this.getParameter("custom_close")&&e){this._getToasterNode().removeClass("bcDefaultClose"),n+=".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")?(n+=r+"background-position: center center;background-size: contain;}",t&&(n+=a+"}")):(n+=r+"}",t?n+=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");n+=this._addClosePositionStyling(c,h);var l=this.getParameter("styling_css");l&&(this.stylingUrl=l,this.customCssUrls.push(l),o.push(l));var d=this.getParameter("styling_css_inline");d&&(n+=d.replace(/&#xd;/gi,"")),n&&(this.inlineCss=s("<style id='"+this.INLINE_CSS_ID_PREFIX+this._variantId+"'>"+n+"</style>"),this.inlineCss.appendTo(s("head"))),this._loadCss(o,i)},_loadCss:function(e,t){var i=(e=e||[]).length,s=0,n=[];if(this.errorList=null,void 0===t&&(t=function(){}),0===i)return t();function o(e){if(++s>=i)return n.length>0?t({message:"Error occured when loading the file "+e,error:n}):t()}e.forEach(function(e){if(document.querySelector('link[href="'+e+'"]'))o();else{var t=document.createElement("link");t.setAttribute("href",e),t.setAttribute("rel","stylesheet"),t.setAttribute("type","text/css"),t.onload=o,t.onerror=function(t){n.push(t),o(e)},document.head.appendChild(t)}})},_loadJs:function(e,t){var i=(e=e||[]).length,s=0,n=[];if(this.errorList=null,void 0===t&&(t=function(){}),0===i)return t();function o(e){if(++s>=i)return n.length>0?t({message:"Error occured when loading the file "+e,error:n}):t()}e.forEach(function(e){if(document.querySelector('script[src="'+e+'"]'))o();else{var t=document.createElement("script");t.setAttribute("src",e),t.setAttribute("type","text/javascript"),t.onload=o,t.onerror=function(t){n.push(t),o(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",n=this._getShowClose(),o="left"===s||"right"===s?i.width:i.height;this._setToasterEffect(!0,n,o),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 n=this.getParameter("click_event_selector");if(n){this.jQuery("body").one("click",n,this.jQuery.proxy(function(e){this.lastClickEvent&&this.lastClickEvent.originalEvent===e.originalEvent||this._logClickEvent(e)},this));try{this.jQuery(n).one("click",this.jQuery.proxy(function(e){this.lastClickEvent=e,this._logClickEvent(e)},this))}catch(e){}}this._setToasterEffect(!1,s);var o=t.getParameter("javascript");if(this.inlineJs=o,o&&!t.isInEditMode){o=o.replace(/(^|\W)blueConicVariantId(\W|$)/g,'$1"'+t.context.getInteractionId()+'"$2');var r=t.jQuery("<script>"+o+"<\/script>");try{r.appendTo(t.jQuery("body"))}catch(e){console.error(e)}}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={},n=this.getParameter("location")||"right",o=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[n]="-"+(i+o)+"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[n]="0px";var l=this._getNodeWithinToaster(".bcToasterContent").get(0).getBoundingClientRect(),d="left"===n||"right"===n?l.width:l.height;this._getToasterNode().css(n,"-"+(d+o)+"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 : ps + i + '/2.0.1/'},{ id : 'html', baseUrl : ps + 'html/1.0.10/'},{ id : 'image', baseUrl : ps + 'image/1.0.2/'},{ id : 'number', baseUrl : ps + 'number/1.0.2/'},{ id : 'string', baseUrl : ps + '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+'"]';this.jQuery(a).attr("data-bc-config",JSON.stringify(i)),n.length>0&&this.jQuery(a).attr("data-bc-preload",n.join(","));var r=this.jQuery(".bcComplexObject"+i.id)[0];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(t.metaDataFilters.filter(function(e){return e.property}).map(function(e){return e.property}))),e},[]):[]},_setUniqueId:function(e,t){var i="bcComplexObject"+t;this.jQuery(e).addClass(i)},_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;this.jQuery(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,t.proxy(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))},this)):i.resolve(this._getFallbackData("noStore",n)),i},_loadHTML:function(e,t){if(t){var i=this.jQuery,n=e.node,a=this._migration(e.config);this._handleStyling(a,t);var r=i('<div class="'+this._getWidthClass(n)+'" data-bc-external="true" data-bc-id="'+a.id+'"></div>');return this._getItems(a).then(i.proxy(function(e){return this._handleItems(e,a,t,r)},this))}},_handleItems:function(e,t,i,n){var a=this.jQuery;if(0!==e.length){var r=this._getDataObject(e,t.interactionId);this._renderTemplate(r,i,n);var s=this._addItemNodes(n,e,t);n.appendTo(s),this.blueConicClient.isInEditMode()||this._bindClicks(n,e[0].recommendationId,t),this._addImageErrorHandler(n,t),this._addJavaScript(i),this._addOnResizeHandler(a(".bcComplexObject"+t.id),n)}else a(".bcComplexObject"+t.id).empty()},_renderTemplate:function(e,t,i){if(e&&t&&window.Mustache){var n=t.getHtml().replace(/<img\s+src=(['"]{{image}}['"])/,"<img data-bc-src=$1"),a=window.Mustache.to_html(n,e);i.empty(),i.append(a),i.find("img[data-bc-src]").each(this.jQuery.proxy(function(e,t){var i=this.jQuery(t),n=i.attr("data-bc-src"),a=i.attr("width");isNaN(a)||(n+="&width="+a);var r=i.attr("height");isNaN(r)||(n+="&height="+r),i.attr("src",n),i.removeAttr("data-bc-src")},this))}},_addItemNodes:function(e,t,i){var n=this.jQuery(".bcComplexObject"+i.id);n.empty();for(var a=0;a<t.length;a++)if(t[a].ID&&t[a].URL)for(var r=e.find('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(e){console.error(e)}}},_addOnResizeHandler:function(e,t){var i=this.jQuery,n=e[0];i(window).resize(i.proxy(function(){if(e&&n&&t){for(var i=t.attr("class").split(" "),a="",r=0;r<i.length;r++)if(-1!==i[r].search("^bcp.*Width$")){a=i[r];break}var s=this._getWidthClass(n);a!==s&&(t.removeClass(a),t.addClass(s))}},this))},_addImageErrorHandler:function(e,t){(t=t||{}).settings=t.settings||{};var i=t.settings.storeId;e.get(0).addEventListener("error",this.jQuery.proxy(function(e){if("IMG"===e.target.tagName){var t=this.jQuery(e.target),n=t.attr("src");if(t.hide(),!n)return;var a=this.blueConicClient.getHostname();if(-1===n.indexOf(a+"/rest/contentStores/"+i+"/items/"))return;var r=t.closest("a[data-bc-item-id]");if(0===r.length)return;var s=r.attr("data-bc-item-id"),o=r.attr("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()})}},this),!0)},_getWidthClass:function(e){return e?e.clientWidth<=480?"bcpSmallWidth":e.clientWidth>=1024?"bcpMaxWidth":"bcpDefaultWidth":""},_getUrl:function(){return(this.jQuery('meta[property="og:url"]').attr("content")||this.jQuery('link[rel="canonical"]').attr("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||[],e.rules.filter(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;this.jQuery(e).find("a[data-bc-item-id]").each(this.jQuery.proxy(function(e,i){var s=this.jQuery(i);s.one("click",this.jQuery.proxy(function(e){e.preventDefault();var i=s.attr("href"),o=s.attr("target");o&&"_blank"===o&&window.open(i,o),this._handleEvent("click",i,s.data("bc-item-id"),n,r,t,a,o,e)},this))},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;i("."+n).remove();var a="";if(e&&e.getCss()){var r=i("<style>"+(a+=e.getCss())+"</style>");r.addClass(n),r.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;if(t("."+i).remove(),e.settings.styling.customCSS){var n=t("<style>"+e.settings.styling.customCSS+"</style>");n.addClass(i),n.appendTo(t("head"))}},_setCssUrl:function(e){(e=e||{}).settings=e.settings||{},e.settings.styling=e.settings.styling||{};var t=this.jQuery;if(!this.blueConicClient.isInEditMode&&e.settings.styling.cssURL)this.blueConicClient.util.loadCSS(e.settings.styling.cssURL);else{var i="bcCssUrl"+e.id;if(t("#"+i).remove(),e.settings.styling.cssURL)t("<link>",{id:i,rel:"stylesheet",type:"text/css",href:e.settings.styling.cssURL}).appendTo("head")}},_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: 'http://code.jquery.com/jquery-1.11.2.min.js', sharing: 'local'});a.push({url: p + i + '/2.2.0/frontend/src/node_modules/@blueconic/frontend-recommendations-rendering/lib/mustache-2.2.1.min.js', sharing: 'local'});a.push({url: p + i + '/2.2.0/frontend/src/node_modules/@blueconic/frontend-metadataservice/metaDataService.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/2.2.0/'}]);})();(function(){ var InteractionTypeImpl=InteractionType.extend({blueConicClient:null,context:null,profile:null,parameters:null,objectName:null,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:!1,_visitorSegmentIds:[],init:function(e,t){this.blueConicClient=e,this.context=t,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(),this.parameters=this._migrateParameters(this.parameters),this.objectName=this.parameters.trackerName&&this.parameters.trackerName[0]||this.DEFAULT_TRACKER_NAME,this._visitorSegmentIds=this._getVisitorSegmentIds(),this._goalParams=this._parseGoalParams(this.parameters.goalParameters),this._fillPreloadProperties()},_getVisitorSegmentIds:function(){return this.blueConicClient.getSegments().map(function(e){return e.id})||[]},_parseGoalParams:function(e){return e.map(function(e){return e&&this.blueConicClient.json.parse(e)},this).filter(function(e){return e&&e.active&&e.parameters}).map(function(e){return e.parameters.id=e.id,e.parameters.exportMapping=this._parseExportMapping(e.parameters.exportMapping),e.parameters},this)},_parseExportMapping:function(e){return(e&&this.blueConicClient.json.parse(e[0])||[]).filter(function(e){return this._isValidExportMapping(e)},this)},_isValidExportMapping:function(e){var t=e&&e.from&&e.to&&e.to.values&&e.to.values[0]&&e.to.values[0].id&&("property"!==e.from.typeId||e.from.values&&e.from.values[0]&&e.from.values[0].id);return Boolean(t)},_fillPreloadProperties:function(){this._preloadProperties=[this.SENT_TO_SYSTEM_PROPERTY,this.SENT_TO_CONNECTION_PROPERTY],this._goalParams.forEach(function(e){this._preloadProperties.push(this._LAST_PUSH_PROPERTY+"_"+e.id),this._preloadProperties.push(this._VARIABLE_STATE_PUSH_PROPERTY+"_"+e.id),e.exportMapping.forEach(function(e){var t=e.from&&"property"===e.from.typeId&&e.from.values&&e.from.values[0]&&e.from.values[0].id;t&&-1===this._preloadProperties.indexOf(t)&&this._preloadProperties.push(e.from.values[0].id)},this)},this)},getPreloadProperties:function(){return this._preloadProperties},onLoad:function(){this.bcConnectionUtil.md5Lib=window.md5;var e=this,t=0;(function i(){if(window[e.objectName])e._handleGoals();else{if(t>20)return;t++,window.setTimeout(i,250)}}).call(this)},_handleGoals:function(){this._goalParams.forEach(function(e){this._isSegmentValid(e.exportSegment)&&this._applyGoal(e)},this)},_isSegmentValid:function(e){var t=!e||0===e.length,i=e&&e[0]&&-1!==this._visitorSegmentIds.indexOf(e[0]);return t||i},_applyGoal:function(e){var t=this._createConnectionContext(e);this._pushProfileValues(e,t),e.triggerEvent&&e.triggerEvent[0]&&this.blueConicClient.event.subscribe(e.triggerEvent[0],this,function(){this._doPush(e,t)});var i=this._getEventNameForGoal(e),n=this._getTrackerNameForGoal(e);e.push_interactions&&"true"===e.push_interactions[0]&&this._subscribeToInteractionViews(n,i),e.passOnEvents&&"true"===e.passOnEvents[0]&&this._subscribeToPassOnEvents(n,i)},_pushProfileValues:function(e,t){this.bcConnectionUtil.doPush(t)?this._doPush(e,t):"plc"===t.push_frequency&&this.blueConicClient.event.subscribe(this.blueConicClient.event.onProfilePermissionChange,this,function(){this._doPush(e,t)})},_doPush:function(e,t){var i=e.exportMapping;if(0===i.length)return!1;var n={nonInteraction:1,userId:this.profile.getId()},s=!1;if(i.forEach(function(e){var i=this.bcConnectionUtil.getVariableValue(e.from,t,!0);i&&(n[e.to.values[0].id]=i.join(","),s=!0)},this),s){var r=this._getEventNameForGoal(e),o=this._getTrackerNameForGoal(e);this._pushUA(o,r,"Profile",n)}return s},_createConnectionContext:function(e){var t={LAST_PUSH_PROPERTY:this._LAST_PUSH_PROPERTY+"_"+e.id,VARIABLE_STATE_PUSH_PROPERTY:this._VARIABLE_STATE_PUSH_PROPERTY+"_"+e.id,profile:this.profile,push_frequency:e.push_frequency&&e.push_frequency[0]?e.push_frequency[0]:null,variables:i,SENT_TO_SYSTEM_PROPERTY:this.SENT_TO_SYSTEM_PROPERTY,SENT_TO_CONNECTION_PROPERTY:this.SENT_TO_CONNECTION_PROPERTY},i=[];return e.exportMapping.forEach(function(e){var n=e.from;this.bcConnectionUtil.getVariableValue(n,t)&&(n.key=e.to.values[0].id,i.push(n))}),t.variables=i,t},_getEventNameForGoal:function(e){return e.eventname&&e.eventname[0]||this.DEFAULT_EVENT_NAME},_getTrackerNameForGoal:function(e){return e.trackerName&&e.trackerName[0]?e.trackerName[0]+".":""},_subscribeToInteractionViews:function(e,t){this.blueConicClient.event.subscribe("VIEW",this,this._pushInteractionViews.bind(this,e,t))},_pushUA:function(e,t,i,n,s){window[this.objectName](e+"send","event",t,i,n,s),this._syncProperties()},_pushInteractionViews:function(e,t){this.blueConicClient.getInteractions().map(function(e){return e.variantName?e.name+" / "+e.variantName:e.name}).forEach(function(i){this._pushUA(e,t,"Interaction View",i,{nonInteraction:1,userId:this.profile.getId()})},this)},_subscribeToPassOnEvents:function(e,t){this.blueConicClient.event.subscribe("inactivity",this,this.onEventPublished.bind(this,e,t,"Inactivity")),this.blueConicClient.event.subscribe("exitintent",this,this.onEventPublished.bind(this,e,t,"Exit Intent")),this.blueConicClient.event.subscribe("cm_firstview",this,this.onEventPublished.bind(this,e,t,"Content Meter View 1")),this.blueConicClient.event.subscribe("cm_exceeded",this,this.onEventPublished.bind(this,e,t,"Content Meter View Content Meter Exceeded"));for(var i=2;i<10;i++)this.blueConicClient.event.subscribe("cm_view_"+i,this,function(i){var n=i.split("_")[2];this.onEventPublished(e,t,"Content Meter View "+n)})},onEventPublished:function(e,t,i){var n={nonInteraction:1,userId:this.profile.getId()};this._pushUA(e,t,i,n)},_syncProperties:function(){this._hasSynchronized||(this.bcConnectionUtil.setSyncProperties(this.context,this.profile,[this.SENT_TO_SYSTEM_PROPERTY,this.SENT_TO_CONNECTION_PROPERTY]),this._hasSynchronized=!0)},_migrateParameters:function(e){return e.goalParameters?e:this._migrateToV2(e)},_migrateToV2:function(e){var t=function(t,i){return e[t]||i},i=[],n=t("dimensions");(n&&n[0]?JSON.parse(n[0]):[]).forEach(function(e){var t={id:e.id,from:{type:"pm"===e.type?"permission":e.type,property:e.property,segments:e.segments,fieldLabel:"text"===e.type?e.text:void 0,fieldId:e.text},to:{type:"text",fieldLabel:"Dimension "+e.index,fieldId:"dimension"+e.index},mergeRule:"set"};i.push(t)});var s=t("profileproperties"),r={exportSegment:[""],exportMapping:[this.blueConicClient.json.stringify(i)],properties_out:Array.isArray(s)?s:[s],segments:[],push_frequency:t("push_frequency")||[""],triggerEvent:t("triggerEvent")||[""],eventname:[this.DEFAULT_EVENT_NAME],push_interactions:["true"],passOnEvents:["false"],saved:["true"]};return{trackerName:[t("custom_tracker")||this.DEFAULT_TRACKER_NAME],goalParameters:[JSON.stringify({id:"1",type:"export",name:"Export data into Universal Analytics",active:!0,parameters:r})]}}});var a = [];var i='uaconnection';a.push({url: p + i + '/1.3.2/frontend/src/node_modules/@blueconic/connection_lib/connection_lib.js', sharing: 'local'});a.push({url: p + i + '/1.3.2/frontend/src/lib/md5.min.js', sharing: 'local'});blueConic.fn.registerInteractionType(i, InteractionTypeImpl, a, [{ id : i, baseUrl : ps + i + '/1.3.2/'}]);})();(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 : 'https://hearst.blueconic.net/plugins/urllistenerinteractiontype_hearst/ts_81e3a5301a9dcbbcce5b0186a790881c/'}]);})();})(blueConicClient);