function _typeof(n){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(p){return typeof p}:function(p){return p&&"function"==typeof Symbol&&p.constructor===Symbol&&p!==Symbol.prototype?"symbol":typeof p})(n)} !function(n,p,D){function x(b,a){return _typeof(b)===a}function P(b){var a=y.className,c=f._config.classPrefix||"";if(F&&(a=a.baseVal),f._config.enableJSClass)a=a.replace(new RegExp("(^|\\s)"+c+"no-js(\\s|$)"),"$1"+c+"js$2");f._config.enableClasses&&(a+=" "+c+b.join(" "+c),F?y.className.baseVal=a:y.className=a)}function Q(b,a){if("object"==_typeof(b))for(var c in b)ca(b,c)&&Q(c,b[c]);else{c=(b=b.toLowerCase()).split(".");var g=f[c[0]];if(2==c.length&&(g=g[c[1]]),void 0!==g)return f;a="function"== typeof a?a():a;1==c.length?f[c[0]]=a:(!f[c[0]]||f[c[0]]instanceof Boolean||(f[c[0]]=new Boolean(f[c[0]])),f[c[0]][c[1]]=a);P([(a&&0!=a?"":"no-")+c.join("-")]);f._trigger(b,a)}return f}function B(b){return"function"!=typeof p.createElement?p.createElement(b):F?p.createElementNS.call(p,"http://www.w3.org/2000/svg",b):p.createElement.apply(p,arguments)}function R(b,a,c,g){var e,h,m,t,q=B("div"),u=((m=p.body)||((m=B(F?"svg":"body")).fake=!0),m);if(parseInt(c,10))for(;c--;)(m=B("div")).id=g?g[c]:"modernizr"+ (c+1),q.appendChild(m);return(e=B("style")).type="text/css",e.id="smodernizr",(u.fake?u:q).appendChild(e),u.appendChild(q),e.styleSheet?e.styleSheet.cssText=b:e.appendChild(p.createTextNode(b)),q.id="modernizr",u.fake&&(u.style.background="",u.style.overflow="hidden",t=y.style.overflow,y.style.overflow="hidden",y.appendChild(u)),h=a(q,b),u.fake?(u.parentNode.removeChild(u),y.style.overflow=t,y.offsetHeight):q.parentNode.removeChild(q),!!h}function da(b,a){return function(){return b.apply(a,arguments)}} function S(b){return b.replace(/([A-Z])/g,function(a,c){return"-"+c.toLowerCase()}).replace(/^ms-/,"-ms-")}function ea(b,a){var c=b.length;if("CSS"in n&&"supports"in n.CSS){for(;c--;)if(n.CSS.supports(S(b[c]),a))return!0;return!1}if("CSSSupportsRule"in n){for(var g=[];c--;)g.push("("+S(b[c])+":"+a+")");return R("@supports ("+(g=g.join(" or "))+") { #modernizr { position: absolute; } }",function(e){if("getComputedStyle"in n){e=getComputedStyle.call(n,e,null);var h=n.console;null!==e?e=e.getPropertyValue("position"): h&&h[h.error?"error":"log"].call(h,"getComputedStyle returning null, its possible modernizr test results are inaccurate")}else e=e.currentStyle&&e.currentStyle.position;return"absolute"==e})}return D}function T(b,a,c,g){function e(){q&&(delete z.style,delete z.modElem)}if(g=!x(g,"undefined")&&g,!x(c,"undefined")){var h=ea(b,c);if(!x(h,"undefined"))return h}var m,t;for(h=["modernizr","tspan","samp"];!z.style&&h.length;){var q=!0;z.modElem=B(h.shift());z.style=z.modElem.style}var u=b.length;for(h=0;h< u;h++)if(m=b[h],t=z.style[m],~(""+m).indexOf("-")&&(m=m.replace(/([a-z])-([a-z])/g,function(K,I,G){return I+G.toUpperCase()}).replace(/^-/,"")),z.style[m]!==D){if(g||x(c,"undefined"))return e(),"pfx"!=a||m;try{z.style[m]=c}catch(K){}if(z.style[m]!=t)return e(),"pfx"!=a||m}return e(),!1}function U(b,a,c,g,e){var h=b.charAt(0).toUpperCase()+b.slice(1),m=(b+" "+V.join(h+" ")+h).split(" ");if(x(a,"string")||x(a,"undefined"))a=T(m,a,g,e);else a:{b=(b+" "+W.join(h+" ")+h).split(" ");var t,q;for(q in b)if(b[q]in a){a=!1===c?b[q]:x(t=a[b[q]],"function")?da(t,c||a):t;break a}a=!1}return a}function L(b,a,c){return U(b,D,D,a,c)}var X=[],H=[],r={_version:"3.6.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(b,a){var c=this;setTimeout(function(){a(c[b])},0)},addTest:function(b,a,c){H.push({name:b,fn:a,options:c})},addAsyncTest:function(b){H.push({name:null,fn:b})}},f=function(){};f.prototype=r;(f=new f).addTest("geolocation","geolocation"in navigator);var Y=r._config.usePrefixes? " -webkit- -moz- -o- -ms- ".split(" "):["",""];r._prefixes=Y;var y=p.documentElement,F="svg"===y.nodeName.toLowerCase();F||function(b,a){function c(){var d=C.elements;return"string"==typeof d?d.split(" "):d}function g(d){var k=Z[d[I]];return k||(k={},G++,d[I]=G,Z[G]=k),k}function e(d,k,l){return k=k||a,t?k.createElement(d):!(A=(l=l||g(k)).cache[d]?l.cache[d].cloneNode():K.test(d)?(l.cache[d]=l.createElem(d)).cloneNode():l.createElem(d)).canHaveChildren||u.test(d)||A.tagUrn?A:l.frag.appendChild(A); var A}function h(d){var k,l,A,M,w=g(d=d||a);return!C.shivCSS||m||w.hasCSS||(w.hasCSS=(A=(l=d).createElement("p"),M=l.getElementsByTagName("head")[0]||l.documentElement,A.innerHTML="x\x3cstyle\x3earticle,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}\x3c/style\x3e",!!M.insertBefore(A.lastChild,M.firstChild))),t||(k=d,w.cache||(w.cache={},w.createElem=k.createElement,w.createFrag=k.createDocumentFragment,w.frag= w.createFrag()),k.createElement=function(E){return C.shivMethods?e(E,k,w):w.createElem(E)},k.createDocumentFragment=Function("h,f","return function(){var n\x3df.cloneNode(),c\x3dn.createElement;h.shivMethods\x26\x26("+c().join().replace(/[\w\-:]+/g,function(E){return w.createElem(E),w.frag.createElement(E),'c("'+E+'")'})+");return n}")(C,w.frag)),d}var m,t,q=b.html5||{},u=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,K=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i, I="_html5shiv",G=0,Z={};!function(){try{var d=a.createElement("a");d.innerHTML="\x3cxyz\x3e\x3c/xyz\x3e";m="hidden"in d;var k;if(!(k=1==d.childNodes.length)){a.createElement("a");var l=a.createDocumentFragment();k=void 0===l.cloneNode||void 0===l.createDocumentFragment||void 0===l.createElement}t=k}catch(A){t=m=!0}}();var C={elements:q.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video", version:"3.7.3",shivCSS:!1!==q.shivCSS,supportsUnknownElements:t,shivMethods:!1!==q.shivMethods,type:"default",shivDocument:h,createElement:e,createDocumentFragment:function(d,k){if(d=d||a,t)return d.createDocumentFragment();d=(k||g(d)).frag.cloneNode();k=0;for(var l=c(),A=l.length;kieVersion}),Modernizr.addTest("ie9",function(){return 9===ieVersion}),Modernizr.addTest("ie10", function(){return 10===ieVersion}),Modernizr.addTest("ie11",function(){return 11===ieVersion}),Modernizr.addTest("ie12",function(){return 12===ieVersion}))};/* jQuery JavaScript Library v1.12.4-aem http://jquery.com/ Includes Sizzle.js http://sizzlejs.com/ Copyright jQuery Foundation and other contributors Released under the MIT license http://jquery.org/license Date: 2016-05-20T17:17Z Sizzle CSS Selector Engine v2.2.1 http://sizzlejs.com/ Copyright jQuery Foundation and other contributors Released under the MIT license http://jquery.org/license Date: 2015-10-17 */ (function(B,ya){"object"===typeof module&&"object"===typeof module.exports?module.exports=B.document?ya(B,!0):function(za){if(!za.document)throw Error("jQuery requires a window with a document");return ya(za)}:ya(B)})("undefined"!==typeof window?window:this,function(B,ya){function za(a){var b=!!a&&"length"in a&&a.length,d=c.type(a);return"function"===d||c.isWindow(a)?!1:"array"===d||0===b||"number"===typeof b&&0b;b+=2)"margin"===d&&(g+=c.css(a,d+Ga[b],!0,f)),e?("content"===d&&(g-=c.css(a,"padding"+Ga[b],!0,f)),"margin"!==d&&(g-=c.css(a,"border"+Ga[b]+"Width",!0,f))):(g+=c.css(a, "padding"+Ga[b],!0,f),"padding"!==d&&(g+=c.css(a,"border"+Ga[b]+"Width",!0,f)));return g}function oc(a,b,d){var e=!0,f="width"===b?a.offsetWidth:a.offsetHeight,g=Oa(a),k=y.boxSizing&&"border-box"===c.css(a,"boxSizing",!1,g);if(0>=f||null==f){f=Ha(a,b,g);if(0>f||null==f)f=a.style[b];if(db.test(f))return f;e=k&&(y.boxSizingReliable()||f===a.style[b]);f=parseFloat(f)||0}return f+nc(a,b,d||(k?"border":"content"),e,g)+"px"}function ha(a,b,d,e,f){return new ha.prototype.init(a,b,d,e,f)}function pc(){B.setTimeout(function(){Pa= void 0});return Pa=c.now()}function eb(a,b){var d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b){var f=Ga[e];d["margin"+f]=d["padding"+f]=a}b&&(d.opacity=d.width=a);return d}function qc(a,b,d){for(var e,f=(ma.tweeners[b]||[]).concat(ma.tweeners["*"]),g=0,k=f.length;gt&&A)return q;k.resolveWith(a,[p]);return!1},p=k.promise({elem:a,props:c.extend({},b),opts:c.extend(!0,{specialEasing:{},easing:c.easing._default},d),originalProperties:b, originalOptions:d,startTime:Pa||pc(),duration:d.duration,tweens:[],createTween:function(q,t){q=c.Tween(a,p.opts,q,t,p.opts.specialEasing[q]||p.opts.easing);p.tweens.push(q);return q},stop:function(q){var t=0,v=q?p.tweens.length:0;if(e)return this;for(e=!0;ta?this[a+this.length]:this[a]:Ca.call(this)}, pushStack:function(a){a=c.merge(this.constructor(),a);a.prevObject=this;a.context=this.context;return a},each:function(a){return c.each(this,a)},map:function(a){return this.pushStack(c.map(this,function(b,d){return a.call(b,d,b)}))},slice:function(){return this.pushStack(Ca.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length;a=+a+(0>a?b:0);return this.pushStack(0<=a&&ad?Math.max(0,e+d):d:0;dP.cacheLength&&delete h[n.shift()];return h[l+" "]=r}var n=[];return h}function e(h){h[M]=!0;return h}function f(h){var n=G.createElement("div");try{return!!h(n)}catch(l){return!1}finally{n.parentNode&&n.parentNode.removeChild(n)}}function g(h,n){h=h.split("|");for(var l=h.length;l--;)P.attrHandle[h[l]]=n}function k(h,n){var l=n&&h,r=l&&1===h.nodeType&&1===n.nodeType&&(~n.sourceIndex||-2147483648)-(~h.sourceIndex||-2147483648);if(r)return r;if(l)for(;l=l.nextSibling;)if(l===n)return-1; return h?1:-1}function m(h){return function(n){return"input"===n.nodeName.toLowerCase()&&n.type===h}}function p(h){return function(n){var l=n.nodeName.toLowerCase();return("input"===l||"button"===l)&&n.type===h}}function q(h){return e(function(n){n=+n;return e(function(l,r){for(var u,x=h([],l.length,n),w=x.length;w--;)l[u=x[w]]&&(l[u]=!(r[u]=l[u]))})})}function t(h){return h&&"undefined"!==typeof h.getElementsByTagName&&h}function v(){}function A(h){for(var n=0,l=h.length,r="";n+~]|[\x20\t\r\n\f])[\x20\t\r\n\f]*/,pd=/=[\x20\t\r\n\f]*([^\]'"]*?)[\x20\t\r\n\f]*\]/g,qd=/:((?:\\.|[\w-]|[^\x00-\xa0])+)(?:\((('((?:\\.|[^\\'])*)'|"((?:\\.|[^\\"])*)")|((?:\\.|[^\\()[\]]|\[[\x20\t\r\n\f]*((?:\\.|[\w-]|[^\x00-\xa0])+)(?:[\x20\t\r\n\f]*([*^$|!~]?=)[\x20\t\r\n\f]*(?:'((?:\\.|[^\\'])*)'|"((?:\\.|[^\\"])*)"|((?:\\.|[\w-]|[^\x00-\xa0])+))|)[\x20\t\r\n\f]*\])*)|.*)\)|)/, wc=/^(?:\\.|[\w-]|[^\x00-\xa0])+$/,kb={ID:/^#((?:\\.|[\w-]|[^\x00-\xa0])+)/,CLASS:/^\.((?:\\.|[\w-]|[^\x00-\xa0])+)/,TAG:/^((?:\\.|[\w-]|[^\x00-\xa0])+|[*])/,ATTR:/^\[[\x20\t\r\n\f]*((?:\\.|[\w-]|[^\x00-\xa0])+)(?:[\x20\t\r\n\f]*([*^$|!~]?=)[\x20\t\r\n\f]*(?:'((?:\\.|[^\\'])*)'|"((?:\\.|[^\\"])*)"|((?:\\.|[\w-]|[^\x00-\xa0])+))|)[\x20\t\r\n\f]*\]/,PSEUDO:/^:((?:\\.|[\w-]|[^\x00-\xa0])+)(?:\((('((?:\\.|[^\\'])*)'|"((?:\\.|[^\\"])*)")|((?:\\.|[^\\()[\]]|\[[\x20\t\r\n\f]*((?:\\.|[\w-]|[^\x00-\xa0])+)(?:[\x20\t\r\n\f]*([*^$|!~]?=)[\x20\t\r\n\f]*(?:'((?:\\.|[^\\'])*)'|"((?:\\.|[^\\"])*)"|((?:\\.|[\w-]|[^\x00-\xa0])+))|)[\x20\t\r\n\f]*\])*)|.*)\)|)/, CHILD:/^:(only|first|last|nth|nth-last)-(child|of-type)(?:\([\x20\t\r\n\f]*(even|odd|(([+-]|)(\d*)n|)[\x20\t\r\n\f]*(?:([+-]|)[\x20\t\r\n\f]*(\d+)|))[\x20\t\r\n\f]*\)|)/i,bool:/^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i,needsContext:/^[\x20\t\r\n\f]*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\([\x20\t\r\n\f]*((?:-\d)?\d*)[\x20\t\r\n\f]*\)|)(?=[^-]|$)/i},rd=/^(?:input|select|textarea|button)$/i,sd=/^h\d$/i,$a= /^[^{]+\{\s*\[native \w/,hd=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,Cb=/[+~]/,id=/'|\\/g,va=/\\([\da-f]{1,6}[\x20\t\r\n\f]?|([\x20\t\r\n\f])|.)/ig,wa=function(h,n,l){h="0x"+n-65536;return h!==h||l?n:0>h?String.fromCharCode(h+65536):String.fromCharCode(h>>10|55296,h&1023|56320)},yc=function(){Ja()};try{Da.apply(ua=xc.call(O.childNodes),O.childNodes),ua[O.childNodes.length].nodeType}catch(h){Da={apply:ua.length?function(n,l){ld.apply(n,xc.call(l))}:function(n,l){for(var r=n.length,u=0;n[r++]=l[u++];);n.length= r-1}}}var S=b.support={};var td=b.isXML=function(h){return(h=h&&(h.ownerDocument||h).documentElement)?"HTML"!==h.nodeName:!1};var Ja=b.setDocument=function(h){var n;h=h?h.ownerDocument||h:O;if(h===G||9!==h.nodeType||!h.documentElement)return G;G=h;W=G.documentElement;R=!td(G);(n=G.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",yc,!1):n.attachEvent&&n.attachEvent("onunload",yc));S.attributes=f(function(l){l.className="i";return!l.getAttribute("className")});S.getElementsByTagName= f(function(l){l.appendChild(G.createComment(""));return!l.getElementsByTagName("*").length});S.getElementsByClassName=$a.test(G.getElementsByClassName);S.getById=f(function(l){W.appendChild(l).id=M;return!G.getElementsByName||!G.getElementsByName(M).length});S.getById?(P.find.ID=function(l,r){if("undefined"!==typeof r.getElementById&&R)return(l=r.getElementById(l))?[l]:[]},P.filter.ID=function(l){var r=l.replace(va,wa);return function(u){return u.getAttribute("id")===r}}):(delete P.find.ID,P.filter.ID= function(l){var r=l.replace(va,wa);return function(u){return(u="undefined"!==typeof u.getAttributeNode&&u.getAttributeNode("id"))&&u.value===r}});P.find.TAG=S.getElementsByTagName?function(l,r){if("undefined"!==typeof r.getElementsByTagName)return r.getElementsByTagName(l);if(S.qsa)return r.querySelectorAll(l)}:function(l,r){var u=[],x=0;r=r.getElementsByTagName(l);if("*"===l){for(;l=r[x++];)1===l.nodeType&&u.push(l);return u}return r};P.find.CLASS=S.getElementsByClassName&&function(l,r){if("undefined"!== typeof r.getElementsByClassName&&R)return r.getElementsByClassName(l)};aa=[];N=[];if(S.qsa=$a.test(G.querySelectorAll))f(function(l){W.appendChild(l).innerHTML="\x3ca id\x3d'"+M+"'\x3e\x3c/a\x3e\x3cselect id\x3d'"+M+"-\r\\' msallowcapture\x3d''\x3e\x3coption selected\x3d''\x3e\x3c/option\x3e\x3c/select\x3e";l.querySelectorAll("[msallowcapture^\x3d'']").length&&N.push("[*^$]\x3d[\\x20\\t\\r\\n\\f]*(?:''|\"\")");l.querySelectorAll("[selected]").length||N.push("\\[[\\x20\\t\\r\\n\\f]*(?:value|checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)"); l.querySelectorAll("[id~\x3d"+M+"-]").length||N.push("~\x3d");l.querySelectorAll(":checked").length||N.push(":checked");l.querySelectorAll("a#"+M+"+*").length||N.push(".#.+[+~]")}),f(function(l){var r=G.createElement("input");r.setAttribute("type","hidden");l.appendChild(r).setAttribute("name","D");l.querySelectorAll("[name\x3dd]").length&&N.push("name[\\x20\\t\\r\\n\\f]*[*^$|!~]?\x3d");l.querySelectorAll(":enabled").length||N.push(":enabled",":disabled");l.querySelectorAll("*,:x");N.push(",.*:")}); (S.matchesSelector=$a.test(da=W.matches||W.webkitMatchesSelector||W.mozMatchesSelector||W.oMatchesSelector||W.msMatchesSelector))&&f(function(l){S.disconnectedMatch=da.call(l,"div");da.call(l,"[s!\x3d'']:x");aa.push("!\x3d",":((?:\\\\.|[\\w-]|[^\\x00-\\xa0])+)(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|\\[[\\x20\\t\\r\\n\\f]*((?:\\\\.|[\\w-]|[^\\x00-\\xa0])+)(?:[\\x20\\t\\r\\n\\f]*([*^$|!~]?\x3d)[\\x20\\t\\r\\n\\f]*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|((?:\\\\.|[\\w-]|[^\\x00-\\xa0])+))|)[\\x20\\t\\r\\n\\f]*\\])*)|.*)\\)|)")}); N=N.length&&new RegExp(N.join("|"));aa=aa.length&&new RegExp(aa.join("|"));la=(n=$a.test(W.compareDocumentPosition))||$a.test(W.contains)?function(l,r){var u=9===l.nodeType?l.documentElement:l;r=r&&r.parentNode;return l===r||!!(r&&1===r.nodeType&&(u.contains?u.contains(r):l.compareDocumentPosition&&l.compareDocumentPosition(r)&16))}:function(l,r){if(r)for(;r=r.parentNode;)if(r===l)return!0;return!1};Ra=n?function(l,r){if(l===r)return U=!0,0;var u=!l.compareDocumentPosition-!r.compareDocumentPosition; if(u)return u;u=(l.ownerDocument||l)===(r.ownerDocument||r)?l.compareDocumentPosition(r):1;return u&1||!S.sortDetached&&r.compareDocumentPosition(l)===u?l===G||l.ownerDocument===O&&la(O,l)?-1:r===G||r.ownerDocument===O&&la(O,r)?1:J?Ka(J,l)-Ka(J,r):0:u&4?-1:1}:function(l,r){if(l===r)return U=!0,0;var u=0,x=l.parentNode,w=r.parentNode,D=[l],z=[r];if(!x||!w)return l===G?-1:r===G?1:x?-1:w?1:J?Ka(J,l)-Ka(J,r):0;if(x===w)return k(l,r);for(;l=l.parentNode;)D.unshift(l);for(l=r;l=l.parentNode;)z.unshift(l); for(;D[u]===z[u];)u++;return u?k(D[u],z[u]):D[u]===O?-1:z[u]===O?1:0};return G};b.matches=function(h,n){return b(h,null,null,n)};b.matchesSelector=function(h,n){(h.ownerDocument||h)!==G&&Ja(h);n=n.replace(pd,"\x3d'$1']");if(!(!S.matchesSelector||!R||ba[n+" "]||aa&&aa.test(n)||N&&N.test(n)))try{var l=da.call(h,n);if(l||S.disconnectedMatch||h.document&&11!==h.document.nodeType)return l}catch(r){}return 0h.nodeType)return!1;return!0},parent:function(h){return!P.pseudos.empty(h)},header:function(h){return sd.test(h.nodeName)}, input:function(h){return rd.test(h.nodeName)},button:function(h){var n=h.nodeName.toLowerCase();return"input"===n&&"button"===h.type||"button"===n},text:function(h){var n;return"input"===h.nodeName.toLowerCase()&&"text"===h.type&&(null==(n=h.getAttribute("type"))||"text"===n.toLowerCase())},first:q(function(){return[0]}),last:q(function(h,n){return[n-1]}),eq:q(function(h,n,l){return[0>l?l+n:l]}),even:q(function(h,n){for(var l=0;ll?l+n:l;0<=--n;)h.push(n);return h}),gt:q(function(h,n,l){for(l=0>l?l+n:l;++l(?:<\/\1>|)$/, Rc=/^.[^:#\[\.,]*$/;c.filter=function(a,b,d){var e=b[0];d&&(a=":not("+a+")");return 1===b.length&&1===e.nodeType?c.find.matchesSelector(e,a)?[e]:[]:c.find.matches(a,c.grep(b,function(f){return 1===f.nodeType}))};c.fn.extend({find:function(a){var b,d=[],e=this,f=e.length;if("string"!==typeof a)return this.pushStack(c(a).filter(function(){for(b=0;b)[^>]*|#([\w-]*))$/;(c.fn.init=function(a,b,d){if(!a)return this;d=d||Dc;if("string"===typeof a){var e="\x3c"===a.charAt(0)&&"\x3e"===a.charAt(a.length-1)&&3<=a.length?[null,a,null]:ud.exec(a);if(!e||!e[1]&&b)return!b||b.jquery?(b||d).find(a):this.constructor(b).find(a); if(e[1]){if(b=b instanceof c?b[0]:b,c.merge(this,c.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:C,!0)),Cc.test(e[1])&&c.isPlainObject(b))for(e in b)if(c.isFunction(this[e]))this[e](b[e]);else this.attr(e,b[e])}else{if((b=C.getElementById(e[2]))&&b.parentNode){if(b.id!==e[2])return Dc.find(a);this.length=1;this[0]=b}this.context=C;this.selector=a}return this}if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(c.isFunction(a))return"undefined"!==typeof d.ready?d.ready(a):a(c);void 0!== a.selector&&(this.selector=a.selector,this.context=a.context);return c.makeArray(a,this)}).prototype=c.fn;var Dc=c(C);var vd=/^(?:parents|prev(?:Until|All))/,wd={children:!0,contents:!0,next:!0,prev:!0};c.fn.extend({has:function(a){var b,d=c(a,this),e=d.length;return this.filter(function(){for(b=0;b d.nodeType&&(k?-1m.indexOf(":")&&"on"+m;a=a[c.expando]?a:new c.Event(m,"object"===typeof a&&a);a.isTrigger=e?2:3;a.namespace=p.join(".");a.rnamespace=a.namespace?new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+ "(\\.|$)"):null;a.result=void 0;a.target||(a.target=d);b=null==b?[a]:c.makeArray(b,[a]);p=c.event.special[m]||{};if(e||!p.trigger||!1!==p.trigger.apply(d,b)){if(!e&&!p.noBubble&&!c.isWindow(d)){var v=p.delegateType||m;Ec.test(v+m)||(q=q.parentNode);for(;q;q=q.parentNode)k.push(q),f=q;f===(d.ownerDocument||C)&&k.push(f.defaultView||f.parentWindow||B)}for(g=0;(q=k[g++])&&!a.isPropagationStopped();)a.type=1a.button))for(;g!=this;g=g.parentNode||this)if(1===g.nodeType&&(!0!==g.disabled||"click"!==a.type)){var k=[];for(d=0;d]/i, Bd=/\s*$/g,Hb=Vb(C).appendChild(C.createElement("div"));c.extend({htmlPrefilter:function(a){return a},clone:function(a,b,d){var e,f,g=c.contains(a.ownerDocument,a);if(y.html5Clone||c.isXMLDoc(a)||!Gc.test("\x3c"+a.nodeName+"\x3e"))var k=a.cloneNode(!0);else Hb.innerHTML=a.outerHTML,Hb.removeChild(k=Hb.firstChild);if(!(y.noCloneEvent&&y.noCloneChecked||1!==a.nodeType&&11!==a.nodeType|| c.isXMLDoc(a))){var m=ea(k);var p=ea(a);for(f=0;null!=(e=p[f]);++f)if(m[f]){var q=void 0,t=e,v=m[f];if(1===v.nodeType){var A=v.nodeName.toLowerCase();if(!y.noCloneEvent&&v[c.expando]){e=c._data(v);for(q in e.events)c.removeEvent(v,q,e.handle);v.removeAttribute(c.expando)}if("script"===A&&v.text!==t.text)bc(v).text=t.text,cc(v);else if("object"===A)v.parentNode&&(v.outerHTML=t.outerHTML),y.html5Clone&&t.innerHTML&&!c.trim(v.innerHTML)&&(v.innerHTML=t.innerHTML);else if("input"===A&&tb.test(t.type))v.defaultChecked= v.checked=t.checked,v.value!==t.value&&(v.value=t.value);else if("option"===A)v.defaultSelected=v.selected=t.defaultSelected;else if("input"===A||"textarea"===A)v.defaultValue=t.defaultValue}}}if(b)if(d)for(p=p||ea(a),m=m||ea(k),f=0;null!=(e=p[f]);f++)dc(e,m[f]);else dc(a,k);m=ea(k,"script");0c.inArray(this,a)&&(c.cleanData(ea(this)),d&&d.replaceChild(b,this))},a)}});c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"}, function(a,b){c.fn[a]=function(d){for(var e=0,f=[],g=c(d),k=g.length-1;e<=k;e++)d=e===k?this:this.clone(!0),c(g[e])[b](d),Bb.apply(f,d.get());return this.pushStack(f)}});var Ya,hc={HTML:"block",BODY:"block"},Hc=/^margin/,db=new RegExp("^("+Fb+")(?!px)[a-z%]+$","i"),Ib=function(a,b,d,e){var f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];d=d.apply(a,e||[]);for(f in b)a.style[f]=g[f];return d},Ic=C.documentElement;(function(){function a(){var q=C.documentElement;q.appendChild(m);p.style.cssText="-webkit-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%"; b=e=k=!1;d=g=!0;if(B.getComputedStyle){var t=B.getComputedStyle(p);b="1%"!==(t||{}).top;k="2px"===(t||{}).marginLeft;e="4px"===(t||{width:"4px"}).width;p.style.marginRight="50%";d="4px"===(t||{marginRight:"4px"}).marginRight;t=p.appendChild(C.createElement("div"));t.style.cssText=p.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0";t.style.marginRight=t.style.width="0";p.style.width="1px";g=!parseFloat((B.getComputedStyle(t)|| {}).marginRight);p.removeChild(t)}p.style.display="none";if(f=0===p.getClientRects().length)if(p.style.display="",p.innerHTML="\x3ctable\x3e\x3ctr\x3e\x3ctd\x3e\x3c/td\x3e\x3ctd\x3et\x3c/td\x3e\x3c/tr\x3e\x3c/table\x3e",p.childNodes[0].style.borderCollapse="separate",t=p.getElementsByTagName("td"),t[0].style.cssText="margin:0;border:0;padding:0;display:none",f=0===t[0].offsetHeight)t[0].style.display="",t[1].style.display="none",f=0===t[0].offsetHeight;q.removeChild(m)}var b,d,e,f,g,k,m=C.createElement("div"), p=C.createElement("div");p.style&&(p.style.cssText="float:left;opacity:.5",y.opacity="0.5"===p.style.opacity,y.cssFloat=!!p.style.cssFloat,p.style.backgroundClip="content-box",p.cloneNode(!0).style.backgroundClip="",y.clearCloneStyle="content-box"===p.style.backgroundClip,m=C.createElement("div"),m.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",p.innerHTML="",m.appendChild(p),y.boxSizing=""===p.style.boxSizing||""===p.style.MozBoxSizing|| ""===p.style.WebkitBoxSizing,c.extend(y,{reliableHiddenOffsets:function(){null==b&&a();return f},boxSizingReliable:function(){null==b&&a();return e},pixelMarginRight:function(){null==b&&a();return d},pixelPosition:function(){null==b&&a();return b},reliableMarginRight:function(){null==b&&a();return g},reliableMarginLeft:function(){null==b&&a();return k}}))})();var Cd=/^(top|right|bottom|left)$/;if(B.getComputedStyle){var Oa=function(a){var b=a.ownerDocument.defaultView;b&&b.opener||(b=B);return b.getComputedStyle(a)}; var Ha=function(a,b,d){var e=a.style;var f=(d=d||Oa(a))?d.getPropertyValue(b)||d[b]:void 0;""!==f&&void 0!==f||c.contains(a.ownerDocument,a)||(f=c.style(a,b));if(d&&!y.pixelMarginRight()&&db.test(f)&&Hc.test(b)){a=e.width;b=e.minWidth;var g=e.maxWidth;e.minWidth=e.maxWidth=e.width=f;f=d.width;e.width=a;e.minWidth=b;e.maxWidth=g}return void 0===f?f:f+""}}else Ic.currentStyle&&(Oa=function(a){return a.currentStyle},Ha=function(a,b,d){var e,f,g=a.style;var k=(d=d||Oa(a))?d[b]:void 0;null==k&&g&&g[b]&& (k=g[b]);if(db.test(k)&&!Cd.test(b)){d=g.left;if(f=(e=a.runtimeStyle)&&e.left)e.left=a.currentStyle.left;g.left="fontSize"===b?"1em":k;k=g.pixelLeft+"px";g.left=d;f&&(e.left=f)}return void 0===k?k:k+""||"auto"});var Jb=/alpha\([^)]*\)/i,Dd=/opacity\s*=\s*([^)]*)/i,Ed=/^(none|table(?!-c[ea]).+)/,Zc=new RegExp("^("+Fb+")(.*)$","i"),Fd={position:"absolute",visibility:"hidden",display:"block"},Jc={letterSpacing:"0",fontWeight:"400"},kc=["Webkit","O","Moz","ms"],jc=C.createElement("div").style;c.extend({cssHooks:{opacity:{get:function(a, b){if(b)return a=Ha(a,"opacity"),""===a?"1":a}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":y.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var f,g=c.camelCase(b),k=a.style;b=c.cssProps[g]||(c.cssProps[g]=ic(g)||g);var m=c.cssHooks[b]||c.cssHooks[g];if(void 0!==d){var p=typeof d;"string"=== p&&(f=rb.exec(d))&&f[1]&&(d=Ub(a,b,f),p="number");if(null!=d&&d===d&&("number"===p&&(d+=f&&f[3]||(c.cssNumber[g]?"":"px")),y.clearCloneStyle||""!==d||0!==b.indexOf("background")||(k[b]="inherit"),!(m&&"set"in m)||void 0!==(d=m.set(a,d,e))))try{k[b]=d}catch(q){}}else return m&&"get"in m&&void 0!==(f=m.get(a,!1,e))?f:k[b]}},css:function(a,b,d,e){var f;var g=c.camelCase(b);b=c.cssProps[g]||(c.cssProps[g]=ic(g)||g);(g=c.cssHooks[b]||c.cssHooks[g])&&"get"in g&&(f=g.get(a,!0,d));void 0===f&&(f=Ha(a,b,e)); "normal"===f&&b in Jc&&(f=Jc[b]);return""===d||d?(a=parseFloat(f),!0===d||isFinite(a)?a||0:f):f}});c.each(["height","width"],function(a,b){c.cssHooks[b]={get:function(d,e,f){if(e)return Ed.test(c.css(d,"display"))&&0===d.offsetWidth?Ib(d,Fd,function(){return oc(d,b,f)}):oc(d,b,f)},set:function(d,e,f){var g=f&&Oa(d);return mc(d,e,f?nc(d,b,f,y.boxSizing&&"border-box"===c.css(d,"boxSizing",!1,g),g):0)}}});y.opacity||(c.cssHooks.opacity={get:function(a,b){return Dd.test((b&&a.currentStyle?a.currentStyle.filter: a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var d=a.style;a=a.currentStyle;var e=c.isNumeric(b)?"alpha(opacity\x3d"+100*b+")":"",f=a&&a.filter||d.filter||"";d.zoom=1;if((1<=b||""===b)&&""===c.trim(f.replace(Jb,""))&&d.removeAttribute&&(d.removeAttribute("filter"),""===b||a&&!a.filter))return;d.filter=Jb.test(f)?f.replace(Jb,e):f+" "+e}});c.cssHooks.marginRight=wb(y.reliableMarginRight,function(a,b){if(b)return Ib(a,{display:"inline-block"},Ha,[a,"marginRight"])}); c.cssHooks.marginLeft=wb(y.reliableMarginLeft,function(a,b){if(b)return(parseFloat(Ha(a,"marginLeft"))||(c.contains(a.ownerDocument,a)?a.getBoundingClientRect().left-Ib(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}):0))+"px"});c.each({margin:"",padding:"",border:"Width"},function(a,b){c.cssHooks[a+b]={expand:function(d){var e=0,f={};for(d="string"===typeof d?d.split(" "):[d];4>e;e++)f[a+Ga[e]+b]=d[e]||d[e-2]||d[0];return f}};Hc.test(a)||(c.cssHooks[a+b].set=mc)});c.fn.extend({css:function(a, b){return Ea(this,function(d,e,f){var g,k={},m=0;if(c.isArray(e)){f=Oa(d);for(g=e.length;me)?null:[],g=a?e+1:d.length,k=0>e?g:a?e:0;ke.indexOf(" "+f+" ")&&(e+=f+" ");e=c.trim(e);m!==e&&c.attr(d,"class",e)}}return this},removeClass:function(a){var b, d,e,f,g,k=0;if(c.isFunction(a))return this.each(function(p){c(this).removeClass(a.call(this,p,Ia(this)))});if(!arguments.length)return this.attr("class","");if("string"===typeof a&&a)for(b=a.match(qa)||[];d=this[k++];){var m=Ia(d);if(e=1===d.nodeType&&(" "+m+" ").replace(Lb," ")){for(g=0;f=b[g++];)for(;-1J||304===J;if(G){var N=q;for(var aa=I,da,la,M,O,Y=N.contents,na=N.dataTypes;"*"===na[0];)na.shift(),void 0===la&&(la=N.mimeType||aa.getResponseHeader("Content-Type"));if(la)for(O in Y)if(Y[O]&&Y[O].test(la)){na.unshift(O);break}if(na[0]in G)M=na[0];else{for(O in G){if(!na[0]|| N.converters[O+" "+na[0]]){M=O;break}da||(da=O)}M=M||da}M?(M!==na[0]&&na.unshift(M),N=G[M]):N=void 0}a:{G=q;da=N;la=I;M=W;var La;aa={};Y=G.dataTypes.slice();if(Y[1])for(ba in G.converters)aa[ba.toLowerCase()]=G.converters[ba];for(O=Y.shift();O;){G.responseFields[O]&&(la[G.responseFields[O]]=da);!sa&&M&&G.dataFilter&&(da=G.dataFilter(da,G.dataType));var sa=O;if(O=Y.shift())if("*"===O)O=sa;else if("*"!==sa&&sa!==O){var ba=aa[sa+" "+O]||aa["* "+O];if(!ba)for(La in aa)if(N=La.split(" "),N[1]===O&&(ba= aa[sa+" "+N[0]]||aa["* "+N[0]])){!0===ba?ba=aa[La]:!0!==aa[La]&&(O=N[0],Y.unshift(N[1]));break}if(!0!==ba)if(ba&&G["throws"])da=ba(da);else try{da=ba(da)}catch(ua){N={state:"parsererror",error:ba?ua:"No conversion from "+sa+" to "+O};break a}}}N={state:"success",data:da}}if(W)if(q.ifModified&&((R=I.getResponseHeader("Last-Modified"))&&(c.lastModified[ca]=R),(R=I.getResponseHeader("etag"))&&(c.etag[ca]=R)),204===J||"HEAD"===q.type)R="nocontent";else if(304===J)R="notmodified";else{R=N.state;var Ra= N.data;var Sa=N.error;W=!Sa}else if(Sa=R,J||!R)R="error",0>J&&(J=0);I.status=J;I.statusText=(U||R)+"";W?A.resolveWith(t,[Ra,R,I]):A.rejectWith(t,[I,R,Sa]);I.statusCode(L);L=void 0;k&&v.trigger(W?"ajaxSuccess":"ajaxError",[I,q,W?Ra:Sa]);Q.fireWith(t,[I,R]);k&&(v.trigger("ajaxComplete",[I,q]),--c.active||c.event.trigger("ajaxStop"))}}"object"===typeof a&&(b=a,a=void 0);b=b||{};var e,f,g,k,m,p,q=c.ajaxSetup({},b),t=q.context||q,v=q.context&&(t.nodeType||t.jquery)?c(t):c.event,A=c.Deferred(),Q=c.Callbacks("once memory"), L=q.statusCode||{},ja={},ia={},fa=0,jb="canceled",I={readyState:0,getResponseHeader:function(J){var U;if(2===fa){if(!p)for(p={};U=Qd.exec(f);)p[U[1].toLowerCase()]=U[2];U=p[J.toLowerCase()]}return null==U?null:U},getAllResponseHeaders:function(){return 2===fa?f:null},setRequestHeader:function(J,U){var G=J.toLowerCase();fa||(J=ia[G]=ia[G]||J,ja[J]=U);return this},overrideMimeType:function(J){fa||(q.mimeType=J);return this},statusCode:function(J){var U;if(J)if(2>fa)for(U in J)L[U]=[L[U],J[U]];else I.always(J[I.status]); return this},abort:function(J){J=J||jb;m&&m.abort(J);d(0,J);return this}};A.promise(I).complete=Q.add;I.success=I.done;I.error=I.fail;q.url=((a||q.url||Ob)+"").replace(Pd,"").replace(Sd,Va[1]+"//");q.type=b.method||b.type||q.method||q.type;q.dataTypes=c.trim(q.dataType||"*").toLowerCase().match(qa)||[""];null==q.crossDomain&&(a=Lc.exec(q.url.toLowerCase()),q.crossDomain=!(!a||a[1]===Va[1]&&a[2]===Va[2]&&(a[3]||("http:"===a[1]?"80":"443"))===(Va[3]||("http:"===Va[1]?"80":"443"))));q.data&&q.processData&& "string"!==typeof q.data&&(q.data=c.param(q.data,q.traditional));sc(Mc,q,b,I);if(2===fa)return I;(k=c.event&&q.global)&&0===c.active++&&c.event.trigger("ajaxStart");q.type=q.type.toUpperCase();q.hasContent=!Rd.test(q.type);var ca=q.url;q.hasContent||(q.data&&(ca=q.url+=(Nb.test(ca)?"\x26":"?")+q.data,delete q.data),!1===q.cache&&(q.url=Kc.test(ca)?ca.replace(Kc,"$1_\x3d"+Mb++):ca+(Nb.test(ca)?"\x26":"?")+"_\x3d"+Mb++));q.ifModified&&(c.lastModified[ca]&&I.setRequestHeader("If-Modified-Since",c.lastModified[ca]), c.etag[ca]&&I.setRequestHeader("If-None-Match",c.etag[ca]));(q.data&&q.hasContent&&!1!==q.contentType||b.contentType)&&I.setRequestHeader("Content-Type",q.contentType);I.setRequestHeader("Accept",q.dataTypes[0]&&q.accepts[q.dataTypes[0]]?q.accepts[q.dataTypes[0]]+("*"!==q.dataTypes[0]?", "+Nc+"; q\x3d0.01":""):q.accepts["*"]);for(e in q.headers)I.setRequestHeader(e,q.headers[e]);if(q.beforeSend&&(!1===q.beforeSend.call(t,I,q)||2===fa))return I.abort();jb="abort";for(e in{success:1,error:1,complete:1})I[e](q[e]); if(m=sc(xb,q,b,I)){I.readyState=1;k&&v.trigger("ajaxSend",[I,q]);if(2===fa)return I;q.async&&0fa)d(-1,J);else throw J;}}else d(-1,"No Transport");return I},getJSON:function(a,b,d){return c.get(a,b,d,"json")},getScript:function(a,b){return c.get(a,void 0,b,"script")}});c.each(["get","post"],function(a,b){c[b]=function(d,e,f,g){c.isFunction(e)&&(g=g||f,f=e,e=void 0);return c.ajax(c.extend({url:d, type:b,dataType:g,data:e,success:f},c.isPlainObject(d)&&d))}});c._evalUrl=function(a){return c.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})};c.fn.extend({wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&1===d.firstChild.nodeType;)d=d.firstChild;return d}).append(this)}return this}, wrapInner:function(a){return c.isFunction(a)?this.each(function(b){c(this).wrapInner(a.call(this,b))}):this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){var b=c.isFunction(a);return this.each(function(d){c(this).wrapAll(b?a.call(this,d):a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()}});c.expr.filters.hidden=function(a){return y.reliableHiddenOffsets()?0>=a.offsetWidth&& 0>=a.offsetHeight&&!a.getClientRects().length:ad(a)};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)};var Td=/%20/g,bd=/\[\]$/,Oc=/\r?\n/g,Ud=/^(?:submit|button|image|reset|file)$/i,Vd=/^(?:input|select|textarea|keygen)/i;c.param=function(a,b){var d,e=[],f=function(g,k){k=c.isFunction(k)?k():null==k?"":k;e[e.length]=encodeURIComponent(g)+"\x3d"+encodeURIComponent(k)};void 0===b&&(b=c.ajaxSettings&&c.ajaxSettings.traditional);if(c.isArray(a)||a.jquery&&!c.isPlainObject(a))c.each(a, function(){f(this.name,this.value)});else for(d in a)zb(d,a[d],b,f);return e.join("\x26").replace(Td,"+")};c.fn.extend({serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=c.prop(this,"elements");return a?c.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!c(this).is(":disabled")&&Vd.test(this.nodeName)&&!Ud.test(a)&&(this.checked||!tb.test(a))}).map(function(a,b){a=c(this).val();return null==a?null:c.isArray(a)? c.map(a,function(d){return{name:b.name,value:d.replace(Oc,"\r\n")}}):{name:b.name,value:a.replace(Oc,"\r\n")}}).get()}});c.ajaxSettings.xhr=void 0!==B.ActiveXObject?function(){return this.isLocal?tc():8B.indexOf("compatible")&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(B)||[];return{browser:B[1]||"",version:B[2]||"0"}}; jQuery.browser||(matched=jQuery.uaMatch(navigator.userAgent),browser={},matched.browser&&(browser[matched.browser]=!0,browser.version=matched.version),browser.chrome?browser.webkit=!0:browser.webkit&&(browser.safari=!0),jQuery.browser=browser); (function(B){function ya(pa){var Aa=window.document.implementation.createHTMLDocument("");Aa.body.innerHTML=pa;return Aa.body&&Aa.body.innerHTML}var za=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,Wa=B.htmlPrefilter;B.htmlPrefilter=function(pa){var Aa=pa.replace(za,"\x3c$1\x3e\x3c/$2\x3e");Aa!==pa&&ya(pa)!==ya(Aa)&&console.error("HTML tags must be properly nested and closed: "+pa);return Wa(pa)}})(window.jQuery);(function(d){"object"===typeof module&&module.exports?module.exports=d():(window.Granite=window.Granite||{}).Sling=d()})(function(){return{SELECTOR_INFINITY:".infinity",CHARSET:"_charset_",STATUS:":status",STATUS_BROWSER:"browser",OPERATION:":operation",OPERATION_DELETE:"delete",OPERATION_MOVE:"move",DELETE_SUFFIX:"@Delete",TYPEHINT_SUFFIX:"@TypeHint",COPY_SUFFIX:"@CopyFrom",MOVE_SUFFIX:"@MoveFrom",ORDER:":order",REPLACE:":replace",DESTINATION:":dest",SAVE_PARAM_PREFIX:":saveParamPrefix",IGNORE_PARAM:":ignore", REQUEST_LOGIN_PARAM:"sling:authRequestLogin",LOGIN_URL:"/system/sling/login.html",LOGOUT_URL:"/system/sling/logout.html"}}); (function(d){"object"===typeof module&&module.exports?module.exports=d():(window.Granite=window.Granite||{}).Util=d()})(function(){return{patchText:function(d,h){if(h)if("[object Array]"!==Object.prototype.toString.call(h))d=d.replace("{0}",h);else for(var f=0;fe&&(e=b.indexOf("-"));if(0>e){var l=b;e=null}else l=b.substring(0,e),e=b.substring(e+1); return{code:b,language:l,country:e}};return c}()}); (function(d){"object"===typeof module&&module.exports?module.exports=d():(window.Granite=window.Granite||{}).TouchIndicator=d()})(function(){var d={},h=[];return{debugWithMouse:!1,init:function(){var f=this,m=function(g){f.update(g.touches);return!0};document.addEventListener("touchstart",m);document.addEventListener("touchmove",m);document.addEventListener("touchend",m);this.debugWithMouse&&document.addEventListener("mousemove",function(g){g.identifer="fake";f.update([g]);return!0})},update:function(f){for(var m= {},g=0;g>>0;if(typeof predicate!=="function")throw TypeError("predicate must be a function");var thisArg=arguments[1];var k=0;while(k=t.length?{done:!0}:{done:!1,value:t[e++]}},e:function(t){throw t;},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var r,o,a=!0,i=!1;return{s:function(){r=t[Symbol.iterator]()}, n:function(){var t=r.next();return a=t.done,t},e:function(t){i=!0,o=t},f:function(){try{a||null==r.return||r.return()}finally{if(i)throw o;}}}}function _unsupportedIterableToArray(t,e){if(t){if("string"==typeof t)return _arrayLikeToArray(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(n):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(t,e):void 0}} function _arrayLikeToArray(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n>>0,r>>>=0,o=Array(i);++an.length-1?[]:n.slice(0,t.index).map(function(t){return y(t)})}}function s(t){var e="The following item cannot be handled by the data layer because it does not have a valid format: "+JSON.stringify(t.config);console.error(e)}return function(){Array.isArray(e.dataLayer)|| (e.dataLayer=[]);r=e.dataLayer.splice(0,e.dataLayer.length),(n=e.dataLayer).version=c,o={},f=h(a)}(),n.push=function(t){var n=arguments,r=arguments;if(Object.keys(n).forEach(function(t){var e=y(n[t]);switch(e.valid||(s(e),delete r[t]),e.type){case v.itemType.DATA:case v.itemType.EVENT:u(e);break;case v.itemType.FCTN:delete r[t],u(e);break;case v.itemType.LISTENER_ON:case v.itemType.LISTENER_OFF:delete r[t]}}),r[0])return Array.prototype.push.apply(this,r)},n.getState=function(t){return t?p(l(o),t): l(o)},n.addEventListener=function(t,e,n){u(y({on:t,handler:e,scope:n&&n.scope,path:n&&n.path}))},n.removeEventListener=function(t,e){u(y({off:t,handler:e}))},function(){for(var t=0;t=e.length?{"done":!0}:{"done":!1,"value":e[a++]}},"e":function(e){throw e},"f":t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var r;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(r="Object"===(r={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:r)||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{var t,r=0;if(e&&0<(null==(t=e.cards)?void 0:t.length)){var n,o=_createForOfIteratorHelper(e.cards);try{for(o.s();!(n=o.n()).done;){var a=n.value;a&&!a.viewed&&r++}}catch(e){o.e(e)}finally{o.f()}}return r})(e),document.cookie="inboxUnreadCount=".concat(r,";"),document.cookie="inboxExpiration=".concat(Number(Date.now())+9e5,";"));var b=r,A=document.getElementsByClassName("inbox-uxdia-c-dropdown--inbox"),e=document.getElementsByClassName("inbox-uxdia-c-unread-count");if(!(b<=0||0==A.length||0'.concat(b,"")}catch(e){y.e(e)}finally{y.f()}e=document.querySelectorAll(".aarp-c-linked-dropdown--header .aarp-c-linked-dropdown__dropdown .aarp-c-linked-dropdown__main-text");if(e&&0'.concat(b,"")}catch(e){f.e(e)}finally{f.f()}}A=document.querySelectorAll(".aarp-c-linked-dropdown--header .aarp-c-linked-dropdown"),e=(A&&0d?l(b):b.stopPropagation())}},f||(document.addEventListener("touchmove",l,k?{passive:!1}: void 0),f=!0)):function(b){if(void 0===h){var d=window.innerWidth-document.documentElement.clientWidth;b&&!0===b.reserveScrollBarGap&&0=a&&.2<=a?b="Expected":.2>a&&(b="LowScore");return b}};AARP.StayingSharp.utils.scrollToTop=function(){window.scrollTo({top:0,behavior:"smooth"})}; AARP.StayingSharp.utils.getOldPillarName=function(a){switch(a){case "ongoing_exercise":return"move";case "engage_your_brain":return"discover";case "manage_stress":return"relax";case "eat_right":return"nourish";case "be_social":return"connect";case "restorative_sleep":return"restorative_sleep"}};AARP.StayingSharp.utils.dateDifference=function(a){a=new Date(a);return new Date(a.setMinutes(a.getMinutes()-a.getTimezoneOffset()))}; AARP.StayingSharp.utils.formatDate=function(a){var b="en"===AARP.StayingSharp.locale?"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "):"Ene Feb Mar Abr May Jun Jul Ago Sept Oct Nov Dic".split(" "),c=new Date(a.replace(/-/g,"/").split(".")[0]);c=AARP.StayingSharp.utils.dateDifference(c);a=c.getDate();b=b[c.getMonth()];c=c.getFullYear();var d=new Date;(new Date(d)).setDate(d.getDate()-1);return b+" "+(10>a?"0"+a:a)+", "+c}; AARP.StayingSharp.utils.hyphenDateFormat=function(a){var b=a.getFullYear(),c=(a.getMonth()+1).toLocaleString("en-US",{minimumIntegerDigits:2});a=a.getDate().toLocaleString("en-US",{minimumIntegerDigits:2});return b+"-"+c+"-"+a};AARP.StayingSharp.utils.slashDateFormat=function(a){var b=new Date(a);a=b.getFullYear();var c=(1+b.getMonth()).toString().padStart(2,"0");b=b.getDate().toString().padStart(2,"0");return c+"/"+b+"/"+a};AARP.StayingSharp.utils.not=function(a){return!a}; AARP.StayingSharp.utils.isValidScore=function(a){return"undefined"!=typeof a&&"number"==typeof a&&10>=a&&0<=a};AARP.StayingSharp.utils.formatNumber=function(a,b){b=b?b:1;return Number(Math.round(a+"e"+b)+"e-"+b).toString()};AARP.StayingSharp.utils.titleCase=function(a){a=a.replace(/_/g," ");a=(a=a.replace(/-/g," "))&&a.toLowerCase().split(" ");for(var b=0;bh.length)k=h.length;for(var n=0,x=Array(k);n{var n;function k(e){for(var e=e.detail.xfURL.replace(/(^"|"$)/g,"").replace(/\\/g,""),t=document.createElement("div"),n=(t.innerHTML=e,document.querySelector(".cmp-experiencefragment--mega-menu")),a=t.getElementsByTagName("script"),l=a.length-1;0<=l;l--)a[l].parentNode.removeChild(a[l]);n.insertAdjacentElement("afterend",t);(n=document.createElement("div")).innerHTML=e;for(var r,o=n.getElementsByTagName("script"),c=0;c { document.querySelector('main')?.querySelectorAll('[tabindex="0"], a, button, iframe, input').forEach((ele) => { // check if the parent of the ele is not the paywall container class then add the tabindex -1 if (!ele.closest(`.${paywallClassName}`) && !ele.closest('.ssHeader')) { ele.setAttribute('tabindex', "-1"); } }); } // The "ms" parameter determines the aarp membership status which can be any of the following values: // 1 = Non member // 0 = Active member // 5 = Expired member // 4 = Cancelled member // M = Suspended member (member requested suspend) // U = Suspended member (undeliverable address suspend) // D = Suspended member (deceased member suspend) const checkMSStatus = (callback, ssNotActivated, paywallClass) => { let authUser = AARP && AARP.cookies ? AARP.cookies.at : null, msAuthUser = authUser ? authUser.ms : null; if (ssNotActivated) { showPaywallFlag = true; scrollHandling(true, callback, paywallClass); callback(showPaywallFlag); } else { if (!authUser) { showPaywallFlag = true; scrollHandling(true, callback, paywallClass); callback(showPaywallFlag); } else if (msAuthUser) { switch (msAuthUser) { case '1': case '5': case '4': case 'M': case 'U': case 'D': showPaywallFlag = true; scrollHandling(true, callback, paywallClass); callback(showPaywallFlag); break; default: scrollHandling(false, callback, paywallClass); break; } } else { scrollHandling(false, callback, paywallClass); } } } /** * @function validateAuthorization checks the membership status * @param callback function to be executed based on membership status */ const validateAuthorization = function (callback, isSS, ssNotActivated, paywallClass) { if (isSS) { checkMSStatus(callback, ssNotActivated, paywallClass); } else { const isMoaAttr = document.querySelectorAll('.cmp-experiencefragment--paywall')[0]; if (isMoaAttr?.getAttribute("data-cmp-membersonlyaccess") === 'true' || isMoaAttr?.getAttribute("data-cmp-membersonlyaccess") === true) { checkMSStatus(callback); } else { scrollHandling(false, callback, paywallClass); } } } /** * @function createMemberShipURL Method to return membership url with active page URL referrer * @param membershipURL membership URL string */ const createMemberShipURL = (membershipURL) => { if (!membershipURL.includes('referrer')) { const seperator = membershipURL.includes('?') ? '&' : '?'; return `${membershipURL}${seperator}referrer=${window.location.href}` } return membershipURL; }; /** * @function createLoginLinkUrl method to return login link * @param href login link String * */ const createLoginLinkUrl = function (href) { const urlObj = window.location, isLowerPubEnv = (/www-pi|www-hw|www-d|www-s|www-ta|nowapp-s|nowapp-pi|nowapp-d|stayingsharp-l.aarp.org|www-cg/g).test(urlObj.hostname), isAARPInstance = isLowerPubEnv || (/www|nowapp/g).test(urlObj.hostname); const getUrlVars = (url) => { const vars = {}; if (url == undefined) { url = window.location.href; } const parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, (m, key, value) => { vars[key] = value; }); return vars; }; if (isAARPInstance) { let redirectUri = urlObj.origin + '/aarp/auth/callback'; let clientId = (isLowerPubEnv) ? '0oakgt9j4hwrtHWUl0h7' : '0oa3rtsa6ahTQReOG2p7'; let scope = 'bui+bmi+openid'; let responseType = 'code'; let state = encodeURIComponent(window.location.href); const urlParams = getUrlVars(href); if (urlParams['referrer']) { state = urlParams['referrer']; } else if (urlParams['state']) { state = urlParams['state']; } href += href.indexOf('?') > -1 ? '&' : '?'; href += `response_type=${responseType}&client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}`; if (window.location.pathname.indexOf('rewards/') < 0) { href += `&state=${state}`; } return href; } else { return href; } } /** * @function showPaywall trigger paywall modal * @param showPaywallcallback callback function executed after paywall is shown * @param authorizationCallback callback function after user is validated */ const showPaywall = (showPaywallcallback, authorizationCallback, isSS = false, ssNotActivated = false, paywallClass = 'uxdia-c-featured-article__paywall-wrapper') => { validateAuthorization(authorizationCallback, isSS, ssNotActivated, paywallClass); if (isSS) { showPaywallComponent(showPaywallcallback, paywallClass); } else { const authUser = AARP && AARP.cookies ? AARP.cookies.at : null; if (!authUser) { showPaywallComponent(showPaywallcallback); } AARP?.Externals?.ContextHub.onLoad(() => { window?.ContextHub?.Utils?.Eventing()?.on( window.ContextHub.Constants.EVENT_TEASER_LOADED, () => { showPaywallComponent(showPaywallcallback); }, 'paywall-article', true); }); } } /** * @function updateLoginlink Updates the login link in the paywall modal * If the button href contains membership Url create MembershipLink * If button href contains login create login Link */ const updateLoginlink = (paywallClassName = 'uxdia-c-featured-article__paywall-wrapper') => { let paywallXf = document.querySelectorAll('.cmp-experiencefragment--paywall')[0]; const paywallContainer = paywallXf?.querySelector(`.${paywallClassName}`); // changing href attrbiute of login link in paywall using js let paywallLinks = paywallContainer?.querySelectorAll('.uxdia-c-featured-article__paywall-btn, .login-signup-link'); paywallLinks?.forEach((link) => { if (link && link.href && (link.href.includes('/membershipChallenge/showChallengeForm') || link.href.includes('user/register') || link.href.includes('/mem/join') || link.href.includes('/membershipChallenge/connectMembership') && !link.href.includes('referrer'))) { link.href = createMemberShipURL(link.href); } else if (link && link.href && link.href.includes('/applications/user/login') && !link.href.includes('redirect_uri=') && !link.classList.contains('auth-params-added')) { link.href = createLoginLinkUrl(link.href); } }); } return { scrollHandling, createLoginLinkUrl, addAccessbility, validateAuthorization, createMemberShipURL, updateLoginlink, showPaywallComponent, showPaywall }; }(); AARP = AARP || {}; AARP.uxdia = AARP.uxdia || {}; AARP.uxdia.uxdiaPaywall = (() => { const init = () => { let bodyWrapperscroll = document.querySelector('.aarp-c-body-wrapper'); let paywallXf = document.querySelectorAll('.cmp-experiencefragment--paywall')[0]; if (bodyWrapperscroll?.classList.contains('aarp-o-edit-mode-false') && bodyWrapperscroll?.classList.contains('uxdia-c-paywall-enabled')) { let paywallContainer = ''; // Below functions contains the old character deletion logic if free-access access container exeeds allowed number of characters const teaseArticle = () => { let charCountAttr = document.querySelectorAll('.cmp-experiencefragment--paywall')[0]?.getAttribute("data-cmp-paywall-teasingcount"), teasingCharValue = charCountAttr ? charCountAttr : 500, textNodes = document.querySelectorAll('.uxdia-c-free-access .articlecontentfragment.contentfragment.uxdia-article-body'), allParentNodeslisticlev2 = document.querySelectorAll('.uxdia-u-base-article-v2 .uxdia-c-listicle-item__container'), listArticleContentTable = document.querySelector('.uxdia-c-listicle-table-of-contents__container'), pDOM = textNodes[0]?.querySelector('div.cmp-contentfragment'), innerMostNodes = pDOM?.getElementsByTagName("div")[2]?.children, counter = 0, totLengthFromEachTextNode = 0; const totlengthForTeasing = teasingCharValue; for (let k = 0; k < innerMostNodes?.length; k++) { if (innerMostNodes[k].tagName == 'P' || innerMostNodes[k].tagName == 'H2' || innerMostNodes[k].tagName == 'H3' || innerMostNodes[k].tagName == 'H4' || innerMostNodes[k].tagName == 'H5' || innerMostNodes[k].tagName == 'H6' || innerMostNodes[k].tagName == 'OL') { if (totLengthFromEachTextNode + innerMostNodes[k].textContent.length > totlengthForTeasing) { innerMostNodes[k].innerHTML = innerMostNodes[k].innerHTML.slice(0, totlengthForTeasing - totLengthFromEachTextNode); break; } else { innerMostNodes[k].innerHTML = innerMostNodes[k].innerHTML.slice(0); totLengthFromEachTextNode = totLengthFromEachTextNode + innerMostNodes[k].textContent.length; counter++; } } else { innerMostNodes[k].innerHTML = innerMostNodes[k].innerHTML.slice(0); counter++; } } for (let j = innerMostNodes?.length - 1; j > counter + 1; j--) { innerMostNodes[j]?.remove(); } /* Handling ListicleV2 template for article-body and length */ if (listArticleContentTable && allParentNodeslisticlev2) { if (innerMostNodes && innerMostNodes[0]?.textContent?.length) { listArticleContentTable.remove(); for (let i = 0; i < allParentNodeslisticlev2?.length; i++) { allParentNodeslisticlev2[i]?.remove(); } } } } // this function will delete all the div's with restricted access or allow authorized users to see the content const paywallRestrictedEle = (paywallEnabled) => { let restrictedDivs = document.querySelectorAll('.uxdia-c-restricted-access'); if (paywallEnabled) { paywallXf && bodyWrapperscroll?.appendChild(paywallXf); teaseArticle(); restrictedDivs?.forEach(payWallEle => { payWallEle.remove(); }); // below three lines might be removed after BE changes for providing the restricted access class on XFs after article body document.querySelector('.uxdia-c-member-benefits-carousel')?.remove(); document.querySelector('.uxdia-o-comments-container')?.remove(); document.querySelector('footer')?.remove(); } else { restrictedDivs?.forEach(payWallEle => { payWallEle.classList.add('uxdia-c-paywall-accessed'); }); } } const updateDesc = () => { paywallContainer = paywallXf?.querySelector('.uxdia-c-featured-article__paywall-wrapper'); let paywallDesc = paywallContainer.querySelector('.uxdia-c-featured-article__paywall-wrapper__disc'); paywallDesc && (paywallDesc.innerHTML = paywallDesc.innerHTML.trim()); } if(document.querySelector('.uxdia-c-featured-article__paywall-wrapper')?.dataset?.paywall) { AARP.Everywhere.Paywall.showPaywall(updateDesc, paywallRestrictedEle); } } } init(); return { init: init } })(); (function(){window.AARP=window.AARP||{};AARP.Everywhere=AARP.Everywhere||{};window.isMobile=function(){var a=!1,b=navigator.userAgent||navigator.vendor||window.opera;if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(b)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(b.substr(0, 4)))a=!0;return a};AARP.Everywhere.isDeviceMobile=window.isMobile();var d=function(){var a=document.querySelectorAll("[hide-aarp-elements\x3dtrue]");a&&a.forEach(function(b){return null===b||void 0===b?void 0:b.classList.add("aarp-u-hidden@mobile")})},e=function(){var a=sessionStorage.getItem("aarpWebView");a?d():a||(a=window.parent.location.href,a=(a=/[?&]EXP=([^&#]*)/i.exec(a?a:window.location.href))?a[1]:null,"staying_sharp_app"!==a&&"aarp_now"!==a)||(sessionStorage.setItem("aarpWebView",!0),d())}, f=function(a){a&&a.forEach(function(b){null===b||void 0===b?void 0:b.setAttribute("hide-aarp-elements","true")})};if(isMobile()){var c,g=null===(c=document.querySelector(".aarp-c-header"))||void 0===c?void 0:c.closest(".experiencefragment");c=document.querySelector(".aarp-c-footer--uxdia");f([g,c]);e()}})();"use strict"; var _document$getElementB, _Granite, _Granite2; var localeInfo = (_document$getElementB = document.getElementById('uxdiaLocale')) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.getAttribute('content'); (_Granite = Granite) === null || _Granite === void 0 ? void 0 : _Granite.I18n.setLocale(localeInfo); (_Granite2 = Granite) === null || _Granite2 === void 0 ? void 0 : _Granite2.I18n.setUrlPrefix('/etc.clientlibs/uxdia/i18n/resources/');(function(c,d,e){var f=document.querySelector(".uxdia-c-series--link"),g=document.querySelector(".uxdia-c-seriesList--close"),a=document.querySelector(".uxdia-c-series__overlay"),b=document.querySelector(".seriesList"),h=null===(c=window)||void 0===c?void 0:null===(d=c.location)||void 0===d?void 0:d.pathname;f&&f.addEventListener("click",function(){null===b||void 0===b?void 0:b.classList.add("uxdia-c-seriesDrawer");null===a||void 0===a?void 0:a.classList.add("uxdia-c-series__overlay-show");document.querySelector("html").classList.add("aarp-c-modal--open")}); g&&g.addEventListener("click",function(){null===b||void 0===b?void 0:b.classList.remove("uxdia-c-seriesDrawer");null===a||void 0===a?void 0:a.classList.add("uxdia-c-series__overlay-show");document.querySelector("html").classList.remove("aarp-c-modal--open")});null===(e=document.querySelector('a[href\x3d "'.concat(h,'"].uxdia-c-series__card-link')))||void 0===e?void 0:e.classList.add("uxdia-c-series__card-active")})();((t,e)=>{function j(){o&&window.cancelAnimationFrame(o),o=window.requestAnimationFrame(function(){var t,s;void 0!==window.onorientationchange&&(t=0==window.orientation?"portrait":"landscape"),(1025<=window.innerWidth||1024==window.innerWidth&&"portrait"==t)&&(t=document.querySelectorAll(".uxdia-action-widget-position__container"),s="position",t.forEach(function(t){var e=t.getBoundingClientRect(),o=t.offsetHeight,i=t.offsetWidth,n=t.querySelector(".uxdia-o-right-rail .advertisement"),l=t.querySelector(".uxdia-o-right-rail .uxdia-c-widget--common-layout-styles"),t=t.querySelector(".uxdia-o-right-rail .uxdia-most-popular-section--right-rail");n&&"absolute"!=n.style.position&&(n.style.position="static"),t&&"absolute"!=t.style.position&&(t.style.position="static"),l&&"absolute"!=l.style.position&&(l.style.position="static"),e.top>=-o&&e.left>=-i&&e.right<=(window.innerWidth||document.documentElement.clientWidth)+i&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)+o&&"position"===s&&(n?r(n,"ad"):t?(r(t,"popular"),l&&t.classList.add("uxdia-most-popular-section--right-rail--mkspace")):l&&r(l,"widget"))}))})}var o,i=document.querySelector(".uxdia-o-header"),m=i?i.offsetHeight+40:0,h=document.querySelector(".uxdia-c-series-landing-template .sticy-ad-container"),r=function(t,e){var o,i,n,l=(d=t.parentNode.closest(".container").parentNode.closest(".aem-Grid--default--12")).getBoundingClientRect().top,s=d.querySelector(".uxdia-o-right-rail .uxdia-most-popular-section--right-rail .cmp-experiencefragment"),r=d.querySelector(".uxdia-o-right-rail .uxdia-c-widget--common-layout-styles"),a=d.querySelector(".uxdia-o-right-rail .aarpe-ad"),a=a&&a.offsetHeight?a.offsetHeight:0,c=(r&&s?a+=r.offsetHeight+s.offsetHeight+40:s?a+=s.offsetHeight+40:r&&(a+=r.offsetHeight+40),d.offsetHeight<=a&&(t.closest(".cmp-container").style.height=a+"px"),la&&(t.closest(".cmp-container").style.height=t.offsetHeight+"px")):(t.style.position="static",t.style.top="0px"),document.querySelectorAll(".uxdia-o-full-width-ads-in-view")),s=d,d=t.getBoundingClientRect(),u=t.nextElementSibling?t.nextElementSibling.querySelector(".uxdia-c-widget--common-layout-styles"):0,p=(u&&(a=null==(r=t.nextElementSibling)?void 0:r.nextElementSibling,(r=u.closest(".advertisement ~ .experiencefragment > .cmp-experiencefragment"))&&(r.style.width=t.parentElement.offsetWidth+"px",n=r.getBoundingClientRect().top),a?(o=u.offsetHeight+a.offsetHeight,a.style.width=t.parentElement.offsetWidth+"px"):o=u.offsetHeight),null!=(r=t.nextElementSibling)&&r.classList.contains("uxdia-most-popular-section--right-rail")?t.nextElementSibling:0);p&&(r=null==(a=t.nextElementSibling.nextElementSibling)?void 0:a.querySelector(".uxdia-c-widget--common-layout-styles"),i=0<(a=p.querySelector(".cmp-experiencefragment")).getBoundingClientRect().top-m,a&&(a.style.width=t.parentElement.offsetWidth+"px",n=a.getBoundingClientRect().top),r?(o=(null==(a=p.querySelector(".cmp-experiencefragment"))?void 0:a.offsetHeight)+673,r.style.width=t.parentElement.offsetWidth+"px"):o=i?(null==(a=p.querySelector(".cmp-experiencefragment"))?void 0:a.offsetHeight)+673:p.offsetHeight),("ad"==e||"popular"==e)&&(u||p)?(r=d.bottom,document.querySelector(".uxdia-o-quiz-container")&&(r+=160),n<=r&&(i=s.closest(".container").nextElementSibling,(i=h&&"none"===(i=h.nextElementSibling).style.display?h.nextElementSibling.nextElementSibling:i)?(a=i.offsetTop-o-l-t.offsetHeight-window.scrollY,t.style.top=a+"px"):(n=o+40,t.style.top="unset",t.style.bottom=n+"px"),t.style.position="absolute")):t.style.paddingBottom="0";for(var f=0;fg.left&&d.topg.top){g=void 0,g="ad"==e&&(u||p)?c[f].offsetTop-o-l-t.offsetHeight-window.scrollY:c[f].offsetTop-l-t.offsetHeight-window.scrollY;t.style.top=g+"px",t.style.position="absolute";break}}r=document.querySelector(".uxdia-c-quiz-related-content-container"),s=document.querySelector(".uxdia-o-quiz-comments-container");s&&d.bottom>=s.getBoundingClientRect().top?(t.style.top=s.offsetTop-l-t.offsetHeight-window.scrollY+"px",t.style.position="absolute"):r&&d.bottom>=r.getBoundingClientRect().top&&d.top=k&&768>=u?"132px":t-1+"px")},p=function(){window.positionAlertTimeout&&window.cancelAnimationFrame(window.positionAlertTimeout);window.positionAlertTimeout=window.requestAnimationFrame(function(){var c=document.querySelector(".aarp-c-alert-bar.alert--rewards").closest(".alertBar"),f=c.offsetHeight,l=c.getBoundingClientRect();0<=l.top&&0<=l.left&&l.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&l.right<=(window.innerWidth||document.documentElement.clientWidth)?(c.style.paddingTop= 0,c.classList.remove("aarp-c-alert-bar--js-sticky")):(c.style.paddingTop=f+"px",c.classList.add("aarp-c-alert-bar--js-sticky"))})},v=function(c){if(c){var f;c.preventDefault();d.push(e);sessionStorage.setItem("alertBarStore",JSON.stringify(d));window.removeEventListener("debouncedresize",n);document.body.style.marginTop="";document.body.classList.contains("sharp-js-noAlertBar")||(document.body.classList.add("sharp-js-noAlertBar"),768<=k&&m&&(m.style.marginTop=parseInt(m.style.marginTop.replace(/px/, ""))-t+"px"));c.target.closest(".aarp-c-alert-bar").classList.remove("closed");a.parentElement.classList.remove("alert-bar--open");null===b||void 0===b?void 0:null===(f=b.classList)||void 0===f?void 0:f.remove("alert-bar-header--open");a.parentElement.classList.add("closed")}g&&g.classList.add("sharp-c-alertbar-reset")},q=0;q 1 && arguments[1] !== undefined ? arguments[1] : document; var coreHeaderSticky = (_document$querySelect = document.querySelector('.coreHeader')) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.classList.contains('coreHeader--js-sticky'); var membershipBanner = ((_document$querySelect2 = document.querySelector('#container_membership_banner')) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.offsetHeight) > 110; var stickyLeaderScrollDepth = 360; container === null || container === void 0 ? void 0 : (_container$querySelec = container.querySelectorAll('.uxdia-c-promo-header:not(.uxdia-c-promo-header--offscren-nav-theme)')) === null || _container$querySelec === void 0 ? void 0 : _container$querySelec.forEach(function (instance) { var _AARP6, _AARP6$header; if (stickyOverride || (_AARP6 = AARP) !== null && _AARP6 !== void 0 && (_AARP6$header = _AARP6.header) !== null && _AARP6$header !== void 0 && _AARP6$header.sticky && coreHeaderSticky) { if (!instance.classList.contains(stickyClass)) { instance.classList.add(stickyClass); } } else if (instance.classList.contains(stickyClass)) { instance.classList.remove(stickyClass); } }); if (window.outerWidth > 767 && stickyLeaderEnabled) { sponsorshipSticky = !(window.scrollY >= stickyLeaderScrollDepth); } if (membershipBanner) { sponsorshipSticky = false; } var sponsorshipElements = (_document$querySelect3 = document.querySelector('.uxdia-c-sponsorship:not(.uxdia-c-series .uxdia-c-sponsorship),.uxdia-c-series')) === null || _document$querySelect3 === void 0 ? void 0 : _document$querySelect3.style; var promoHeight = ((_document$querySelect4 = document.querySelector('.uxdia-c-promo-header:not(.uxdia-c-promo-header--offscren-nav-theme)')) === null || _document$querySelect4 === void 0 ? void 0 : _document$querySelect4.clientHeight) || 0; var megamenu = document.querySelector('.uxdia-c-megamenu'); var aarpHeader = document.querySelector('.coreHeader .aarp-c-header'); var galleryComponent = !document.querySelector('.gallery.gallery__container'); var coreHeaderElement = (_document$querySelect5 = document.querySelector('.coreHeader')) === null || _document$querySelect5 === void 0 ? void 0 : _document$querySelect5.style; var mainWrapper = (_document$querySelect6 = document.querySelector('.uxdia-o-header+main.container, .aarpe-main-content-wrap')) === null || _document$querySelect6 === void 0 ? void 0 : _document$querySelect6.style; var aarpHeaderEle = aarpHeader === null || aarpHeader === void 0 ? void 0 : aarpHeader.style; var adContainer = document.querySelector('.uxdia-u-bg-ads--utility-medium-grey, #container-81ea044270'); var stickyLeaderCon = adContainer === null || adContainer === void 0 ? void 0 : adContainer.dataset; var adContainerHeight = (adContainer === null || adContainer === void 0 ? void 0 : adContainer.clientHeight) || 0; var adHeight = stickyLeaderEnabled && sponsorshipSticky && adContainerHeight || 0; if (stickyLeaderCon && stickyLeaderEnabled) { if (!membershipBanner) { stickyLeaderCon.scroll = window.scrollY > 0 ? window.scrollY : 0; } else { adContainer === null || adContainer === void 0 ? void 0 : adContainer.removeAttribute('data-scroll'); } } adContainer === null || adContainer === void 0 ? void 0 : adContainer.classList[sponsorshipSticky && window.scrollY > 0 ? 'add' : 'remove']('uxdia-leaderboard-js--sticky'); adContainer !== null && adContainer !== void 0 && (_adContainer$classLis = adContainer.classList) !== null && _adContainer$classLis !== void 0 && _adContainer$classLis.contains('uxdia-leaderboard-js--sticky') ? dispatchEvent(new CustomEvent('activateShyHeader', { detail: 'showNavigation' })) : ''; if (!(megamenu !== null && megamenu !== void 0 && (_megamenu$classList = megamenu.classList) !== null && _megamenu$classList !== void 0 && _megamenu$classList.contains('uxdia-c-megamenu--open')) && window.scrollY > 0 && (sponsorshipSticky || stickyLeaderCon && stickyLeaderCon.scroll >= stickyLeaderScrollDepth)) { coreHeaderElement && (coreHeaderElement.paddingTop = 0); mainWrapper && aarpHeader && (mainWrapper.paddingTop = adContainerHeight + (aarpHeader !== null && aarpHeader !== void 0 && aarpHeader.clientHeight ? aarpHeader === null || aarpHeader === void 0 ? void 0 : aarpHeader.clientHeight : 0) + (megamenu !== null && megamenu !== void 0 && megamenu.clientHeight ? megamenu === null || megamenu === void 0 ? void 0 : megamenu.clientHeight : 0) + 'px'); } else { mainWrapper && (mainWrapper.paddingTop = 0); } if (window.outerWidth < 768) { sponsorshipElements && (sponsorshipElements.top = (aarpHeader !== null && aarpHeader !== void 0 && aarpHeader.clientHeight ? aarpHeader.clientHeight - 1 : 0) + promoHeight + ((megamenu === null || megamenu === void 0 ? void 0 : megamenu.clientHeight) !== undefined ? megamenu.clientHeight : 0) + adHeight + 'px'); } else { sponsorshipElements && (sponsorshipElements.top = (aarpHeader !== null && aarpHeader !== void 0 && aarpHeader.clientHeight ? aarpHeader.clientHeight - 1 : 0) + (megamenu !== null && megamenu !== void 0 && megamenu.clientHeight ? megamenu.clientHeight - 1 : 0) + adHeight + 'px'); } galleryComponent && aarpHeaderEle && (aarpHeaderEle.top = adHeight + 'px'); // CVC-3641 fix jumpiness in promo header to improve CLS score var promoHeaderEle = document.querySelectorAll('.promoHeader'); promoHeaderEle === null || promoHeaderEle === void 0 ? void 0 : promoHeaderEle.forEach(function (promoheader) { promoheader.querySelector('.uxdia-c-promo-header').style.visibility = 'visible'; }); }; // For adjusting the space when moving to part of the page using link document.querySelectorAll('a[href^="#"]').forEach(function (ele) { ele.addEventListener('click', function (e) { var _document$querySelect7, _document$querySelect8, _document$querySelect9, _document$querySelect10, _document$querySelect11; var scrollerId = ele === null || ele === void 0 ? void 0 : ele.hash; if (!scrollerId) { return; } var targetElement = document.querySelector(scrollerId); var sponsorshipHeight = ((_document$querySelect7 = document.querySelector('.uxdia-c-sponsorship:not(.uxdia-c-series .uxdia-c-sponsorship),.uxdia-c-series')) === null || _document$querySelect7 === void 0 ? void 0 : _document$querySelect7.clientHeight) || 0; var promoHeaderHeight = ((_document$querySelect8 = document.querySelector('.uxdia-c-promo-header:not(.uxdia-c-promo-header--offscren-nav-theme)')) === null || _document$querySelect8 === void 0 ? void 0 : _document$querySelect8.clientHeight) || 0; var megamenuHeight = ((_document$querySelect9 = document.querySelector('.uxdia-c-megamenu')) === null || _document$querySelect9 === void 0 ? void 0 : _document$querySelect9.clientHeight) || 0; var aarpHeaderHeight = ((_document$querySelect10 = document.querySelector('.coreHeader .aarp-c-header')) === null || _document$querySelect10 === void 0 ? void 0 : _document$querySelect10.clientHeight) || 0; var coreHeaderSticky = document.querySelector('.coreHeader--js-sticky'); var htmlElement = (_document$querySelect11 = document.querySelector('html')) === null || _document$querySelect11 === void 0 ? void 0 : _document$querySelect11.style; var requiredScroll = +sponsorshipHeight + +promoHeaderHeight + +megamenuHeight + aarpHeaderHeight; !coreHeaderSticky && (requiredScroll += sponsorshipHeight + megamenuHeight); if (!(targetElement && requiredScroll)) { return; } htmlElement && (htmlElement.scrollPaddingTop = requiredScroll + 'px'); }); }); // Below if condition checks if targetting is disabled and the optimized header is authored if (document.querySelector('.promoHeader.articleimage.uxdia-c-no-target-header') && !currentStickiness) { syncWithCoreHeader(currentStickiness, document); } // Custom logic for nowapp domain, core header absence, and promo header stickiness var subdomain = window.location.hostname.split('.')[0]; var isNowApp = /nowapp-s|nowapp-pi|nowapp-d|nowapp/g.test(subdomain); var hasNoCoreHeader = !document.querySelector('.uxdiaCacheableXF.experiencefragment .coreHeader'); var promoHeaderEl = document.querySelector('.uxdia-c-promo-header'); if (isNowApp && hasNoCoreHeader && promoHeaderEl) { var _window$getComputedSt; var isPromoHeaderSticky = promoHeaderEl === null || promoHeaderEl === void 0 ? void 0 : promoHeaderEl.classList.contains('uxdia-c-promo-header--js-sticky'); var topValue = (_window$getComputedSt = window.getComputedStyle(promoHeaderEl)) === null || _window$getComputedSt === void 0 ? void 0 : _window$getComputedSt.top; // Remove inline top style before syncing if (isPromoHeaderSticky && promoHeaderEl && topValue !== 'auto' && topValue !== '0px') { promoHeaderEl.style.setProperty('top', 0, 'important'); } syncWithCoreHeader(isPromoHeaderSticky ? true : false, document); } AARP.Externals.ContextHub.attachContexthubCallback({ callback: function callback(added, removed, details) { var _details$keys, _details$keys$set, _details$keys$set$lis; details === null || details === void 0 ? void 0 : (_details$keys = details.keys) === null || _details$keys === void 0 ? void 0 : (_details$keys$set = _details$keys.set) === null || _details$keys$set === void 0 ? void 0 : (_details$keys$set$lis = _details$keys$set.list) === null || _details$keys$set$lis === void 0 ? void 0 : _details$keys$set$lis.forEach(function (item) { var container = document.getElementById(item); syncWithCoreHeader(currentStickiness, container); }); } }); window.addEventListener('CORE_HEADER.STICKY_UPDATE', function (_ref) { var sticky = _ref.detail.sticky; currentStickiness = sticky; syncWithCoreHeader(sticky); }); })();AARP=AARP||{};AARP.Externals=AARP.Externals||{}; (function(){function e(c){(document.getElementById(c)||document).querySelectorAll(".aarpe-clear-storage").forEach(function(b){b.addEventListener("click",function(a){Object.keys(localStorage).forEach(function(d){"qaToolResultsPageMappings"!=d&&localStorage.removeItem(d)});sessionStorage.clear();f();window.dispatchEvent(new CustomEvent("VIAFOURA_LOGOUT"));a=new CustomEvent("aarp-user-logout");window.dispatchEvent(a)})})}function g(){void 0===AARP.store.getState().cookie.at&&f();e();"undefined"!=typeof ContextHub&& ContextHub.Utils&&ContextHub.Utils.Eventing&&ContextHub.Constants&&ContextHub.Constants.EVENT_TEASER_LOADED&&ContextHub.Utils.Eventing().on(ContextHub.Constants.EVENT_TEASER_LOADED,function(c,b){void 0!==b&&b.data.forEach(function(a){"set"==a.action&&"loaded"==a.value&&e(a.key)})},"logout-link-binding",!0)}var f=function(){document.cookie="rewards_cookie\x3d;expires\x3dThu, 01 Jan 1970 00:00:01 GMT;path\x3d/;";document.cookie="aarp_rewards_balance\x3d;domain\x3d.aarp.org;expires\x3dThu, 01 Jan 1970 00:00:01 GMT;path\x3d/"}; AARP.Externals.attachPageJsCallback(g);AARP.Externals.ContextHub.onLoad(function(){var c,b,a,d;null===(c=window)||void 0===c||null!==(b=c.ContextHub)&&void 0!==b&&(null===(a=b.Utils)||void 0===a||null!==(d=a.Eventing())&&void 0!==d&&d.on(window.ContextHub.Constants.EVENT_TEASER_LOADED,g))})})();(function(){function h(a){13===(a.keyCode||a.which)&&g(a)}function g(a){a=a.currentTarget;a.classList.toggle("aarp-c-linked-dropdown__arrow-open");a.classList.toggle("aarp-c-linked-dropdown__arrow-close");var b=a.querySelector("span");b.classList.toggle("aarp-c-linked-dropdown__arrow-open__span");b.classList.toggle("aarp-c-linked-dropdown__arrow-close__span");"true"==a.getAttribute("aria-expanded")?a.setAttribute("aria-expanded","false"):a.setAttribute("aria-expanded","true")}function n(a){var b, c;a+="\x3d";var e=null===(b=document)||void 0===b?void 0:null===(c=b.cookie)||void 0===c?void 0:c.split(";");for(b=0;b/g,"").replace(/\s+/g," "),a.setAttribute("aria-label",b),a.innerHTML='\x3cspan class\x3d"aarp-c-linked-dropdown__arrow-open__span"\x3e\x3c/span\x3e', a.removeEventListener("click",g),a.removeEventListener("keyup",h),a.addEventListener("click",g),a.addEventListener("keyup",h))}})});AARP.Externals.ContextHub.onLoad(function(){var a,b,c,e;null===(a=window)||void 0===a?void 0:null===(b=a.ContextHub)||void 0===b?void 0:null===(c=b.Utils)||void 0===c?void 0:null===(e=c.Eventing())||void 0===e?void 0:e.on(window.ContextHub.Constants.EVENT_TEASER_LOADED,function(){m();document.querySelectorAll(".aarp-c-linked-dropdown .aarp-c-linked-dropdown__label").forEach(function(d){if(d&& d.parentElement){var f=d.parentElement.querySelector(".aarp-c-linked-dropdown__main-text");f&&(f=f.innerHTML.replace(/<.*?>/g,"").replace(/\s+/g," "),d.setAttribute("aria-label",f),d.innerHTML='\x3cspan class\x3d"aarp-c-linked-dropdown__arrow-open__span"\x3e\x3c/span\x3e',d.removeEventListener("click",g),d.removeEventListener("keyup",h),d.addEventListener("click",g),d.addEventListener("keyup",h))}})})});(function(){var a=AARP.store.getState().cookie.aarp_rewards_balance;if(null!==n("at")&&a&&parseInt(a)){a= a?Number(a).toLocaleString("en-US"):"";var b=document.createTextNode(" ".concat(a," pts"));(a=document.querySelectorAll(".icon-r4g-badge-points"))&&Array.prototype.slice.call(a).forEach(function(c){c.innerHTML="";c.appendChild(b)})}})();m()})();(function(){function l(e){var f=document.querySelector(".aarp-c-search");document.dispatchEvent(g);f.classList.toggle("aarp-c-search-form-container__trigger--closed");k(e)}function m(e){var f=document.querySelector(".aarp-o-search-status");f&&(f.innerText=e)}function k(e){e=e.target;var f=document.querySelector(".aarp-c-search__button");f&&f.contains(e)&&(f.classList.toggle("aarp-c-search__button--open"),f.classList.toggle("aarp-c-search__button--close"),"true"==f.getAttribute("aria-expanded")?f.setAttribute("aria-expanded", "false"):f.setAttribute("aria-expanded","true"));m("")}function b(e){if(13===(e.keyCode||e.which)){var f=document.querySelector(".aarp-c-search");document.dispatchEvent(g);f.classList.toggle("aarp-c-search-form-container__trigger--closed");k(e)}}function c(e){e.preventDefault();e=document.querySelector(".aarp-c-search__search-input").value;q(e)}function d(e){13===(e.keyCode||e.which)&&(e=document.querySelector(".aarp-c-search__search-input").value,q(e))}function a(){var e=document.querySelector(".aarp-c-search__search-input"), f=document.querySelector(".aarp-c-search__search-label");""==e.value?(e.classList.remove("active"),f.classList.remove("label__inactive")):(e.classList.add("active"),f.classList.add("label__inactive"))}var g=new CustomEvent("SEARCH_CLICKED",{detail:{}}),h=function(e){var f=document.querySelector(".aarp-c-search");e&&f&&!f.contains(e.target)&&(e=document.querySelector(".aarp-c-search__button"),f=document.querySelector(".aarp-c-search__search-input"),e.classList.add("aarp-c-search__button--open"),e.classList.remove("aarp-c-search__button--close"), e.setAttribute("aria-expanded","false"),f&&(f.value=""));m("")},q=function(e){e&&(e=encodeURIComponent(e),e=AARP.Everywhere.endecaSearchUrl+"?q\x3d"+e+"\x26"+AARP.Everywhere.endecaSearchUrlInternalTracking,window.dispatchEvent(new CustomEvent("SEND_ANALYTICS_ON_NEW_SEARCH_SUBMIT")),window.location=e)},n=function(){if(document.querySelector(".aarp-o-body")){var e=document.querySelector(".aarp-c-search__submit-button"),f=document.querySelector(".aarp-c-search__search-input"),p=document.querySelector(".aarp-c-search__button"); p&&(p.removeEventListener("click",l),p.addEventListener("click",l),window.removeEventListener("click",h),window.addEventListener("click",h),p.removeEventListener("keyup",b),p.addEventListener("keyup",b),e&&(e.removeEventListener("click",c),e.addEventListener("click",c)),f&&(f.removeEventListener("keyup",d),f.addEventListener("keyup",d),f.addEventListener("input",a)),document.removeEventListener("MENU_CLICKED",h),document.removeEventListener("CONTENT_TITLE_OPTIONS_CLICKED",h),document.addEventListener("MENU_CLICKED", h),document.addEventListener("CONTENT_TITLE_OPTIONS_CLICKED",h))}};AARP.readyStateLoader(n);AARP.Externals.ContextHub.onLoad(function(){var e,f,p,r;null===(e=window)||void 0===e?void 0:null===(f=e.ContextHub)||void 0===f?void 0:null===(p=f.Utils)||void 0===p?void 0:null===(r=p.Eventing())||void 0===r?void 0:r.on(window.ContextHub.Constants.EVENT_TEASER_LOADED,n)})})();"use strict";function _classCallCheck(l,m){if(!(l instanceof m))throw new TypeError("Cannot call a class as a function");} function _defineProperties(l,m){for(var k=0;k=c._options.minAutoSuggestInputLength?(b.setSearchStatus("Loading search suggestions for ".concat(d)),c.requestData()):(b.setSearchStatus("Search term too short"),c.hide()));c._lastValue=d},this._options.delay)}},{key:"requestData",value:function(){var b= this,c=this,d=this._element.value.trim(),a=c.composeUrl();fetch(a).then(function(g){return g.json()}).then(function(g){c._storedData=g;c.createAnalyticsData(g,d,a);c.showSearchResult(g,d);b.setSearchStatus("".concat(g.completions.length," suggested search terms loaded"))},function(g){console.log("Unable to fetch the data for this location",g);b.setSearchStatus("Unable to provide search suggesions due to an error")})}},{key:"createAnalyticsData",value:function(b,c,d){b.completions&&(d=null,b.completions&& 0'+r+""}; AARP.token.processor.italicHighlight=function(i){return''+i+""}; AARP.token.processor.italicHighlightComma=function(i){return''+i+","}; AARP.token.processor.rewardsPoints=function(r){return''+r+""}; AARP&&AARP.store&&AARP.token&&(AARP.token.updateCookieToken=function(e){e.cookie.at&&(e.cookie.at.f&&(AARP.token.store.firstName={"value":e.cookie.at.f.replace(/\+/g," ")}),AARP.token.store.userName={"value":e.cookie.at.a},AARP.token.store.userEmail={"value":e.cookie.at.e},AARP.token.store.userAddressState={"value":e.cookie.at.us},AARP.token.store.memberJoinedDate={"value":new Date(e.cookie.at.mj)},AARP.token.store.memberExpiryDate={"value":new Date(e.cookie.at.me)})},AARP.token.updateCookieToken(AARP.store.getState()),AARP.store.subscribe(function(){return AARP.token.updateCookieToken(AARP.store.getState())})); AARP.token.store.points={"value":""},AARP.token.store.pointsNumOnly={"value":""};var numKFormatter,updatePointsVal,cookies=AARP.store.getState().cookie;cookies&&cookies.at&&(numKFormatter=function(e){return e<1e3?e:999{null!=(n=AARP)&&null!=(t=n.Externals)&&null!=(e=t.ContextHub)&&e.onLoad(function(){var n;null!=(n=ContextHub)&&null!=(n=n.Utils)&&null!=(n=n.Eventing())&&n.on(ContextHub.Constants.EVENT_TEASER_LOADED,function(n,t){t&&(t=t.data.reduce(function(n,t){return"set"==t.action&&"loaded"==t.value&&n.push("#".concat(t.key)),n},[]).join(","),AARP.token.replace(new CustomEvent({"details":{"selectors":t}})))},"token-replacer",!0)})})(); var AARP=AARP||{};AARP.addStateParam=function(b){var a=b.href.split("?")[1],c=!1;(c=a?-1a.indexOf("state\x3d"):c)&&(a=window.location.href,c=encodeURIComponent(a),-1=f.length?{done:!0}:{done:!1,value:f[v++]}},e:function(p){throw p;},f:k}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }var w=!0,m=!1,q;return{s:function(){g=g.call(f)},n:function(){var p=g.next();w=p.done;return p},e:function(p){m=!0;q=p},f:function(){try{if(!w&&null!=g["return"])g["return"]()}finally{if(m)throw q;}}}} function _unsupportedIterableToArray(f,k){if(f){if("string"===typeof f)return _arrayLikeToArray(f,k);var g=Object.prototype.toString.call(f).slice(8,-1);"Object"===g&&f.constructor&&(g=f.constructor.name);if("Map"===g||"Set"===g)return Array.from(f);if("Arguments"===g||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(g))return _arrayLikeToArray(f,k)}}function _arrayLikeToArray(f,k){if(null==k||k>f.length)k=f.length;for(var g=0,v=Array(k);ga.getMonth()?"0".concat(a.getMonth()+1):a.getMonth()+1,"-").concat(9>=a.getDate()?"0".concat(a.getDate()):a.getDate(),"-").concat(a.getFullYear())}; window.updateChallengesShape=function(){return new Promise(function(a,b){var c,d,e,h=window.getUserType(),l=null===(c=AARP)||void 0===c?void 0:null===(d=c.StayingSharp)||void 0===d?void 0:null===(e=d.SessionData)||void 0===e?void 0:e.getChallengesShape();if(l&&"null"!=l)a(JSON.parse(l));else if(h){var n,r,y;c="".concat(null===(n=AARP)||void 0===n?void 0:null===(r=n.StayingSharp)||void 0===r?void 0:null===(y=r.apiConstants)||void 0===y?void 0:y.cmsApiBaseUrl,"/challenges.").concat(h,".json");AARP.httpUtil.doGet(c).then(function(x){var z, A;null===(z=AARP)||void 0===z?void 0:null===(A=z.StayingSharp)||void 0===A?void 0:A.SessionData.setChallengesShape(x);a(JSON.parse(x))})["catch"](function(x){console.log("Failed to update challengeShape: ",x);b("Failed to Update Challenges Shape")})}})};var p=function(){var a=document.querySelectorAll('a[data-functionality\x3d"dailypuzzle"]');Array.prototype.forEach.call(a,function(b){var c=b.getAttribute("href");c+=window.calcTime(-5);b.setAttribute("href",c);b.addEventListener("click",function(d){d.preventDefault(); window.location.pathname=c})})},t=function(){console.log("core stayingSharp Init");p();var a=AARP.StayingSharp.getPageName();if(a===AARP.StayingSharp.constants.articlesDetail||a===AARP.StayingSharp.constants.activitiesDetail||a===AARP.StayingSharp.constants.gamesDetail)a=JSON.stringify("{}"),localStorage.setItem("tagRecommendation",a),document.dispatchEvent(new CustomEvent("TAGS_BASED_CONTENT",{detail:a})),window.getTagRecommendation()};document.addEventListener("HIDE_STAYINGSHARP_MENU_NEW_HEADER", function(){f&&f.classList.add("sharp-c-challenges__body","sharp-c-challenges__body@desktop");k&&k.classList.add("sharp-u-hidden")});document.addEventListener("SHOW_STAYINGSHARP_MENU_NEW_HEADER",function(){f&&f.classList.remove("sharp-c-challenges__body","sharp-c-challenges__body@desktop");k&&k.classList.remove("sharp-u-hidden")});document.addEventListener("HIDE_STAYINGSHARP_FOOTER",function(){g&&g.classList.add("sharp-u-hidden")});document.addEventListener("SHOW_STAYINGSHARP_FOOTER",function(){g&& g.classList.remove("sharp-u-hidden")});window.addEventListener("load",function(){var a,b,c,d,e,h,l,n,r,y,x,z,A;document.body.classList.add(null!==(a=AARP)&&void 0!==a&&null!==(b=a.StayingSharp)&&void 0!==b&&null!==(c=b.utils)&&void 0!==c&&c.isUserUHC()?"sharp-c-uhc-user":"sharp-c-".concat(null===(d=window)||void 0===d?void 0:null===(e=d.getUserType())||void 0===e?void 0:e.toLowerCase(),"-user"),"4"===(null===(h=AARP)||void 0===h?void 0:null===(l=h.cookies)||void 0===l?void 0:null===(n=l.at)||void 0=== n?void 0:n.ss)||"3"===(null===(r=AARP)||void 0===r?void 0:null===(y=r.cookies)||void 0===y?void 0:null===(x=y.at)||void 0===x?void 0:x.ss)?"sharp-c-buy-user":"sharp-c-join-user","sharp-c-".concat(null===(z=AARP)||void 0===z?void 0:null===(A=z.StayingSharp)||void 0===A?void 0:A.getPageName()));window.parent!==window&&window.parent.postMessage({HotContainerIFrameLoaded:!0},"/")});window.addEventListener("beforeunload",function(){window.parent!==window&&document.body.classList.add("sharp-o-state-exiting")}); if(window.parent!==window)if("undefined"===typeof ResizeObserver){var u=0;setInterval(function(){u!=document.documentElement.scrollHeight&&(u=document.documentElement.scrollHeight,window.parent.postMessage({HotContainerIFrameLoaded:!0},"/"))},800)}else(new ResizeObserver(function(a){a=_createForOfIteratorHelper(a);var b;try{for(a.s();!(b=a.n()).done;)document.documentElement===b.value.target&&window.parent.postMessage({HotContainerIFrameLoaded:!0},"/")}catch(c){a.e(c)}finally{a.f()}})).observe(document.documentElement); window.addEventListener("message",function(a){if((null===a||void 0===a?void 0:a.origin)==="https://".concat(AARP.StayingSharp.hostName)&&(a.data.SS_SPA_MODAL&&(document.body.classList["OPEN"===a.data.SS_SPA_MODAL?"add":"remove"]("sharp-c-challenges-spa-modal--active"),window.dispatchEvent(new CustomEvent("debouncedresize"))),"SS_POPUP_MODAL"===a.data.event)){var b,c,d,e=a.data.active?"disableBodyScroll":"enableBodyScroll";document.body.classList[a.data.active?"add":"remove"]("sharp-c-challenge-redesign--modalOpen"); (null===(b=AARP)||void 0===b?0:null===(c=b.Foundation)||void 0===c?0:null===(d=c.Module)||void 0===d?0:d.bsl)&&AARP.Foundation.Module.bsl[e]()}});AARP.Externals.ContextHub.onLoad(t);return{coreStayingSharpInit:t}}();"use strict"; (function(){var f,k,g,v=function(m){return(8B&&D&&E&&(C=v(C),E.innerHTML=C,D.classList.remove("sharp-u-hidden"),F.forEach(function(G){G.classList.remove("sharp-u-hidden")}))})})}e=(null===(n=AARP)||void 0===n?void 0:null===(r=n.StayingSharp)||void 0===r?void 0:r.appSecDomain)+"/mem/renew?campaignid\x3dUSSTEST7\x26intcmp\x3dSS-HDR-RENEW";if(n=document.querySelector("#sharp-c-member-renew"))n.href= e};null===(f=AARP)||void 0===f?void 0:null===(k=f.Externals)||void 0===k?void 0:k.ContextHub.onLoad(function(){var m,q,p,t;null===(m=window)||void 0===m?void 0:null===(q=m.ContextHub)||void 0===q?void 0:null===(p=q.Utils)||void 0===p?void 0:null===(t=p.Eventing())||void 0===t?void 0:t.on("ch-segment-engine:teaser-loaded",function(u,a){var b,c;u||a?null!==a&&void 0!==a&&null!==(b=a.keys)&&void 0!==b&&null!==(c=b.all)&&void 0!==c&&c.list&&a.keys.all.list.forEach(function(d){0<=d.indexOf("header-ipar_cacheableexperiencef")&& document.querySelector(".ssHeader")&&w()}):w()},"ssHeader",!0)});(null===(g=document.querySelector("#isVendorWrapper"))||void 0===g?0:g.value)&&w()})();"use strict"; AARP.StayingSharp.specialMemInit=function(){var f=document.querySelector("body"),k=document.querySelector(".sharp-c-homepage__banner-container");AARP.Externals.ContextHub.onLoad(function(){var g,v,w,m;null===(g=window)||void 0===g?void 0:null===(v=g.ContextHub)||void 0===v?void 0:null===(w=v.Utils)||void 0===w?void 0:null===(m=w.Eventing())||void 0===m?void 0:m.on(window.ContextHub.Constants.EVENT_STORE_READY+":ss-usertypes-jsonp",function(){var q,p,t,u,a=null===(q=window.ContextHub.getStore("ss-usertypes-jsonp"))|| void 0===q?void 0:q.getItem("/");if(null!==a&&void 0!==a&&null!==(p=a.fullResponse)&&void 0!==p&&null!==(t=p.user)&&void 0!==t&&null!==(u=t.access_and_features)&&void 0!==u&&u.sponsor)switch(a.fullResponse.user.access_and_features.sponsor){case "UHCOP":f&&f.classList.add("sharp-c-header--one-pass");break;case "UHCMS15":f&&f.classList.add("sharp-c-header--med-supplement");break;case "UHCMA":case "UHCMS35":f&&f.classList.add("sharp-c-header--renew-active");break;case "PRUDENTIAL":f&&f.classList.add("sharp-c-header--prudential")}k&& (null===k||void 0===k?void 0:k.setAttribute("data-original-src","/content/dam/specialized-membership/staying-sharp/staying-sharp-homepage/showcase-redesign/".concat("wave.png")),null===k||void 0===k?void 0:k.setAttribute("data-original-ratio","0.59"));return""},"specialMem",!0)})};AARP.StayingSharp.specialMemInit();function _toConsumableArray(c){return _arrayWithoutHoles(c)||_iterableToArray(c)||_unsupportedIterableToArray(c)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");} function _unsupportedIterableToArray(c,v){if(c){if("string"===typeof c)return _arrayLikeToArray(c,v);var n=Object.prototype.toString.call(c).slice(8,-1);"Object"===n&&c.constructor&&(n=c.constructor.name);if("Map"===n||"Set"===n)return Array.from(c);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(c,v)}}function _iterableToArray(c){if("undefined"!==typeof Symbol&&Symbol.iterator in Object(c))return Array.from(c)} function _arrayWithoutHoles(c){if(Array.isArray(c))return _arrayLikeToArray(c)}function _arrayLikeToArray(c,v){if(null==v||v>c.length)v=c.length;for(var n=0,f=Array(v);n=window.scrollY&&M.top<=window.scrollY+window.innerHeight||M.bottom>=window.scrollY&&M.bottom<=window.scrollY+window.innerHeight);M?(u.style.paddingTop=0,u.classList.remove("coreHeader--js-sticky"), u=!1):(u.style.paddingTop=J+"px",u.classList.contains("coreHeader--js-sticky")||u.classList.add("coreHeader--js-sticky"),u=!0);t(u);window.dispatchEvent(new CustomEvent("CORE_HEADER.STICKY_UPDATE",{detail:{height:J,sticky:u}}))})};e();window.removeEventListener("scroll",e);window.addEventListener("scroll",e)}else e=function(){t(!1)},window.removeEventListener("scroll",e),window.addEventListener("scroll",e)},R=function(){var e=document.getElementById("aarp-c-offscreen-nav-id");if(e){var g=e.classList.contains("aarp-c-offscreen-nav--uxdia-theme"); e=document.querySelector(".aarp-c-linked-dropdown--header .aarp-c-linked-dropdown__link-list");var l=document.querySelector(".aarp-c-linked-dropdown--header .aarp-c-linked-dropdown__link-item-user"),p=e&&e.firstChild,k=Math.max(document.documentElement.clientWidth,window.innerWidth||0);g&&e&&768>k&&!l&&(g=document.createElement("li"),l=document.createElement("span"),g.classList.add("aarp-c-linked-dropdown__list-item"),l.classList.add("aarp-c-linked-dropdown__link-item","aarp-c-linked-dropdown__link-item-user"), l.innerText="Hi, %{ firstName }%",g.appendChild(l),e.insertBefore(g,p));AARP.token.replace()}};document.addEventListener("click",function(e){var g=document.querySelector(".aarp-c-offscreen-nav--uxdia-theme"),l=document.querySelector(".aarp-c-linked-dropdown--header .aarp-c-linked-dropdown");if(g){var p=document.querySelector(".aarp-c-search"),k=document.querySelector(".aarp-c-header__menu-icon-link");g.contains(e.target)||k.contains(e.target)||openNav(e,!0);l.contains(e.target)||(g=l.querySelector(".aarp-c-linked-dropdown__control"), k=document.activeElement,g&&(g.checked=!1),k.focus());p.contains(e.target)||(p=p.querySelector(".aarp-c-search__control"),g=document.activeElement,p&&(p.checked=!1),g.focus())}p=null===l||void 0===l?void 0:l.querySelector(".aarp-c-linked-dropdown__label");g=null===l||void 0===l?void 0:l.querySelector(".aarp-c-linked-dropdown__link-list");k="true"==(null===p||void 0===p?void 0:p.getAttribute("aria-expanded"));l&&!l.contains(e.target)&&p&&k&&(e=p.querySelector("span"),p.classList.add("aarp-c-linked-dropdown__arrow-open"), p.classList.remove("aarp-c-linked-dropdown__arrow-close"),null===e||void 0===e?void 0:e.classList.add("aarp-c-linked-dropdown__arrow-open__span"),null===e||void 0===e?void 0:e.classList.remove("aarp-c-linked-dropdown__arrow-close__span"),p.setAttribute("aria-expanded","false"),null===g||void 0===g?void 0:g.classList.remove("showDropDown"))});N();R();window.addEventListener("STICKY_HEADER",N);var D;window.addEventListener("resize",function(){D&&window.cancelAnimationFrame(D);D=window.requestAnimationFrame(function(){N(); R()})});z();var Q=document.querySelectorAll(".aemform");null===Q||void 0===Q?void 0:Q.forEach(function(e){e.querySelector("#aemFormFrame").setAttribute("aria-label","aem form iframe")});null===(n=window)||void 0===n?void 0:null===(f=n.ContextHub)||void 0===f?void 0:null===(G=f.Utils)||void 0===G?void 0:null===(x=G.Eventing())||void 0===x?void 0:x.on(window.ContextHub.Constants.EVENT_STORE_READY+":ss-usertypes-jsonp",function(){var e,g,l,p,k,m,t,J,K=document.location.hostname.match("stayingsharp"), u=null===(e=window)||void 0===e?void 0:null===(g=e.ContextHub)||void 0===g?void 0:null===(l=g.getStore("ss-usertypes-jsonp"))||void 0===l?void 0:l.getItem("/");e=null===u||void 0===u?void 0:null===(p=u.fullResponse)||void 0===p?void 0:null===(k=p.user.access_and_features)||void 0===k?void 0:k.sponsor;p=null===u||void 0===u?void 0:null===(m=u.fullResponse)||void 0===m?void 0:null===(t=m.user)||void 0===t?void 0:null===(J=t.access_and_features)||void 0===J?void 0:J.activate_free_trail_stayingsharp; K&&e&&"IMH"!==e&&!p&&document.querySelector(".coreHeader.uxdia-c-no-target-header .aarp-c-header__r4g-section").classList.add("sharp-u-hidden")},"sponsored-user",!0);(function(){var e=document.querySelectorAll(".uxdia-c-home-page--text-block .cmp-container");0k&&"Y"!=p&&(l.userType="".concat(m,"expiring-member")),2800==k.getFullYear()&&(l.userType="".concat(m,"lifetime-member"),(p=document.querySelector(".uxdia-c-fullwidth-membership-promo__container"))&&(p.style.display="none"));return l},e=function(){var g,l,p,k=null===(g=AARP)|| void 0===g?void 0:null===(l=g.store)||void 0===l?void 0:null===(p=l.getState())||void 0===p?void 0:p.knownUser;if(!z){g=null===k||void 0===k?void 0:k.memberState;l=null===k||void 0===k?void 0:k.memberShipStatus;p=null===k||void 0===k?void 0:k.memberAutoRenewStatus;k=null===k||void 0===k?void 0:k.memberExpiry;if("ANON"===g||"undefined"===typeof g)D.userType="anonymous-user";else{var m;D.userType=null===(m=Q(l,D,p,k,"known-"))||void 0===m?void 0:m.userType}D.error=!0}else if(z){var t;D.userType=null=== (t=Q(null===z||void 0===z?void 0:z.ms,D,null===z||void 0===z?void 0:z.mar,null===z||void 0===z?void 0:z.me,""))||void 0===t?void 0:t.userType}v(D.userType,N);null===H||void 0===H?void 0:H.forEach(function(J){J&&n(D.userType,N,J,R)})};AARP.store.subscribe(function(){e()});w=new URL(window.location.href);w=new URLSearchParams(w.search);(w=null===w||void 0===w?void 0:w.get("encparam"))&&(AARP.store.getState().cookie.ufo||AARP.store.getState().cookie.at)?e():w||e();window.addEventListener("UFO-refresher", e);return D}},v=function(f,G){var x,y,w,H;f=G[f];null===f||void 0===f?void 0:null===(x=f.deleteUserStates)||void 0===x?void 0:x.forEach(function(L){var z;null===(z=document.querySelector(".coreHeader.uxdia-c-no-target-header ".concat(L)))||void 0===z?void 0:z.remove()});null===(y=document.querySelector(".coreHeader"))||void 0===y?void 0:y.classList.add(f["class"]);null===(w=AARP)||void 0===w?void 0:null===(H=w.token)||void 0===H?void 0:H.replace()},n=function(f,G,x,y){var w=G[f].promoHeaderState; if("remove"===w)x.remove();else if("keep"===w){var H,L;null===(H=x.querySelector(".uxdia-c-user-state__element-rejoin"))||void 0===H?void 0:H.remove();null===(L=x.querySelector(".uxdia-c-user-state__element-enroll"))||void 0===L?void 0:L.remove()}else y.map(function(z){if(".uxdia-c-user-state__element-".concat(w)!=z){var N;null===(N=x.querySelector(z))||void 0===N?void 0:N.remove()}});x&&x.classList.add("showPromoHeader")};c();return{executeHeaderOnLoad:c}}();"use strict";AARP=AARP||{}; AARP.Uxdia=AARP.Uxdia||{}; AARP.Uxdia.shyHeaderWrapper=function(){var c=function(){var v,n=document.querySelector(".aarp-c-offscreen-nav--dark-overlay"),f=null===n||void 0===n?void 0:null===(v=n.dataset)||void 0===v?void 0:v.shyheader;v=!(!document.querySelector(".uxdia-c-series")&&!document.querySelector(".uxdia-c-sponsorship"));if("yesShyHeader"===f&&!v){var G,x,y=document.querySelector(".coreHeader"),w=document.querySelector(".uxdia-c-megamenu"),H=document.querySelectorAll(".uxdia-c-promo-header")[1],L=parseInt(null===(G= n.dataset)||void 0===G?void 0:G.scrolldowndistance),z=parseInt(null===(x=n.dataset)||void 0===x?void 0:x.scrollupdistance),N=n.dataset.shyheaderaftertimedelay;n=document.querySelector("header")||document.querySelector(".everywhere-header.aarp-blog-header-sticky");var R=[],D=!1,Q=function(k){var m=document.querySelector("body.offerEvolPage");if(m&&!m.classList.contains("iframe-offer-evol-page")){var t=m.querySelector(".mvc-u-breadcrumb-odp-container");m=m.querySelector(".mvc-u-title-odp");t&&m&&(k? (t.style.top="0",m.style.top=t.offsetHeight-1+"px"):(k=window.matchMedia("(min-width: 1025px)").matches?120:60,t.style.top=k+"px",m.style.top=k+t.offsetHeight-1+"px"))}},e=function(k,m){"add"===m?k.forEach(function(t){null===t||void 0===t?void 0:t.classList.add("hideNavigation");Q("headerHidden")}):k.forEach(function(t){null===t||void 0===t?void 0:t.classList.remove("hideNavigation");Q()})},g=function(k){var m;null===k||void 0===k?void 0:k.scrollIntoView({behavior:"smooth"});null===(m=document.querySelector(".uxdia-leaderboard-js--sticky"))|| void 0===m?void 0:m.classList.remove("uxdia-leaderboard-js--sticky");window.addEventListener("scrollend",l)},l=function m(){e([y,w,H],"add");R.forEach(function(t){return clearInterval(t)});window.removeEventListener("scrollend",m)};f=function(m){var t;if("showNavigation"===m.detail)e([y,w,H],"remove");else if("hideNavigation"===m.detail)e([y,w,H],"add");else if("megaMenuClosed"===m.detail)D=!1;else if("Playing"===(null===(t=m.detail)||void 0===t?void 0:t.status)){var J,K=document.querySelector(".".concat(null=== (J=m.detail)||void 0===J?void 0:J.dynamicClassName));K&&(K.style.scrollMarginTop="30px",g(K),K.addEventListener("click",function(){var u=K.getBoundingClientRect().top;(2u)&&!y.classList.contains("hideNavigation")&&g(K)}))}};G=function(){return D=!0};var p=function(){return D=!1};x=function(){var m=window.pageYOffset||document.documentElement.scrollTop,t="down",J="",K=function(){var u=window.pageYOffset||document.documentElement.scrollTop;if(0L)dispatchEvent(new CustomEvent("activateShyHeader",{detail:"hideNavigation"}));else if(!D){var M=document.querySelector(".uxdia-leaderboard-js--sticky");mz?dispatchEvent(new CustomEvent("activateShyHeader",{detail:"showNavigation"})):"":M||(u-m>L?dispatchEvent(new CustomEvent("activateShyHeader",{detail:"hideNavigation"})):"")}m=u};return function(){R.push(setInterval(function(){K();R.forEach(function(u){return clearInterval(u)})},250));N&&"true"==N&&(clearTimeout(J), J=setTimeout(function(){var u=document.querySelector(".uxdia-leaderboard-js--sticky");null===y||void 0===y||!y.classList.contains("coreHeader--js-sticky")||y.classList.contains("hideNavigation")||u||K(!0)},3E3))}}();window.addEventListener("scroll",x);window.addEventListener("activateShyHeader",f);window.addEventListener("gamePlayStatus",f);null===n||void 0===n?void 0:n.addEventListener("mouseenter",G);null===n||void 0===n?void 0:n.addEventListener("mouseleave",p);[".uxdia-c-megamenu--close",".js-aarp-c-header__close-icon--megamenu", ".search-modal__header .close"].forEach(function(m){var t;return null===(t=document.querySelector(m))||void 0===t?void 0:t.addEventListener("click",p)})}};c();return{shyHeaderFunctionality:c}}();"use strict";function _toConsumableArray(c){return _arrayWithoutHoles(c)||_iterableToArray(c)||_unsupportedIterableToArray(c)||_nonIterableSpread()} function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");} function _unsupportedIterableToArray(c,v){if(c){if("string"===typeof c)return _arrayLikeToArray(c,v);var n=Object.prototype.toString.call(c).slice(8,-1);"Object"===n&&c.constructor&&(n=c.constructor.name);if("Map"===n||"Set"===n)return Array.from(c);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(c,v)}}function _iterableToArray(c){if("undefined"!==typeof Symbol&&Symbol.iterator in Object(c))return Array.from(c)} function _arrayWithoutHoles(c){if(Array.isArray(c))return _arrayLikeToArray(c)}function _arrayLikeToArray(c,v){if(null==v||v>c.length)v=c.length;for(var n=0,f=Array(v);na.steps_completed&&parseInt(d.currentStep)<=a.total_steps&&(a.steps_completed+=1,delete a.data,a=JSON.stringify(a),window.challengesStepDataPost(b.detail.targetEvent,{data:a})));a.steps_completed>a.total_steps&&(a.steps_completed=a.total_steps,delete a.data,window.challengesStepDataPost(b.detail.targetEvent,{data:a}))}else if(b&&"completeChallenge"===b.detail.data){var h,q={};b=null===(d=b.detail.targetEvent)||void 0===d?void 0:null===(a=d.currentTarget)||void 0===a?void 0: null===(h=a.dataset)||void 0===h?void 0:h.url;try{var r=JSON.parse(localStorage.getItem("ss-challenges-jsonp"));if(0!==Object.keys(r).length||r.constructor!==Object){var E=document.querySelector("#challengeId")?parseInt(document.querySelector("#challengeId").value):localStorage.getItem("CurrentChallengeId");q=window.getFilterChallenge(r,E);localStorage.setItem("CurrentChallengeId",E);q.steps_completed=q.total_steps;q.completed=!0;delete q.data;var A=JSON.stringify(q);e({data:A},b,"congratulation-modal")}}catch(F){e({}, b,""),console.log("No Challenges Data")}}})},p=function(){window.updateAddCount=function(a){var d=0;a&&a.item_response_list&&a.item_response_list.forEach(function(h){if("added"===(null===h||void 0===h?void 0:h.status)){var q;("en"==AARP.StayingSharp.locale||"es"==AARP.StayingSharp.locale&&null!==h&&void 0!==h&&null!==(q=h.item_details)&&void 0!==q&&q.item_id_es)&&d++}});return d};document.addEventListener("UPDATE_MYPLAN_COUNT",function(a){var d=a.detail;(a=window.parent!==window?window.parent.document.querySelectorAll("[data-formelementid\x3d'global-nav-ss-btn-clk-my-list-count']"): document.querySelectorAll("[data-formelementid\x3d'global-nav-ss-btn-clk-my-list-count']"))&&a.forEach(function(h){var q=document.createElement("span");q.classList.add("uxdia-sharp-c-my-plan-count");h.querySelector(".uxdia-sharp-c-my-plan-count")?q=h.querySelector(".uxdia-sharp-c-my-plan-count"):h.appendChild(q);q.textContent=d})});var b=function(a){a=window.updateAddCount(a?a:"");a=new CustomEvent("UPDATE_MYPLAN_COUNT",{detail:a});document.dispatchEvent(a)};(function(){if(window.ContextHub&&ContextHub.Utils&& ContextHub.Utils.Eventing){var a;null===(a=AARP.StayingSharp.ContextHubStore)||void 0===a?void 0:a.subscription("EVENT_LISTITEMS_STORE",function(){var d=JSON.parse(localStorage.getItem("ss-listItems-jsonp"));b(d||"")}).subscribe()}a=JSON.parse(localStorage.getItem("ss-listItems-jsonp"));b(a)})()},k=function(){document.querySelectorAll(".uxdia-c-user-state__element-join a").forEach(function(b){-1===b.href.indexOf("referrer")&&(b.href+="\x26referrer\x3d".concat(window.location.href))})},m=function(){var b, a,d,h,q=document.querySelector(".coreHeader.uxdia-ss-c-no-target-header"),r=document.querySelectorAll(".promoHeader.uxdia-c-no-target-header"),E=document.querySelector(".aarp-o-body-ctg"),A=null===(b=AARP)||void 0===b?void 0:null===(a=b.store)||void 0===a?void 0:null===(d=a.getState())||void 0===d?void 0:null===(h=d.cookie)||void 0===h?void 0:h.at;f&&f.classList.remove("sharp-c-header--anonymous","sharp-c-header--registered-non-member","sharp-c-header--registered-non-activate-member","sharp-c-header--member", "sharp-c-header--special-member");var F="CANCEL;EXPIRE;DECEASED SUSPEND;DECEASED_SUSPEND;MEMBER REQUEST SUSPEND;MEMBER_REQUEST_SUSPEND;UNDELIVERABLE SUSPEND;UNDELIVERABLE_SUSPEND".split(";");if(q){var B;E&&(b=void 0!==A?"loggedin":"anonymous",q.classList.remove("aarp-c-header--uxdia-ctg-".concat("loggedin"===b?"anonymous":"loggedin")),q.classList.add("aarp-c-header--uxdia-ctg-".concat(b)));var U={"anonymous-user":{"class":"aarp-c-header--uxdia-anonymous",deleteUserStates:[".uxdia-c-user-state__element-userData", ".aarp-c-ss-header__my-favourites",".uxdia-c-user-state__element-rejoin",".uxdia-c-user-state__element-enroll"],promoHeaderState:"keep"},"lifetime-member":{"class":"aarp-c-header--uxdia-member",deleteUserStates:".uxdia-c-user-state__element-join .uxdia-c-user-state__element-Login .uxdia-c-user-state__element-renew .uxdia-c-user-state__element-register .uxdia-c-user-state__element-rejoin .uxdia-c-user-state__element-enroll".split(" "),promoHeaderState:"remove"},"member-on-automatic-renew":{"class":"aarp-c-header--uxdia-member", deleteUserStates:".uxdia-c-user-state__element-join .uxdia-c-user-state__element-Login .uxdia-c-user-state__element-renew .uxdia-c-user-state__element-register .uxdia-c-user-state__element-rejoin .uxdia-c-user-state__element-enroll".split(" "),promoHeaderState:"remove"},"non-member":{"class":"aarp-c-header--uxdia-non-member",deleteUserStates:[".uxdia-c-user-state__element-Login",".uxdia-c-user-state__element-renew",".uxdia-c-user-state__element-register",".uxdia-c-user-state__element-rejoin",".uxdia-c-user-state__element-enroll"], promoHeaderState:"join"},"member-on-trail-period":{"class":"aarp-c-header--uxdia-non-member",deleteUserStates:[".uxdia-c-user-state__element-Login",".uxdia-c-user-state__element-renew",".uxdia-c-user-state__element-register",".uxdia-c-user-state__element-rejoin",".uxdia-c-user-state__element-enroll"],promoHeaderState:"join"},"member-not-on-automatic-renew":{"class":"aarp-c-header--uxdia-renew",deleteUserStates:[".uxdia-c-user-state__element-Login",".uxdia-c-user-state__element-join",".uxdia-c-user-state__element-register", ".uxdia-c-user-state__element-rejoin",".uxdia-c-user-state__element-renew"],promoHeaderState:"enroll"},"expiring-member":{"class":"aarp-c-header--uxdia-renew",deleteUserStates:[".uxdia-c-user-state__element-join",".uxdia-c-user-state__element-Login",".uxdia-c-user-state__element-register",".uxdia-c-user-state__element-rejoin",".uxdia-c-user-state__element-enroll"],promoHeaderState:"renew"},"suspended-member":{"class":"aarp-c-header--uxdia-member",deleteUserStates:[".uxdia-c-user-state__element-join", ".uxdia-c-user-state__element-Login",".uxdia-c-user-state__element-register",".uxdia-c-user-state__element-enroll",".uxdia-c-user-state__element-renew"],promoHeaderState:"rejoin"},"sponsor-subsciption-member":{"class":"aarp-c-header--uxdia-member",deleteUserStates:".uxdia-c-user-state__element-join .uxdia-c-user-state__element-Login .uxdia-c-user-state__element-renew .uxdia-c-user-state__element-register .uxdia-c-user-state__element-rejoin .uxdia-c-user-state__element-enroll .iconLink".split(" "), promoHeaderState:"remove"}},V=[".uxdia-c-user-state__element-join",".uxdia-c-user-state__element-renew",".uxdia-c-user-state__element-enroll",".uxdia-c-user-state__element-rejoin"],T={userType:"anonymous-user"},aa=function(C,I,O,Y,P,W){var X,Z;"ACTIVE"!==(null===C||void 0===C?void 0:C.membership_status)||W?F.includes(null===C||void 0===C?void 0:C.membership_status)?I.userType="suspended-member":null!==C&&void 0!==C&&null!==(X=C.access_and_features)&&void 0!==X&&X.activate_free_trail_stayingsharp? I.userType="member-on-trail-period":null!==C&&void 0!==C&&null!==(Z=C.access_and_features)&&void 0!==Z&&Z.active?W&&(I.userType="sponsor-subsciption-member","IMH"===W&&(I.userType="lifetime-member")):I.userType="non-member":I.userType=O&&"Y"==O?"member-on-automatic-renew":"member-not-on-automatic-renew";if(I.userType=="".concat(P,"member-on-automatic-renew")||I.userType=="".concat(P,"member-not-on-automatic-renew"))C=new Date,C.setDate(C.getDate()+180),Y=new Date(Y),C>Y&&"Y"!=O&&(I.userType="".concat(P, "expiring-member")),2800==Y.getFullYear()&&(I.userType="".concat(P,"lifetime-member"),(O=document.querySelector(".uxdia-c-fullwidth-membership-promo__container"))&&(O.style.display="none"));I.userType=="".concat(P,"lifetime-member")&&(P=document.querySelector(".uxdia-c-fullwidth-membership-promo__container"))&&(P.style.display="none");return I},ba=function(C){var I,O;switch(C){case "anonymous-user":null===f||void 0===f?void 0:f.classList.add("sharp-c-header--anonymous");break;case "registered-non-member":case "cancelled-or-expired-member":null=== f||void 0===f?void 0:f.classList.add("sharp-c-header--registered-non-member");"true"===(null===(I=ssUserInfo)||void 0===I?void 0:I.is_registered_non_member_activated)&&(k(),null===f||void 0===f?void 0:f.classList.add("sharp-c-header--special-member"),null===f||void 0===f?void 0:f.classList.add("sharp-c-header--special-member-rnma"),F.includes(ssUserInfo.membership_status)&&(null===f||void 0===f?void 0:f.classList.add("sharp-c-header--special-member-expired")));break;case "registered-non-activated-member":null=== f||void 0===f?void 0:f.classList.add("sharp-c-header--registered-non-activate-member");break;case "first-time-member":case "returning-member-content-access":case "returning-member-no-assessment-started":case "mbs-assessment-inProgress":case "lifestyle-completed-mbs-inProgress":case "returning-member-assessment-inProgress":case "returning-member-noAssessment-inProgress":case "assessment-taken-more-than-90-days-ago":null===f||void 0===f?void 0:f.classList.add("sharp-c-header--special-member");"true"=== (null===(O=ssUserInfo)||void 0===O?void 0:O.is_registered_non_member_activated)&&(k(),null===f||void 0===f?void 0:f.classList.add("sharp-c-header--special-member-rnma"),F.includes(ssUserInfo.membership_status)&&(null===f||void 0===f?void 0:f.classList.add("sharp-c-header--special-member-expired")));break;case "mbs-completed-lifestyle-inProgress":sessionStorage.removeItem("mbs-complete");null===f||void 0===f?void 0:f.classList.add("sharp-c-header--special-member");break;default:null===f||void 0=== f?void 0:f.classList.add("sharp-c-header--anonymous")}},fa=function(){var C;if("function"===typeof window.getContextHubData){var I,O;var Y=window.getContextHubData("ss-usertypes-jsonp");ssUserInfo=null===(I=Y)||void 0===I?void 0:null===(O=I.fullResponse)||void 0===O?void 0:O.user}if(!A||!ssUserInfo||!ssUserInfo&&"anonymous-user"===(null===(C=Y)||void 0===C?void 0:C.userType))T.userType="anonymous-user",T.error=!0,null===f||void 0===f?void 0:f.classList.add("sharp-c-header--anonymous");else if(A){var P, W,X,Z,ca,da;C=null===(P=Y)||void 0===P?void 0:P.userType;P=null===(W=ssUserInfo)||void 0===W?void 0:W.auto_renew;W=null===(X=ssUserInfo)||void 0===X?void 0:X.membership_expiration_date;X=null===(Z=ssUserInfo)||void 0===Z?void 0:null===(ca=Z.access_and_features)||void 0===ca?void 0:ca.sponsor;T.userType=null===(da=aa(ssUserInfo,T,P,W,"",X))||void 0===da?void 0:da.userType;ba(C);p()}M(T.userType,U);null===r||void 0===r?void 0:r.forEach(function(ea){ea&&ha(T.userType,U,ea,V)})};(null===(B=ContextHub)|| void 0===B?0:B.Utils)&&ContextHub.Utils.Eventing().on(ContextHub.Constants.EVENT_STORE_READY+":ss-usertypes-jsonp",function(){fa()},"usertypes",!0);fa();return T}},t=function(){var b,a,d,h;null===(b=window)||void 0===b?void 0:null===(a=b.ContextHub)||void 0===a?void 0:null===(d=a.Utils)||void 0===d?void 0:null===(h=d.Eventing())||void 0===h?void 0:h.on(ContextHub.Constants.EVENT_STORE_READY+":ss-usertypes-jsonp",function(){var q=window.getContextHubData("ss-usertypes-jsonp"),r=AARP.StayingSharp.utils.isInIframe(), E=r?window.parent.document.querySelector(".stayingSharpSpa"):document.querySelector(".stayingSharpSpa");localStorage.removeItem("cleanUserTypeStores");localStorage.removeItem("cleanAssessmentStores");(E&&r||!E)&&localStorage.removeItem("cleanListItemStores");if("anonymous-user"===(null===q||void 0===q?void 0:q.userType)){var A,F,B,U,V;q=document.querySelector("header.sharp-c-header-main-wrapper");r=document.querySelector("iframe.sharp-c-staying-sharp-spa-hot-container");q&&(null===r||void 0===r?void 0: null===(A=r.contentWindow)||void 0===A?void 0:null===(F=A.document)||void 0===F?void 0:null===(B=F.body)||void 0===B?void 0:null===(U=B.querySelector("header"))||void 0===U?void 0:null===(V=U.classList)||void 0===V?void 0:V.add("sharp-u-hidden"));D()}},"usertypes",!0)},J=function(){var b,a,d,h,q=null===(b=document.querySelector("#isVendorWrapper"))||void 0===b?void 0:b.value;b=null===(a=window.ContextHub)||void 0===a?void 0:null===(d=a.getStore)||void 0===d?void 0:null===(h=d.call(a,"ss-usertypes-jsonp"))|| void 0===h?void 0:h.getItem("/");q||"undefined"!==typeof b||(a=JSON.parse(localStorage.getItem("ContextHubPersistence")),b=null===a||void 0===a?void 0:a.store["ss-usertypes-jsonp"]);"true"===q&&(D(),document.querySelectorAll(".sharp-c-myplan").forEach(function(r){r.classList.add("sharp-u-hidden")}));m()},K=function(){var b;N();R();if(null!==(b=ContextHub)&&void 0!==b&&b.Utils)ContextHub.Utils.Eventing().on(ContextHub.Constants.EVENT_STORE_READY+":ss-usertypes-jsonp",function(){J()},"userItems",!0)}, u=function(){document.body.style.opacity=1;if(!AARP.cookies.at&&AARP.StayingSharp.apiConstants.cookie().ss_user){var b,a,d,h,q,r;localStorage.setItem("cleanUserTypeStores","true");localStorage.setItem("cleanAssessmentStores","true");localStorage.setItem("cleanListItemStores","true");null===(b=AARP)||void 0===b?void 0:null===(a=b.StayingSharp)||void 0===a?void 0:null===(d=a.SessionData)||void 0===d?void 0:d.setChallengesShape(null);null===(h=AARP)||void 0===h?void 0:null===(q=h.StayingSharp)||void 0=== q?void 0:null===(r=q.SessionData)||void 0===r?void 0:r.setFitnessData(null);x()}b=AARP.StayingSharp.getPageName();a=document.body;"anonymousPage"===b?a.classList.add("sharp-js-anonymous-home","sharp-c-anonymous-home"):"authenticated"===b?a.classList.add("sharp-js-authenticated-home","sharp-c-authenticated-home"):"whatIsStayingSharp"===b?a.classList.add("sharp-js-about-staying-sharp"):"problem-solving-challenge"===b?a.classList.add("sharp-js-problem-solving-challenge"):-1a.length)b=a.length;for(var c=0,d=Array(b);cb.indexOf(c)})} function getActionFromKey(a,b){var c=a.key,d=a.altKey,e=a.ctrlKey;a=a.metaKey;var f=["ArrowDown","ArrowUp","Enter"," "];if(!b&&f.includes(c))return SelectActions.Open;if("Home"===c)return SelectActions.First;if("End"===c)return SelectActions.Last;if("Backspace"===c||"Clear"===c||1===c.length&&" "!==c&&!d&&!e&&!a)return SelectActions.Type;if(b){if("ArrowUp"===c&&d)return SelectActions.CloseSelect;if("ArrowDown"!==c||d){if("ArrowUp"===c)return SelectActions.Previous;if("PageUp"===c)return SelectActions.PageUp; if("PageDown"===c)return SelectActions.PageDown;if("Escape"===c)return SelectActions.Close;if("Enter"===c||" "===c)return SelectActions.CloseSelect}else return SelectActions.Next}} function getIndexByLetter(a,b){var c=2e+d;ad)return!1}}var e="".concat(this.idBase,"-").concat(this.activeIndex);this.comboEl.setAttribute("aria-activedescendant", e);var f=null===(b=this.el.querySelector("#".concat(e)))||void 0===b?void 0:b.getAttribute("value");f&&this.comboEl.setAttribute("data-formelementid","SEARCH-DROPDOWN-MODAL-".concat(f));f&&this.comboEl.setAttribute("onClick","s_objectID\x3d'SEARCH-DROPDOWN-MODAL-".concat(f,"';"));""!==e||isElementInView(this.comboEl)||this.comboEl.scrollIntoView({behavior:"smooth",block:"nearest"});c&&this.comboEl.focus()}}; function configureComboBox(){var a=document.querySelector(".combo-box-data");if(a=a&&a.innerText.trim()){var b="[".concat(a,"]");b=JSON.parse(b);document.querySelectorAll(".js-select").forEach(function(c){new Select(c,b)})}}var dispatchCustomEvent=function(a){a&&(a=new CustomEvent("customClickTrack",{detail:{formelementid:"SEARCH-DROPDOWN-MODAL--".concat(a),customlinkname:"SEARCH MODAL USER DROPDOWN CHANGE "}}),window.dispatchEvent(a))};configureComboBox();"use strict"; var _AARP, _AARP2, _AARP2$Externals; var lazyLoadImages = function lazyLoadImages() { var lazyImages = [].slice.call(document.querySelectorAll(".articlelazy > source, .articlelazy > .cmp-image__image")); if ("IntersectionObserver" in window && 'IntersectionObserverEntry' in window) { var lazyImageObserver = new IntersectionObserver(function (entries, observer) { entries.forEach(function (entry) { if (entry.isIntersecting) { var _lazyImage$nextElemen, _lazyImage$parentElem; var lazyImage = entry.target; if (lazyImage.parentElement.dataset.loading == 'lazy') { lazyImage.srcset = lazyImage.dataset.srcset; if (lazyImage.tagName.toUpperCase() === 'IMG') { lazyImage.src = lazyImage.dataset.src; } } (_lazyImage$nextElemen = lazyImage.nextElementSibling) === null || _lazyImage$nextElemen === void 0 ? void 0 : _lazyImage$nextElemen.classList.add('fade-in'); (_lazyImage$parentElem = lazyImage.parentElement) === null || _lazyImage$parentElem === void 0 ? void 0 : _lazyImage$parentElem.classList.remove('articlelazy'); var uxdiaSpinner = lazyImage.closest('.uxdia-c-image').querySelector('.uxdia-c-spinner'); if (lazyImage.complete) { if (uxdiaSpinner) { uxdiaSpinner.classList.add('aarp-u-hidden'); } } else { lazyImage.onload = function () { if (uxdiaSpinner) { uxdiaSpinner.classList.add('aarp-u-hidden'); } }; lazyImage.onerror = function () { console.error('onerror Image is having an Error', lazyImage); }; } lazyImageObserver.unobserve(lazyImage); } }); }); lazyImages === null || lazyImages === void 0 ? void 0 : lazyImages.forEach(function (lazyImage) { lazyImageObserver.observe(lazyImage); }); } }; if ((_AARP = AARP) !== null && _AARP !== void 0 && _AARP.readyStateLoader) { AARP.readyStateLoader(function () { lazyLoadImages(); }); } (_AARP2 = AARP) === null || _AARP2 === void 0 ? void 0 : (_AARP2$Externals = _AARP2.Externals) === null || _AARP2$Externals === void 0 ? void 0 : _AARP2$Externals.ContextHub.onLoad(function () { var _window, _window$ContextHub, _window$ContextHub$Ut, _window$ContextHub$Ut2; (_window = window) === null || _window === void 0 ? void 0 : (_window$ContextHub = _window.ContextHub) === null || _window$ContextHub === void 0 ? void 0 : (_window$ContextHub$Ut = _window$ContextHub.Utils) === null || _window$ContextHub$Ut === void 0 ? void 0 : (_window$ContextHub$Ut2 = _window$ContextHub$Ut.Eventing()) === null || _window$ContextHub$Ut2 === void 0 ? void 0 : _window$ContextHub$Ut2.on(window.ContextHub.Constants.EVENT_TEASER_LOADED, lazyLoadImages); }); // Below code is to add analytics tag to Magazine & Bulletins carousel var featureTileWrappers = document.querySelectorAll('.sharp-c-configurable-carousel__slides'); var titleLinkContainer = '.sharp-c-configurable-carousel__slide'; var magazineContentType = 'aarp publications'; var bulletinsContentType = 'aarp bulletin'; var bulletinsComponentId = 'Bulletin Cover'; var magazineComponentId = 'Publications Cover'; var bulletins = 'bulletins'; var magazine = 'magazine'; featureTileWrappers === null || featureTileWrappers === void 0 ? void 0 : featureTileWrappers.forEach(function (element) { var mainLinkTwo = element === null || element === void 0 ? void 0 : element.querySelectorAll(titleLinkContainer); mainLinkTwo === null || mainLinkTwo === void 0 ? void 0 : mainLinkTwo.forEach(function (list) { var _link$href$split$filt; var link = list === null || list === void 0 ? void 0 : list.querySelector('a'); // Code to extract title from href var splitTitle = (_link$href$split$filt = link === null || link === void 0 ? void 0 : link.href.split('/').filter(Boolean).pop()) !== null && _link$href$split$filt !== void 0 ? _link$href$split$filt : ''; var linkTitle = splitTitle === null || splitTitle === void 0 ? void 0 : splitTitle.split('.')[0]; var linkHref = link === null || link === void 0 ? void 0 : link.href; if (link) { /*** * Checking if link is related to bulletin or magazine * Analytics tags should be only for magazin & bulletins **/ if (linkHref.includes(bulletins)) { link.dataset.contentTitle = linkTitle.trim(); link.dataset.componentid = bulletinsComponentId; link.dataset.contentType = bulletinsContentType; } else if (linkHref.includes(magazine)) { link.dataset.contentTitle = linkTitle.trim(); link.dataset.componentid = magazineComponentId; link.dataset.contentType = magazineContentType; } } }); });AARP.readyStateLoader(() => { /* We are using text component for modal functionally so anchor data-target attribute must start with modal-id-{Id what author configured} */ const modalBtn = document.querySelectorAll('[data-target^="modal-id"]'); let modal, allNodes = document.querySelectorAll("*"), modalOpen = false, lastFocus, mOverlay, i; // This loop will get the modal Id for respected button and adds aria tags for modal modalBtn?.forEach((item) => { item.addEventListener("click", openNewModal); const modalId = item.getAttribute("data-target"); const modalContainer = document.getElementById(modalId); if (modalContainer?.parentElement.style) { modalOverlay = modalContainer.parentElement; //Aria tags for modal Accessibility modalOverlay.setAttribute("aria-hidden", "true"); modalOverlay.setAttribute("role", "dialog"); modalOverlay.setAttribute("aria-modal", "true"); modalContainer.setAttribute("tabindex", "0"); modalContainer.setAttribute("role", "document"); } }); function openNewModal(e) { e.preventDefault(); const modalId = e.currentTarget.getAttribute("data-target"); modal = document.getElementById(modalId); if ( modal?.parentElement.style && modal?.parentElement.classList.contains("uxdia-c-modal") ) { mOverlay = modal.parentElement; lastFocus = document.activeElement; mOverlay.classList.add("open"); mOverlay.setAttribute("aria-hidden", "false"); modalOpen = true; modal.focus(); //Check modal close button already exist in the DOM than remove form dom if (modal.querySelector(".uxdia-c-modal__close-button")?.style) { modal.querySelector(".uxdia-c-modal__close-button").remove(); } //Check modal backdrop already exist in the DOM than remove form dom if (document.querySelector(".uxdia-c-modal-backdrop")?.style) { document.querySelector(".uxdia-c-modal-backdrop").remove(); } // Adding modal backdrop let modalBackdrop = document.createElement("div"); modalBackdrop.classList.add("uxdia-c-modal-backdrop"); modalBackdrop.addEventListener("click", modalClose); document.body.appendChild(modalBackdrop); //As this modal is container approach by default we don't have close button, so adding close button let closeButton = document.createElement("button"); closeButton.setAttribute("aria-label", "close"); closeButton.classList.add("uxdia-c-modal__close-button"); closeButton.addEventListener("click", modalClose); modal.appendChild(closeButton); document.body.classList.add("uxdia-c-modal-open"); } } //Function to close the modal and removed unnecessary tags and classes function modalClose(e) { if (modalOpen && (!e.keyCode || e.keyCode === 27)) { mOverlay.setAttribute("aria-hidden", "true"); modal.setAttribute("tabindex", "-1"); modalOpen = false; mOverlay.classList.remove("open"); document.querySelector(".uxdia-c-modal-backdrop").remove(); lastFocus.focus(); document.body.classList.remove("uxdia-c-modal-open"); } } //Function to restrict focus should in the modal function focusRestrict(e) { if (modalOpen && !modal.contains(e.target)) { event.stopPropagation(); modal.focus(); } } for (i = 0; i < allNodes.length; i++) { allNodes.item(i).addEventListener("focus", focusRestrict); } document.addEventListener("keydown", modalClose); window.onclick = function (event) { if (event.target.classList.contains("uxdia-c-modal")) { modalClose(event); } }; }, false); AARP.readyStateLoader(() => { let urlParams = new URLSearchParams(window.location.search); let valueTileArray = urlParams.get("savingcards"); // To work sort function the parent container must have the #aarp-c-events__wrapper iD if (document.querySelector("#aarp-c-events__wrapper") && document.querySelector("#aarp-c-events__wrapper").getAttribute('data-wcmmode') !== "edit") { //adding data class for events to sort document.querySelectorAll("[data-savingscalctype]").forEach((el) => { const eventType = el.getAttribute("data-savingscalctype"); if(eventType.trim()){ el.parentElement.classList.add(`data-${eventType}`); } }); if (!(valueTileArray && /^[a-zA-Z-]*$/.test(valueTileArray) == true)) { valueTileArray = "r-ar-h-m-air-c-b-ag-ra-a-cr-ads"; } valueTileArray = valueTileArray.split("-"); for (let i = 0; i < valueTileArray.length; i++) { if ( document.getElementsByClassName( "data-" + valueTileArray[i] + "" ).length > 0 && valueTileArray[i] != "" ) { document .querySelector(".data-" + valueTileArray[i] + "") .setAttribute("data-card", i); } } document.querySelectorAll("[data-savingscalctype]").forEach((el) => { if (!el.parentElement.hasAttribute("data-card")) { el.parentElement.remove(); } }); var tiles = document.querySelectorAll("[data-savingscalctype]"); var tilesArray = Array.from(tiles); let sorted = tilesArray.sort(comparator); sorted.forEach((e) => { document .querySelector("#aarp-c-events__wrapper > div") .appendChild(e.parentElement); e.style.display = "block"; }); function comparator(a, b) { return a.parentElement.getAttribute("data-card") - b.parentElement.getAttribute("data-card"); } } }, false); AARP = AARP || {}; AARP.executePalantir = (() => { function toggleLocked(arryOfElements) { if (arryOfElements.length === 0) { return; } const knownUser = AARP.store.getState().knownUser; const isLocked = !(knownUser?.memberState === 'MEMBER'); arryOfElements.forEach(d => { if (!isLocked) { d.classList.remove('banner-moa-locked'); d.classList.add('banner-moa-unlocked'); } else { d.classList.add('banner-moa-locked'); d.classList.remove('banner-moa-unlocked'); } }) } //handle Banner icon for curated static containers function handleMoaIconForCurated() { const curatedImages = document.querySelectorAll('.curatedContainer .aem-Grid > .articleImage > .cmp-image'); const staticImages = document.querySelectorAll('.cmp-img--banner-membersonly > .cmp-image'); const moaLabels = document.querySelectorAll('.curatedcontainer .aem-Grid .banner-rewards-moa-container [data-moa-label]') const moaLabelsExternal = document.querySelectorAll('.cmp-text--banner-membersonly .banner-rewards-moa-container .banner-aarpMoa'); toggleLocked(curatedImages); toggleLocked(staticImages); toggleLocked(moaLabels); toggleLocked(moaLabelsExternal); } handleMoaIconForCurated(); const aiOuterContainer = document.querySelector('.aiOuterContainer'); if (!aiOuterContainer) { return null; } var options = { root: null, rootMargin: '0px', threshold: 0 }; const apiURL = typeof rfyPalantirEndpoint === 'undefined' ? '' : rfyPalantirEndpoint; const generateTransactionID = () => { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => { const randomNo = Math.random() * 16 | 0, v = ch == 'x' ? randomNo : (randomNo & 0x3 | 0x8); return v.toString(16); }); } const getCookieFromBrowser = (cookieName) => { var name = cookieName + "="; 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); if (c.indexOf(name) == 0) return decodeURIComponent(c.substring(name.length, c.length)); } return ""; } const amcvCookie = getCookieFromBrowser("AMCV_AA853BC75245B3CE0A490D4D%40AdobeOrg")?.split('|'); const mcmidIndex = amcvCookie?.indexOf('MCMID'); let mcmid; if (mcmidIndex !== -1 && amcvCookie[mcmidIndex + 1].length > 20) { mcmid = amcvCookie[mcmidIndex + 1]; } txID = `${Date.now()}${crypto?.randomUUID().substring(0, 7)}`; const changeURLhost = (url) => { if (!url) return ''; const currentHost = window.location.hostname; const subdomain = currentHost.split('.')[0]; const isApp = (/nowapp-s|nowapp-pi|nowapp-d|nowapp/g).test(subdomain); try { const parsedUrl = new URL(url); if (isApp) { if(parsedUrl.hostname === 'www.aarp.org') { parsedUrl.hostname = currentHost; return parsedUrl.toString(); } return parsedUrl.toString(); } else { return url; } } catch (error) { if (isApp) { return `https://${currentHost}${url}` } else { return `https://www.aarp.org${url}`; } } } const createPayload = () => { const ecid = (window._satellite && _satellite.getVisitorId()?.getMarketingCloudVisitorID()) || mcmid || window?._svDataLayer?.cid_key || '111111111111111111111111111111111111111'; const konnexId = AARP?.store?.getState()?.cookie?.at?.cid || AARP?.store?.getState()?.cookie?.ufo?.p; const containers = document.querySelectorAll('.aiOuterContainer'); let requestBundle = []; let requestData = []; let basicDetails = { "channel": "website", "url": window.location.href, "txid": txID, } if (konnexId) { basicDetails['konnex'] = konnexId; } else if (ecid) { basicDetails['ecid'] = ecid; } containers?.forEach(data => { let placementVal = data.closest('.cmp-experiencefragment')?.getAttribute('rfyIndex') || data.getAttribute('data-rfyindex'); let obj = { componentId: data.getAttribute('id'), 'count': data.querySelectorAll('.aiOuterContainer>.aem-Grid>.container>.cmp-container:not(.curatedcontainer)')?.length?.toString(), 'model': data.getAttribute('data-model') } if (data.getAttribute('data-filter')) { obj.filter = `latitude: ${localStorage.getItem('aarpLat')}|longitude: ${localStorage.getItem('aarpLng')}|${data.getAttribute('data-filter')}`; } else { obj.filter = `latitude: ${localStorage.getItem('aarpLat')}|longitude: ${localStorage.getItem('aarpLng')}`; } if (placementVal) obj.placement = placementVal; requestBundle.push(obj) }) requestData.push({ ...basicDetails, requestBundle: requestBundle.filter(request => request.count !== '0') }) return { requestData }; } async function apiRequestThenable(apiURL) { let response; let result; let backupApi = "/etc/aarp/palantir/consolidatedFallbackContent.json"; let URL = apiURL ? apiURL : backupApi try { response = await fetch(URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(createPayload()) }); result = await response.json(); let apiResponseData = result.responseData[0].responseBundle; let idsWithNoResponse = apiResponseData.filter(a => a.response.length === 0).map(x => x.componentId); if(idsWithNoResponse.length > 0){ let fbResponse = await fetch(backupApi, { method: 'GET' }); let fbResult = await fbResponse.json(); let fbResponseData = fbResult.responseData[0].responseBundle; const replaceEmptyResponses = (result, fbResponseData) => { let idMap = new Map(fbResponseData.map(obj => [obj.componentId, obj])); let newResult = result.map(item => { const modelId = document.getElementById(item.componentId)?.getAttribute('data-model') if (item.response.length === 0 && idMap.has(modelId)) { // return a shallow copy and mark it as coming from fallback return { ...idMap.get(modelId), __fallback: true }; } return item }); return newResult } result = {...result,responseData:[{...result.responseData[0], responseBundle: replaceEmptyResponses(apiResponseData, fbResponseData)}]} } if (result?.errorCode || result?.responseData?.length <= 0) { throw new Error('Error code'); } } catch (error) { if (backupApi) { response = await fetch(backupApi, { method: 'GET' }); result = await response.json(); // mark that this entire response bundle is from fallback result["fbTxId"] = txID; if (result?.responseData?.[0]?.responseBundle) { result.responseData[0].responseBundle = result.responseData[0].responseBundle.map(item => ({ ...item, __fallback: true })); } } else { console.log(error) return; } } return result; }; // code to build DAM url for content dam images const extractDetailsFromImgPath = (imageURL, host) => { try { const url = new URL(imageURL); const path = url.pathname; const protocol = url.protocol; const domain = url.hostname; const extension = imageURL.split('.').pop().split(/\#|\?/)[0]; return { domain: `${protocol}//${host}`, extension, path } } catch { return { path: '#' } } } const buildDAMUrl = (viewport, src, imgPath, host) => { const viewportLookup = { '375': '.coreimg.50.375', '425': '.coreimg.50.425', '768': '.coreimg.50.688', } try { const srcUrl = new URL(src); const { domain, extension, path } = extractDetailsFromImgPath(src, host); return `${domain}${imgPath}${viewportLookup[viewport]}.${extension}${path}` } catch { return '#' } } const createImageElement = (img, src, alt, host, cIndex, imgPath) => { const imgElement = img.querySelector('img'); // pictureTag img if (src.includes('widen.net')) { try { let newUrl = new URL(src); if(!newUrl.searchParams.has('w') && !newUrl.searchParams.has('h')) { newUrl.searchParams.delete("crop"); } const cleanedUrl = newUrl.toString(); img.querySelector('#max375')?.setAttribute('srcset', cleanedUrl.concat(`&width=375`)); img.querySelector('#max425')?.setAttribute('srcset', cleanedUrl.concat(`&width=425`)); img.querySelector('#max768')?.setAttribute('srcset', cleanedUrl.concat(`&width=768`)); } catch (error) { console.log(error, 'Invalid URL'); } } else if (src.includes('custom.cvent')) { img.querySelector('#max375')?.setAttribute('srcset', src); img.querySelector('#max425')?.setAttribute('srcset', src); img.querySelector('#max768')?.setAttribute('srcset', src); } else { img.querySelector('#max375')?.setAttribute('srcset', buildDAMUrl('375', src, imgPath, host)); img.querySelector('#max425')?.setAttribute('srcset', buildDAMUrl('425', src, imgPath, host)); img.querySelector('#max768')?.setAttribute('srcset', buildDAMUrl('768', src, imgPath, host)); } let newSrc = extractDetailsFromImgPath(src,host).path; src = src.startsWith('/content/dam') ? `https://${host}${src}` : src; imgElement.src = src; imgElement.alt = alt ? alt : ''; imgElement.className = "cmp-image__image cmp-image__image@tablet"; if (cIndex >= 4) { imgElement.setAttribute('loading', 'lazy'); } else { imgElement.setAttribute('loading', 'eager'); } return imgElement; } const createAnchorElement = (href = '#', textContent) => { const anchorElement = document.createElement('a'); anchorElement.href = href; anchorElement.textContent = textContent ? textContent : ''; return anchorElement; } const getFormattedDate = (timestamp) => { let date = new Date(timestamp); date = date.getTime() + (date.getTimezoneOffset() * 60000); date = new Date(date); const monthName = ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]; const year = date.getFullYear(); const month = date.getMonth(); const day = date.getDate().toString() .padStart(2, '0'); let name = monthName[month]; return `${name} ${day}, ${year} ` // Format MM/DD/YYYY } const handleBanners = (variation, image, banner, ic) => { const hasNoImgMoa = ic.querySelector('.no-img-moa'); // Get index const getIndexOfBanner = (banner, charToCompare) => { const bannerValues = banner ? banner.split(',').map(s => s.toLowerCase()) : []; return bannerValues.findIndex(i => i.includes(charToCompare?.toLowerCase())); } // Check for Membership access and get Icon const knownUser = AARP.store.getState().knownUser; const isLocked = !(knownUser?.memberState === 'MEMBER'); const memberOnlyIndex = getIndexOfBanner(banner, 'membersOnly'); const newIndex = getIndexOfBanner(banner, 'New'); const rewardsIndex = getIndexOfBanner(banner, 'Rewards'); const rewardsMoaContainer = ic.querySelectorAll('.banner-rewards-moa-container'); const rewardsMoaContainerLast = rewardsMoaContainer?.[rewardsMoaContainer.length -1]; let imgmoa = ic.querySelector('.imgMoaContainer') if (rewardsIndex !== -1) { rewardsMoaContainerLast?.classList.add('cmp-text--banner-rewards'); } const membersInline = ic.querySelector('.cmp-text--banner-membersonly .js-banner-aarpMoa'); const rewards = ic.querySelector('.cmp-text--banner-rewards .js-banner-aarpRewards'); let titleElem = ic.querySelector('.js-rfytitle') // Show MOA on image. If no image show at the bottom if (memberOnlyIndex !== -1) { // small image in teritiary section if (hasNoImgMoa) { rewardsMoaContainerLast?.classList.add('cmp-text--banner-membersonly') if (!isLocked) { rewardsMoaContainerLast?.querySelector('.js-banner-aarpMoa').classList.add('banner-moa-unlocked'); rewardsMoaContainerLast?.querySelector('.js-banner-aarpMoa').classList.remove('banner-moa-locked'); } } if (variation == "aiimage" && image && imgmoa) { imgmoa.querySelector('.banner-moaBadge')?.classList.remove('aarp-u-hidden') imgmoa?.classList.add('cmp-img--banner-membersonly') if (!isLocked) { imgmoa.querySelector('.banner-moaBadge')?.classList.add('banner-moa-unlocked') imgmoa.querySelector('.banner-moaBadge')?.classList.remove('banner-moa-locked') } } else { rewardsMoaContainerLast?.classList.add('cmp-text--banner-membersonly') rewardsMoaContainerLast?.querySelector('.js-banner-aarpMoa')?.classList.remove('.aarp-u-hidden'); if (!isLocked) { rewardsMoaContainerLast?.querySelector('.js-banner-aarpMoa')?.classList.add('banner-moa-unlocked') rewardsMoaContainerLast?.querySelector('.js-banner-aarpMoa')?.classList.remove('banner-moa-locked') } } } else { imgmoa?.querySelector('.banner-moaBadge')?.classList.add('aarp-u-hidden') membersInline?.classList.add('aarp-u-hidden') } // Show NEW badge if (newIndex !== -1) { titleElem?.querySelector('.js-rfytitle')?.setAttribute('data-new-label', 'NEW') titleElem?.classList.add('cmp-title--banner-new') } // Hide Rewards if (rewardsIndex === -1) { rewards?.classList.add('aarp-u-hidden') } } const disPatchAnalyticsEvent = (item) => { if (!item) return null; const events = item.querySelector('.events').value; const products = item.querySelector('.products').value; const model = item.querySelector('.model').value; const region = item.querySelector('.region').value; const txid = item.querySelector('.txid').value; const customlinkname = 'Product Impression'; const track = new CustomEvent('customImpTrack', { detail: { region: region, events: events, products: products, model: model, customlinkname: customlinkname, txid: txid } }); window.dispatchEvent(track); }; const setAnalytics = (ele, obj) => { Object.keys(obj).forEach(attr => { ele.setAttribute(attr, obj[attr]) }); } // IntersectionObserver to call API only when any aiOuterContainer is in viewport let apiCalled = false; const apiObserverOptions = { root: null, rootMargin: '0px', threshold: 0.1 }; const apiObserver = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting && !apiCalled) { apiCalled = true; // Call the API when any container enters viewport executeApiCall(); // Disconnect observer after API call apiObserver.disconnect(); } }); }, apiObserverOptions); // Observe all aiOuterContainer elements const containers = document.querySelectorAll('.aiOuterContainer'); containers.forEach(container => { apiObserver.observe(container); }); // Shuffle helper (Fisher-Yates) const shuffle = (arr) => { const a = arr.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; }; // Global pools for fallback responses so the same fallback item won't repeat // across top-level containers during this execution. const globalFallbackPools = new Map(); // function API call logic into a function function executeApiCall() { apiRequestThenable(apiURL).then(data => { const topLevelContainers = document.getElementsByClassName('aiOuterContainer'); let componentIds = Array.from(topLevelContainers).map(comp => comp.getAttribute('id')); let result = data?.responseData[0]; let txIdResponse = data?.fbTxId ? "fb:" + data?.fbTxId : result?.txid ? result.txid : txID; componentIds.forEach((cid, cIndex) => { const outerContainer = document.getElementById(cid); const model = outerContainer?.getAttribute('data-model'); const rfyIndex = outerContainer?.closest('.cmp-experiencefragment')?.getAttribute('rfyIndex') || outerContainer?.getAttribute('data-rfyindex'); const count = outerContainer.querySelectorAll('.aiOuterContainer>.aem-Grid>.container>.cmp-container:not(.curatedcontainer)')?.length const innerContainers = outerContainer.querySelectorAll('.aiOuterContainer>.aem-Grid>.container>.cmp-container:not(.curatedcontainer)'); const events = outerContainer.querySelector('.events'); const products = outerContainer.querySelector('.products'); const modelAttr = outerContainer.querySelector('.model'); const regionElem = outerContainer.querySelector('.region'); const txIdApi = outerContainer.querySelector('.txid'); const host = outerContainer.querySelector('.hostName')?.value; const region = ['cc:' + model, count, rfyIndex].filter(Boolean).join("|"); if (regionElem) regionElem.value = region; if (txIdApi) txIdApi.value = txIdResponse; innerContainers.forEach((ic, index) => { const prodPos = index + 1; let shimmers = ic.querySelectorAll('.js-rfy-shimmer') let img = ic.querySelector('.js-rfyimage'); const imgPath = ic.querySelector('.js-ai-image-path')?.getAttribute('value'); // Prefer a responseBundle entry whose componentId is "model|" // where the container's data-filter starts with that filterPrefix. // If not found, randomly pick any "model|" entry for this model, // then try component id (cid), then fall back to model. const filterAttr = outerContainer?.getAttribute('data-filter') || ''; let obj = result?.responseBundle?.find(s => s.componentId === cid); // 1) exact model|prefix match if (!obj && filterAttr) { obj = (result?.responseBundle || []).find(s => { if (!s?.componentId) return false; const parts = s.componentId.split('|'); return parts[0] === model && parts[1] && filterAttr.startsWith(parts[1]); }); } // 2) random model|filter candidate if (!obj) { const filterCandidates = (result?.responseBundle || []).filter(s => { if (!s?.componentId) return false; const parts = s.componentId.split('|'); return parts[0] === model && parts[1]; }); if (filterCandidates.length > 0) { obj = filterCandidates[Math.floor(Math.random() * filterCandidates.length)]; } } // 3) model match final fallback if (!obj) { obj = (result?.responseBundle || []).find(s => s.componentId === model); } if (!obj) return; const isFallback = !!obj.__fallback; let responseItem; if (isFallback) { //console.log(obj.componentId); // Use a global per-component pool so fallback items are unique across // all top-level containers. Key by the responseBundle componentId. const poolKey = obj.componentId || model || cid; if (!globalFallbackPools.has(poolKey) || globalFallbackPools.get(poolKey).length === 0) { const candidates = Array.isArray(obj.response) ? obj.response.slice() : []; globalFallbackPools.set(poolKey, shuffle(candidates)); } responseItem = globalFallbackPools.get(poolKey).shift(); } else { responseItem = obj.response?.[index]; } if (!responseItem) { //ic.remove(); return; } let { image = null, ctaText, category, mediumTitle, shortTitle, longTitle, longDesc, mediumDesc, shortDesc, ctaUrl, date, banner = null, id, imageAlt, srcModelTracking, icon, iconAlt, categoryURL } = responseItem; const modelValueType = id?.includes('-') ? id.split('-')[0] : 'offer'; shimmers.forEach(shimmer => shimmer.remove()); const linkEle = ic.querySelector('.js-rfy-button-link'); if (linkEle && ctaText && ctaUrl) { linkEle.text = ctaText; linkEle.setAttribute('href', changeURLhost(ctaUrl)); linkEle.classList.remove('aarp-u-hidden'); } let imgVariation = img?.dataset?.variation; if (img && imgVariation) { if (imgVariation == "aiimage" && image) { createImageElement(img, image, imageAlt, host, cIndex, imgPath); } else if (imgVariation == "aiicon" && icon) { createImageElement(img, icon, iconAlt, host, cIndex, imgPath); } } ic.querySelector('.aem-Grid .container .cmp-container > .articleimage')?.classList.add('no-img-moa') let categoryElement = ic.querySelector('.js-cmp-rfyeyebrow'); let subtitle = ic.querySelector('.js-cmp-rfysubtitle'); let title = ic.querySelector('.js-rfytitle.cmp-title__text'); const dateElement = ic.querySelector('.js-cmp-rfydate'); handleBanners(imgVariation, image, banner, ic); if (categoryElement) { categoryElement.innerHTML = category; if (categoryURL) { categoryElement.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); window.location.href = changeURLhost(categoryURL); }) } } if (subtitle) { let descVal; switch (subtitle.dataset.variation) { case 'longDesc': descVal = longDesc; break; case 'shortDesc': descVal = shortDesc; break; case 'mediumDesc': descVal = mediumDesc; break; default: descVal = mediumDesc; } subtitle.innerHTML = descVal; } if (title) { let titleVal; switch (title.dataset.variation) { case 'longTitle': titleVal = longTitle; break; case 'mediumTitle': titleVal = mediumTitle; break; case 'shortTitle': titleVal = shortTitle; break; default: titleVal = mediumTitle; } title.innerHTML = titleVal; } if (date && dateElement) { const formattedDate = getFormattedDate(date); dateElement.textContent = formattedDate; } ic.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); window.location.href = changeURLhost(ctaUrl); }) // Creating Impression Analytic Events const oldProducts = products?.value; const oldEvent = events?.value; const oldModel = modelAttr?.value; //removing coma,semicolon and pipes from category before passing to product string for impression tracking let impressionCategory = category.replace(/[,|; ]+/g, " "); if (prodPos != 1) { events.value = oldEvent + ',event90' + prodPos; products.value = oldProducts + ',' + impressionCategory + ';' + id + ';;;' + 'event90' + prodPos; modelAttr.value = oldModel + ',' + srcModelTracking; } else { events.value = oldEvent + 'event90' + prodPos; products.value = oldProducts + impressionCategory + ';' + id + ';;;' + 'event90' + prodPos; modelAttr.value = oldModel + srcModelTracking; } let analyticsObj = { 'data-formelementid': `GLOBAL-RFY-${modelValueType.toUpperCase()}-LNK-CLK-TOUT-SPOT` + prodPos, 'data-posid': prodPos, 'data-model': srcModelTracking, 'data-txid': txIdResponse, 'data-region': region, 'data-productID': id, 'data-prod-category': category } setAnalytics(ic, analyticsObj); }) if (count > 0) { // outer container var observer = new IntersectionObserver(elements => { elements.forEach(element => { if (element.isIntersecting) { disPatchAnalyticsEvent(outerContainer); observer.unobserve(outerContainer); } }); }, options); observer.observe(outerContainer); } }); }).catch(error => { console.error('API call failed:', error); }); } })(); AARP.readyStateLoader(() => { (() => { if (document.querySelector('.aarp-c-body-wrapper')?.classList?.contains('aarp-o-edit-mode-false') && document.querySelector('.aarp-c-body-wrapper')?.classList.contains('uxdia-c-wall-enabled')) { const bodyWrapperscroll = document.querySelector('.aarp-c-body-wrapper'); const restrictedDivs = document.querySelectorAll('.uxdia-c-restricted-access'); const wallXf = document.querySelector('.cmp-experiencefragment--paywall'); const ssLocalPage = (window.location.hostname).includes('cms-l') && (window.location.href).includes('staying-sharp'); const isStayingSharp = (window.location.hostname).includes('stayingsharp') || ssLocalPage; const triggerAnalyticsForWall = () => { const language = document.querySelector("meta[name=language]")?.content; const channelName = document.querySelector("meta[name=ChannelName]")?.content; const pageName = window.location.href; window.dispatchEvent(new CustomEvent('registerwall', { detail: { siteChannel: channelName, pageName: pageName, siteLanguage: language } })); } const addAccessibilityToRegisterwall = () => { document.querySelector('body')?.querySelectorAll('[tabindex="0"], a, button, iframe, input, svg, path, g').forEach((ele) => { // check if the parent of the ele is not the register paywall container class, header and megamenu then add the tabindex -1 if (!ele.closest('.uxdia-c-wall') && !ele.closest('.aarp-c-core-navigation') && !ele.closest('.coreHeader') && !ele.closest('.cmp-tabs') && !ele.closest('.searchModal') && !ele.closest('.uxdia-c-megamenu')) { ele.setAttribute('tabindex', "-1"); } }); } const showShimmer = () => { const shimmerWrapper = document.querySelector('.shimmer-wrapper'); const shimmerElement = document.createElement('div'); shimmerElement?.classList?.add('shimmer-wrapper'); shimmerElement.innerHTML = `
`; if (!shimmerWrapper) { wallXf?.appendChild(shimmerElement); } } const loadRegisterWall = () => { const knownUserData = AARP.store?.getState()?.knownUser; const paywallXf = document.querySelectorAll('.cmp-experiencefragment--paywall')[0]; const ssRnmUsersList = ['registered-non-member', 'cancelled-or-expired-member', 'registered-non-activated-member', 'anonymous-user']; const ssUserType = isStayingSharp && window.getContextHubData('ss-usertypes-jsonp')?.userType; const isSSRnmUser = ssUserType && ssRnmUsersList.includes(ssUserType); const registerwallClass = (isStayingSharp && ssUserType !== 'anonymous-user') ? '.uxdia-c-featured-article__paywall-wrapper' : '.uxdia-c-wall'; const registerWallContainer = document.querySelector(registerwallClass); const paywallFooterSS = paywallXf?.querySelector('.paywall ~ .articleImage, .paywall ~ .textImage'); const showWallClass = isStayingSharp ? 'showPaywall' : 'show-wall'; if (knownUserData?.memberState === "ANON" || isSSRnmUser) { showShimmer(); } const showRegisterWall = () => { bodyWrapperscroll?.appendChild(paywallXf); registerWallContainer?.classList?.add(showWallClass); isStayingSharp && paywallFooterSS && paywallFooterSS?.classList?.add('showPaywallFooter'); registerWallContainer?.classList?.remove('hide-wall'); bodyWrapperscroll?.classList?.add('uxdia-c-restrict-scroll'); restrictedDivs?.forEach(payWallEle => { payWallEle?.remove(); }); document.querySelector('footer')?.remove(); addAccessibilityToRegisterwall(); const shimmerWrapper = document.querySelector('.shimmer-wrapper'); if (registerWallContainer?.classList?.contains(showWallClass)) { shimmerWrapper?.remove(); // trigger analytics triggerAnalyticsForWall(); } }; const hideRegisterWall = () => { registerWallContainer?.classList?.add('hide-wall'); registerWallContainer?.classList?.remove(showWallClass); isStayingSharp && paywallFooterSS && paywallFooterSS?.classList?.remove('showPaywallFooter'); if(knownUserData?.memberState !== "ANON" || (ssUserType && !ssRnmUsersList.includes(ssUserType))) { const shimmerWrapper = document.querySelector('.shimmer-wrapper'); shimmerWrapper?.remove(); } }; if (registerWallContainer) { if (knownUserData?.memberState === "ANON" || isSSRnmUser) { showRegisterWall(); } else { hideRegisterWall(); } AARP.store.subscribe(function () { loadRegisterWall(); }); } else { hideRegisterWall(); } } loadRegisterWall(); AARP?.Externals?.ContextHub.onLoad(() => { window?.ContextHub?.Utils?.Eventing()?.on( window.ContextHub.Constants.EVENT_TEASER_LOADED, () => { loadRegisterWall(); }, 'wall', true); }); window.addEventListener("SHOW_REGISTER_WALL", loadRegisterWall()); } })(); }); AARP = AARP || {}; AARP.executePalantir = (() => { //AI swat Banner close icon document.addEventListener('BTN_CLICKED', function (e) { const originalEvent = e.detail.event; const clickedElement = originalEvent.target; const swatContainer = clickedElement.closest('#swatImageContainer'); const swatNoImageContainer = clickedElement.closest('#swatNoImageContainer'); if (swatContainer) { swatContainer.remove(); } if (swatNoImageContainer) { swatNoImageContainer.remove(); } }); // replacing mobile image section for swatbanner setTimeout(() => { const swat_containers = document.querySelectorAll('#swatImageContainer'); swat_containers.forEach((swat) => { const swatImage = swat.querySelector('#swatbannerImage .js-rfyimage'); if (swatImage) { const clone = swatImage.cloneNode(true); const mobile = swat.querySelector('#swatbannerImageMobile .js-rfyimage'); if (mobile) { mobile.replaceWith(clone); } } }); }, 2000) })(); AARP.readyStateLoader(() => { const JS_EVENT_CLICK = "JS_EVENT_CLICKED"; function initCustomClickListeners(className) { const elements = document.querySelectorAll(`${className}`); elements.forEach((element) => { element.setAttribute("tabindex", "0"); // Dispatch function function dispatchCustomClick() { const event = new Event(JS_EVENT_CLICK, { bubbles: true, cancelable: true, }); element.dispatchEvent(event); } // Support click + keyboard element.addEventListener("click", dispatchCustomClick); element.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); dispatchCustomClick(); } }); }); } initCustomClickListeners('div[data-target="clickable"]'); }, false); function initAskAARP(askAARPContainer) { // --- Constants --- const MAX_INPUT_LENGTH = 800; const SCROLL_THRESHOLD = 20; const TYPING_DELAY = 15; const TAB_INDEX_DEFAULT = 0; const TAB_INDEX_DISABLED = -1; // --- DOM Elements --- const LLM_ASK_FORM = askAARPContainer.querySelector('#llm_ask_form'); const LLM_ASK_INPUT = LLM_ASK_FORM?.querySelector('textarea[name="query"]'); const LLM_ASK_BTN = LLM_ASK_FORM?.querySelector('button[type="SUBMIT"]'); const ASK_CONTAINER = askAARPContainer.querySelector("[data-target='ask_container']"); const LEFT_RAIL_MENU = askAARPContainer.querySelector('#left_rail_menu'); const CLOSE_BUTTON = document.querySelector('#close_button_container'); const HAMBURGER_MENU = document.querySelector('#hamburger_mobile'); const RESPONSE_SECTION = askAARPContainer.querySelector('#ask_aarp_response_section'); const START_NEW_CHAT = document.querySelector("[data-target='new_chat_button']"); const SCROLL_DOWN_BTN = document.querySelector("[data-target='scroll_down']"); const ASK_AARP_HEADING = askAARPContainer.querySelector('.ask-response-header'); const EMPTY_INPUT_ERROR_MESSAGE = askAARPContainer.querySelector("[name='empty-input-error']"); const MAX_CHARACTER_INPUT_ERROR_MESSAGE = askAARPContainer.querySelector("[name='max-input-error']"); const API_ERROR_MESSAGES = askAARPContainer.querySelector("[name='API-error']")?.parentElement.getAttribute('data-cmp-constraint-message').split('\n'); const ERROR_ELEMENT = `

`; const API_FORBIDDEN_MSG = askAARPContainer.querySelector("[name='forbidden_403_msg']")?.value; const REDIRECT_URL = askAARPContainer.querySelector("[data-redirect-url]")?.getAttribute('data-redirect-url') || null; const SIDEBAR_BUTTONS_CONTAINER = askAARPContainer.querySelector('#sidebar_buttons_container'); const MEDICARE_BUTTON = askAARPContainer.querySelector("[data-target='medicare_button']"); const SOCIAL_SECURITY_BUTTON = askAARPContainer.querySelector("[data-target='social_security_button']"); // --- State Variables --- let isAskLandingPage = !!RESPONSE_SECTION; let agent = askAARPContainer.querySelector("[name='agent-name']")?.value || "medicare"; let socket; let sessionId = null; let interactionId = null; let llmResources = null; let llmFollowUpQuestion = null; let currentBotMessageEl = null; let scrollPosition = null; let buffer = new Map(); let nextSeq = 1; let typingQueue = ''; let isTyping = false; let isStreaming = false; let pendingReset = false; let currentBlock = null; let currentElement = null; let currentList = null; let currentOl = null; let lastOrderedLi = null; // used for nesting bullets let focusedElementBefore = null; let firstTabStop; let lastTabStop; let scrollTimeout; let initialHeadingPosition = null; let baseHeightAskContainer = null; // --- Reusable Utility Functions --- function enableButton(btn) { btn?.removeAttribute('disabled'); btn?.classList.add('active'); } function disableButton(btn) { btn?.setAttribute('disabled', 'disabled'); btn?.classList.remove('active'); } function setFocus(el) { if (window.innerWidth <= 767) return; el.focus(); } function setTabIndex(el, idx = 0) { el?.setAttribute('tabindex', idx); } function copyToClipboard(text, messageElement) { if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard .writeText(text) .then(() => { showMessage(messageElement, 'Content copied to clipboard!', true); }) .catch(() => { showMessage(messageElement, 'Failed to copy content.', false); }); } } function showMessage(el, msg, isSuccess = true) { if (!el) return; el.textContent = msg; el.classList.remove('error', 'success'); el.classList.add(isSuccess ? 'success' : 'error', 'visible'); setTimeout(() => { el.classList.remove('visible'); setTimeout(() => { el.textContent = ''; }, 500); }, 2000); } function showError(input, errorEl, msg) { if (!input || !errorEl) return; input.classList.add('uxdia-cmp-form-text__text--error'); errorEl.innerText = msg; errorEl.classList.add('active'); } function clearError(input, errorEl) { if (!input || !errorEl) return; input.classList.remove('uxdia-cmp-form-text__text--error'); errorEl.classList.remove('active'); errorEl.innerText = ''; } const subdomain = window.location.hostname.split('.')[0]; const isNowApp = (/nowapp-s|nowapp-pi|nowapp-d|nowapp/g).test(subdomain); const thoughts = [ 'Thinking about the answer ...', 'Looking up details... ', 'Reviewing the most accurate resources for you... ', 'Organizing response... ', ]; const endPoint = LLM_ASK_FORM?.querySelector('input[name="endPointUrl"]')?.value; const related_questions = LLM_ASK_FORM?.querySelector('input[name="related_questions"]')?.value; const checkQuery = localStorage.getItem('Ask_query'); const AI_THINK_STAR = ` `; let LLM_PROMPT_SECTION = askAARPContainer.querySelector("[data-target='llm_query_suggestion_section']"); function getLeftRailFocusableElements() { const focusableElementsString = `a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable]`; const focusableElements = Array.prototype.slice.call(LEFT_RAIL_MENU.querySelectorAll(focusableElementsString)); firstTabStop = focusableElements[0]; lastTabStop = focusableElements[focusableElements.length - 1]; } function checkIfShouldShowArrow(scrollSection) { if (!scrollSection || !SCROLL_DOWN_BTN) return; const nearBottom = scrollSection.scrollHeight - scrollSection.scrollTop <= scrollSection.clientHeight + SCROLL_THRESHOLD; if (nearBottom) { SCROLL_DOWN_BTN.classList.remove('active_scroll_down'); } else { SCROLL_DOWN_BTN.classList.add('active_scroll_down'); } } function handleResponseSectionScroll() { clearTimeout(scrollTimeout); scrollTimeout = setTimeout(() => { checkIfShouldShowArrow(RESPONSE_SECTION); }, 100); }; function init() { LLM_ASK_BTN?.setAttribute('disabled', 'disabled'); //Check weather the data comes from entry page if (checkQuery) { promptSuggestionsClick(checkQuery); localStorage.removeItem('Ask_query'); } if (isAskLandingPage) { initialHeadingPosition = ASK_AARP_HEADING.getBoundingClientRect().bottom; baseHeightAskContainer = initialHeadingPosition + (ASK_CONTAINER.offsetHeight - ASK_CONTAINER.querySelector('.ask_disclaimer_section').offsetHeight); setFocus(LLM_ASK_INPUT); addTabIndexLeftRailItems(); getLeftRailFocusableElements(); document.querySelector('body').setAttribute('style', `--base_height_ask_container: ${baseHeightAskContainer}px;`); if (window.innerWidth <= 767) { LLM_PROMPT_SECTION = askAARPContainer.querySelector("[data-target='llm_query_suggestion_section_mobile']"); } } else { LLM_PROMPT_SECTION?.parentNode.setAttribute('style', 'display: block'); } LLM_ASK_FORM?.insertAdjacentHTML('afterend', ERROR_ELEMENT); START_NEW_CHAT?.setAttribute('disabled', 'disabled'); if (SCROLL_DOWN_BTN && isAskLandingPage) { updateMeta(agent); RESPONSE_SECTION.addEventListener('scroll', handleResponseSectionScroll); SCROLL_DOWN_BTN?.addEventListener('click', () => { RESPONSE_SECTION.scrollTo({ top: RESPONSE_SECTION.scrollHeight, behavior: 'smooth', }); SCROLL_DOWN_BTN.classList.remove('active_scroll_down'); }); const observer = new MutationObserver(handleResponseSectionScroll); observer.observe(RESPONSE_SECTION, { childList: true, subtree: true }); } } function updateMeta(agent = "medicare") { let askMetaTag = document.querySelector("meta[id='ASK_AARP']"); if (!askMetaTag) { let metaTag = document.createElement("meta"); metaTag.setAttribute("name", agent); metaTag.setAttribute('id', 'ASK_AARP'); document.head.appendChild(metaTag); } else { askMetaTag.name = agent; } } function isMobileOrTablet() { const hasTouchEvent = 'ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; const userAgent = navigator.userAgent.toLowerCase(); const isMobileUA = /(android|iphone|ipad|ipod|blackberry|windows phone|opera mini|mobile)/.test(userAgent); const isSmallScreen = Math.max(window.screen.width, window.screen.height) < 1024; return hasTouchEvent && isMobileUA && isSmallScreen; } function autoGrow(e) { if (LLM_ASK_INPUT.value.trim().length > 0) { enableButton(LLM_ASK_BTN); } else { disableButton(LLM_ASK_BTN); } e.target.style.height = 'auto'; e.target.style.height = e.target.scrollHeight + 'px'; } function promptSuggestionsClick(containerText) { if(LLM_ASK_INPUT) { LLM_ASK_INPUT.value = containerText; enableButton(LLM_ASK_BTN); LLM_ASK_BTN.click(); } else { handleFormSubmit(null, {'From Prompt Suggestions': containerText})(); } } function resetPage() { LLM_ASK_BTN.classList.remove('loading', 'active'); START_NEW_CHAT?.removeAttribute('disabled'); MEDICARE_BUTTON?.removeAttribute('disabled'); SOCIAL_SECURITY_BUTTON?.removeAttribute('disabled'); isStreaming = false; if (LLM_ASK_INPUT.value.trim().length > 0) { enableButton(LLM_ASK_BTN); } else { disableButton(LLM_ASK_BTN); } } function resetBuffer() { // Reset buffer for next message buffer = new Map(); nextSeq = 1; typingQueue = ''; isTyping = false; currentBlock = null; currentElement = null; currentList = null; currentOl = null; lastOrderedLi = null; } function startNewChartClickHandler() { RESPONSE_SECTION && (RESPONSE_SECTION.innerHTML = ''); LLM_ASK_INPUT.value = ''; resetPage(); disableButton(START_NEW_CHAT); setFocus(LLM_ASK_INPUT); ASK_AARP_HEADING.classList.remove('active'); handleWSCallonCancel(); sessionId = crypto.randomUUID(); handleResponseSectionDOM(); } function copyTheResultClickHandler(copyElement) { const textToCopy = copyElement.innerText; const messageElement = document.querySelector('.show_copy_message'); copyToClipboard(textToCopy, messageElement); } function showThinkingDots(container) { const thinking = document.createElement('div'); thinking.className = 'ask-aarp__thinking-indicator'; thinking.innerHTML = ` ${AI_THINK_STAR}
${thoughts[0]}
`; container.appendChild(thinking); RESPONSE_SECTION && (RESPONSE_SECTION.scrollTop = RESPONSE_SECTION.scrollHeight); let thoughtIndex = 1; // Display rotating messages const thoughtInterval = setInterval(() => { let thinkingEle = document.querySelector('.ask-aarp__thinking-text'); if (thoughtIndex >= thoughts.length) { clearInterval(thoughtInterval); // stop when all thoughts have been shown return; } if (thinkingEle) { thinkingEle.innerHTML = thoughts[thoughtIndex]; } thoughtIndex++; }, 2000); } function removeThinkingDots(container) { const thinking = container.querySelector('.ask-aarp__thinking-indicator'); if (thinking) container.removeChild(thinking); } function addCopyShareSection(container) { const copyBtn = ` `; container.insertAdjacentHTML('beforeend', copyBtn); } function addFeedback(container) { const feedbackBtns = ` `; container.insertAdjacentHTML('beforeend', feedbackBtns); } RESPONSE_SECTION?.addEventListener('click', function (e) { const feedbackYesBtn = e.target.closest('.toolbar__feedback-button--yes'); const feedbackNoBtn = e.target.closest('.toolbar__feedback-button--no'); const copyButton = e.target.closest('.toolbar__copy-button'); if (feedbackYesBtn) { if (feedbackYesBtn.classList.contains('clicked')) { return; } const noBtn = feedbackYesBtn.nextElementSibling; feedbackYesBtn.classList.add('clicked'); setTabIndex(feedbackYesBtn, TAB_INDEX_DISABLED); noBtn.disabled = true; } else if (feedbackNoBtn) { if (feedbackNoBtn.classList.contains('clicked')) { return; } const yesBtn = feedbackNoBtn.previousElementSibling; feedbackNoBtn.classList.add('clicked'); setTabIndex(feedbackNoBtn, TAB_INDEX_DISABLED); yesBtn.disabled = true; } else if (copyButton) { const responseTextContainer = copyButton.parentElement.closest('.ask-aarp__response-answer')?.querySelector('.ask-aarp__bot-response-text'); if (responseTextContainer) { copyTheResultClickHandler(responseTextContainer); } } }); function addToolbar(container) { const toolbar = document.createElement('div'); toolbar.className = 'toolbar'; addCopyShareSection(toolbar); addFeedback(toolbar); container.appendChild(toolbar); } function addMessage(sender, text) { const message = document.createElement('div'); message.classList.add(sender); if (sender === 'ask-aarp__response-answer') { const question_elements = document.querySelectorAll(".ask-aarp__response-question"); let basHeight = initialHeadingPosition + 20 + ASK_CONTAINER.offsetHeight + question_elements[question_elements.length - 1].offsetHeight; message.setAttribute('style', `min-height: calc(100vh - ${basHeight}px)`); } const resourceHTML = `
`; message.innerHTML = `
${text.replace(/\n/g, '
')}
${sender === 'ask-aarp__response-answer' ? resourceHTML : ''}`; RESPONSE_SECTION?.appendChild(message); if (sender !== 'ask-aarp__response-question') { RESPONSE_SECTION && (RESPONSE_SECTION.scrollTop = RESPONSE_SECTION.scrollHeight); } return message; } function setChatWindow(question, inputElement) { addMessage('ask-aarp__response-question', question); inputElement.value = ''; inputElement.style.height = 'auto'; window?.scrollTo({ top: 0, behavior: 'smooth', }); setTimeout(() => { RESPONSE_SECTION?.setAttribute( 'style', `--search_box_height: ${ASK_CONTAINER.offsetHeight + initialHeadingPosition}px;` ); }, 120); currentBotMessageEl = addMessage('ask-aarp__response-answer', ''); showThinkingDots(currentBotMessageEl); } async function handleUserMessage(ev, question, index) { ev.preventDefault(); if (isStreaming) { return; } await ensureWebSocketConnected(); handleResponseSectionDOM('active'); setChatWindow(question, LLM_ASK_INPUT); isStreaming = true; socket.send(JSON.stringify({ prompt: question, sessionId: sessionId, agent })); setFocus(LLM_ASK_INPUT); localStorage.setItem('eventNameForAnalytics', `LLM-BTN-CLK-ASK_AARP_${index + 1}`) } function formateNowAppLinks(link) { const mainDomainRegex = /www-s.aarp.org|www-pi.aarp.org|www-d.aarp.org|www.aarp.org/g; const isMainDomainLink = (mainDomainRegex).test(link); const isRelativeUrl = !/^(?:[a-z][a-z0-9+.-]*:)?\/\//i.test(link); let formatedLink = link; if (isNowApp && (isMainDomainLink || isRelativeUrl)) { formatedLink = formatedLink .replace(mainDomainRegex, window.location.host); if (formatedLink.endsWith('.html')) { formatedLink = formatedLink.slice(0, -5) + '/.now.html'; } else if (formatedLink.endsWith('/')) { formatedLink = formatedLink + '.now.html'; } else { formatedLink = formatedLink + '/.now.html'; } } return formatedLink; } function appendResources(resources, container, otherDetails) { if (!resources.length) return; const resourcesContainer = container.querySelector('.ask-aarp__response-resources'); let linksArray = []; let resourcesHTML = 'Sources: '; if (resources.length > 0) { linksArray = [...resources].map((resource, index) => { const formatedLink = formateNowAppLinks(resource.link); return `${resource.title.replace(/\n/g, '')}`; }); } resourcesHTML += linksArray.join(', '); if (resourcesContainer) { resourcesContainer.innerHTML = resourcesHTML; } } function appendFollowUpQuestion(questions, container) { const recContainer = document.createElement('div'); const recText = document.createElement('p'); const recDiv = document.createElement('div'); recContainer.className = 'ask-aarp__recommendations-container'; recText.className = 'ask-aarp__recommendations-text'; recDiv.className = 'ask-aarp__recommendations'; recText.innerText = related_questions; questions.forEach((q, index) => { const tile = document.createElement('a'); tile.href = '#'; tile.role = 'button'; tile.className = 'ask-aarp__recommendation-tile'; tile.textContent = q; tile.onclick = (ev) => handleUserMessage(ev, q, index); recDiv.appendChild(tile); }); recContainer.appendChild(recText); recContainer.appendChild(recDiv); container.appendChild(recContainer); } const dispatchAnalyticsEvent = (data) => { const track = new CustomEvent('customEngTrack', { detail: data }); window.dispatchEvent(track); } async function callWebSocket() { return new Promise((resolve, reject) => { socket = new WebSocket(endPoint); socket.onopen = () => { console.log('WebSocket connection established'); resolve(); }; socket.onerror = (err) => { console.error('WebSocket error:', err); dispatchAnalyticsEvent({ "data-eventName": localStorage.getItem('eventNameForAnalytics') ? localStorage.getItem('eventNameForAnalytics') : 'LLM-BTN-CLK-ASK_AARP', "data-language": 'en', "data-sessionid": '', "data-response": 'error', "data-responseid": '', "region": 'LLM', }); localStorage.removeItem('eventNameForAnalytics'); reject(err); }; socket.onmessage = (event) => { const msg = JSON.parse(event.data); const agentStatus = msg.status || msg.message_chunk switch (agentStatus) { case 'AGENT_STREAM_END': processStreamEnd(msg); break; case 'RESOURCES_USED': processResources(msg); break; case 'FOLLOWUP_QUESTIONS': processFollowupQuestions(msg); break; default: handleAgentStream(msg); } }; socket.onclose = (event) => { if (event.code === 1006 && event.reason === "") { handleAgentStreamError(event); } } }); } function handleAgentStream(msg) { const hasMessageChunkProperty = Object.prototype.hasOwnProperty.call(msg, "message_chunk"); if (hasMessageChunkProperty) { processStream(msg); } else { handleAgentStreamError(msg); } } function handleAgentStreamError(msg) { if (msg.message?.toLowerCase().includes('server error')) { if (!currentBotMessageEl) return; handleAgentStreamEnd(); } else if (msg.error) { handleErrorResponse(currentBotMessageEl); dispatchAnalyticsEvent({ "data-eventName": localStorage.getItem('eventNameForAnalytics') ? localStorage.getItem('eventNameForAnalytics') : 'LLM-BTN-CLK-ASK_AARP', "data-language": 'en', "data-sessionid": msg.sessionId, "data-response": 'error', "data-responseid": msg.interactionId, "region": 'LLM', }); localStorage.removeItem('eventNameForAnalytics'); addToolbar(currentBotMessageEl); } else if (msg.code) { handleErrorResponse(currentBotMessageEl, msg.code); } } function processStream(msg) { if (!msg.sequence && msg.sequence !== 0) { console.warn('Missing sequence number in chunk:', msg); return; } if (currentBotMessageEl) { removeThinkingDots(currentBotMessageEl); addSparkElement(); receiveChunk(msg) } } function processStreamEnd(msg) { handleStreamEnd(); sessionId = msg.sessionId; interactionId = msg.interactionId; dispatchAnalyticsEvent({ "data-eventName": localStorage.getItem('eventNameForAnalytics') ? localStorage.getItem('eventNameForAnalytics') : 'LLM-BTN-CLK-ASK_AARP', "data-language": 'en', "data-sessionid": msg.sessionId, "data-response": 'success', "data-responseid": msg.interactionId, "region": 'LLM', }); localStorage.removeItem('eventNameForAnalytics'); } function processResources(msg) { if (!currentBotMessageEl) return; if (msg.resources.length > 0) { llmResources = msg; } renderAfterTyping(); } function processFollowupQuestions(msg) { if (!currentBotMessageEl) return; if (msg.followup_questions) { llmFollowUpQuestion = msg; } renderAfterTyping(); } function addSparkElement() { if (!currentBotMessageEl.querySelector('.sparkle')) { const response_header = document.createElement('div'); response_header.innerHTML = AI_THINK_STAR; currentBotMessageEl.insertBefore( response_header, currentBotMessageEl.querySelector( '.ask-aarp__bot-response-text' ) ); } } function handleStreamEnd() { pendingReset = true; } function renderAfterTyping() { if (isTyping) return; if (!currentBotMessageEl) return; if (!currentBotMessageEl.querySelector('.toolbar')) { addToolbar(currentBotMessageEl); } if (llmResources) { appendResources([...llmResources.resources], currentBotMessageEl, { sessionId: llmResources.sessionId, interactionId: llmResources.interactionId }); llmResources = null; } if (llmFollowUpQuestion) { appendFollowUpQuestion([...llmFollowUpQuestion.followup_questions], currentBotMessageEl); llmFollowUpQuestion = null; } handleAgentStreamEnd(); } function receiveChunk({ sequence, message_chunk }) { if (typeof sequence !== 'number') return; buffer.set(sequence, message_chunk || ''); processChunks(); } function processChunks() { while (buffer.has(nextSeq)) { const chunk = buffer.get(nextSeq); buffer.delete(nextSeq); nextSeq++; typingQueue += chunk; } if (!isTyping) processTextToHtml(); } // Typing Animation (1 character per frame) function processTextToHtml() { let outputElement = currentBotMessageEl.querySelector('.ask-aarp__bot-response-text'); if (!typingQueue) { isTyping = false; if (pendingReset) { resetBuffer(); renderAfterTyping(); pendingReset = false; } return; } isTyping = true; if (!currentElement) { const preview = typingQueue.trimStart().slice(0, 40); const orderedMatch = preview.match(/^(\d+\.)\s+/); const unorderedMatch = preview.match(/^([-*•])\s+/); if (orderedMatch) { const prefixLen = orderedMatch[0].length; typingQueue = typingQueue.slice(prefixLen); if (orderedMatch[1] === '1.') { currentOl = document.createElement('ol'); currentOl.className = 'ask-aarp__bot-response-text__order_list'; outputElement.appendChild(currentOl); } const li = document.createElement('li'); currentOl.appendChild(li); currentElement = li; currentBlock = 'ol'; currentList = currentOl; lastOrderedLi = li; } else if (unorderedMatch) { const prefixLen = unorderedMatch[0].length; typingQueue = typingQueue.slice(prefixLen); let ul = currentList; const needsNewUl = !ul || currentBlock !== 'ul' || ul.tagName !== 'UL' || (lastOrderedLi && !lastOrderedLi.contains(ul)); if (needsNewUl) { ul = document.createElement('ul'); ul.className = 'ask-aarp__bot-response-text__un_oder_list'; if (lastOrderedLi) { lastOrderedLi.appendChild(ul); // nested } else { outputElement.appendChild(ul); // top-level } currentList = ul; currentBlock = 'ul'; } const li = document.createElement('li'); currentList.appendChild(li); currentElement = li; } else { currentBlock = 'p'; const p = document.createElement('p'); p.className = 'ask-aarp__bot-response-text__para'; outputElement.appendChild(p); currentElement = p; currentList = null; currentOl = null; lastOrderedLi = null; } } const char = typingQueue[0]; typingQueue = typingQueue.slice(1); if (char === '\n') { while (typingQueue.startsWith('\n')) { typingQueue = typingQueue.slice(1); } currentElement = null; } else { currentElement.append(char); } checkIfShouldShowArrow(RESPONSE_SECTION); setTimeout(processTextToHtml, TYPING_DELAY); } function handleAgentStreamEnd() { if (currentBotMessageEl) { currentBotMessageEl.querySelector('.sparkle').parentNode.remove(); currentBotMessageEl.removeAttribute('style'); currentBotMessageEl = null; } resetPage(); } function handleErrorResponse(currentBotMessageEl, errorCode) { const responseTextEl = currentBotMessageEl.querySelector('.ask-aarp__bot-response-text'); const errorMessagesLength = API_ERROR_MESSAGES.length; const randomIndex = Math.floor(Math.random() * errorMessagesLength); let errorMsg = ''; if (errorCode === 1006) { //added fallback message we can remove this once author handled this through author errorMsg = API_FORBIDDEN_MSG || "Thanks for your input; please try again."; if (currentBotMessageEl.querySelector('.toolbar')) { currentBotMessageEl.querySelector('.toolbar').remove(); } } else { errorMsg += API_ERROR_MESSAGES[randomIndex]; } handleWSCallonCancel(); removeThinkingDots(currentBotMessageEl); responseTextEl.innerHTML = errorMsg; resetPage(); currentBotMessageEl.removeAttribute('style'); } function handleResponseSectionDOM(loading) { if (loading === 'active') { LLM_PROMPT_SECTION?.parentNode.setAttribute('style', 'display: none'); askAARPContainer .querySelector('.ask_disclaimer_section') ?.setAttribute('style', 'display: none'); RESPONSE_SECTION?.classList.add('active'); LLM_ASK_BTN.classList.remove('active'); START_NEW_CHAT?.setAttribute('disabled', 'disabled'); MEDICARE_BUTTON?.setAttribute('disabled', 'disabled'); SOCIAL_SECURITY_BUTTON?.setAttribute('disabled', 'disabled'); LLM_ASK_BTN.classList.add('loading'); LLM_ASK_BTN.removeAttribute('disabled'); ASK_CONTAINER.classList.add('conversation_started'); } else { RESPONSE_SECTION?.removeAttribute('style'); RESPONSE_SECTION?.classList.remove('active'); ASK_CONTAINER.classList.remove('conversation_started'); LLM_PROMPT_SECTION?.parentNode.removeAttribute('style'); askAARPContainer .querySelector('.ask_disclaimer_section') ?.removeAttribute('style'); } } function handleWSCallonCancel() { if (socket && socket.readyState === WebSocket.OPEN) { socket.close(); } } // Helper to handle UI updates function setupResponseUI(question, inputElement) { const showMessageDiv = document.createElement('div'); showMessageDiv.setAttribute('class', 'show_copy_message'); if (!ASK_AARP_HEADING.classList.contains('active')) { ASK_AARP_HEADING.classList.add('active'); const { bottom, height } = ASK_AARP_HEADING.getBoundingClientRect(); scrollPosition = bottom + height; } RESPONSE_SECTION?.appendChild(showMessageDiv); handleResponseSectionDOM('active'); setChatWindow(question, inputElement) } // Helper to check WebSocket state and reconnect if needed async function ensureWebSocketConnected() { if (!socket || socket.readyState !== WebSocket.OPEN) { try { if (!sessionId) { sessionId = crypto.randomUUID(); } await callWebSocket(); } catch (err) { console.error('Failed to open WebSocket:', err); throw err; } } } function handleWSCancel() { socket.close(); removeThinkingDots(currentBotMessageEl); resetPage(); resetBuffer(); LLM_ASK_INPUT.focus(); currentBotMessageEl.querySelector('.sparkle')?.parentNode.remove(); currentBotMessageEl.removeAttribute('style'); } function checkFormInput(question) { const INPUT_ERROR = document.querySelector('.input-error'); if (!question) { showError(LLM_ASK_INPUT, INPUT_ERROR, EMPTY_INPUT_ERROR_MESSAGE.value); return false; } if (!handleMaxCharacterInput(question)) { return false; } return true; } function handleMaxCharacterInput(inputValue) { const INPUT_ERROR = document.querySelector('.input-error'); let inputResult = removeLineBreak(inputValue); let countLimit = inputResult.length - MAX_INPUT_LENGTH; if (inputResult.length > MAX_INPUT_LENGTH) { const result = MAX_CHARACTER_INPUT_ERROR_MESSAGE.value.replace('{%countlimit%}', countLimit); showError(LLM_ASK_INPUT, INPUT_ERROR, result); return false; } else if (LLM_ASK_INPUT.classList.contains('uxdia-cmp-form-text__text--error')) { clearError(LLM_ASK_INPUT, INPUT_ERROR); return true; } return true; } function removeLineBreak(inputElement) { const result = inputElement.replace(/\n/g, ''); return result; } function navigateToAskPage(question) { localStorage.setItem('Ask_query', question); let askPageLocation = null; // Extract query parameters for all scenarios const queryParams = new URLSearchParams(window.location.search); const encodedParams = Array.from(queryParams.entries()).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&'); const safeQuery = encodedParams ? `?${encodedParams}` : ''; if (REDIRECT_URL !== null) { // Check if REDIRECT_URL starts with http(s) - use as is if (REDIRECT_URL.startsWith('http://') || REDIRECT_URL.startsWith('https://')) { askPageLocation = `${REDIRECT_URL}${safeQuery}`; } // Check if REDIRECT_URL starts with /content - modify by removing path till home and add .html else if (REDIRECT_URL.startsWith('/content')) { // Extract path after /content/aarpe/en/home/ and add .html const pathAfterHome = REDIRECT_URL.replace(/^\/content\/[^\/]+\/[^\/]+\/home/, ''); if (AARP.Everywhere.isAuthor) { askPageLocation = `${window.location.origin}${REDIRECT_URL}${isNowApp ? '/.now' : ''}.html${safeQuery}`; } if (!AARP.Everywhere.isAuthor) { askPageLocation = `${window.location.origin}${pathAfterHome}${isNowApp ? '/.now.html' : ''}`; } } } else { // Fallback to original logic when REDIRECT_URL is not available if (AARP.Everywhere.isAuthor) { askPageLocation = `${window.location.origin}/content/aarpe/en/home/ask-aarp${isNowApp ? '/.now' : ''}.html${safeQuery}`; } else { askPageLocation = `${window.location.origin}/ask-aarp${isNowApp ? '/.now.html' : ''}`; } } window.open(askPageLocation, isNowApp ? "_self" : "_blank"); } function handleFormSubmit(inputElement, additionalArg) { return async function (e) { e?.preventDefault(); if (e?.target.classList.contains('loading')) { handleWSCancel(); return; } if(additionalArg && additionalArg['From Prompt Suggestions']) { navigateToAskPage(additionalArg['From Prompt Suggestions']); return; } const question = inputElement && inputElement.value.trim(); if (!checkFormInput(question)) return; const targetId = (e?.target && e.target.id) || ''; if (targetId === 'Submit_Channel_Entry') { navigateToAskPage(question); return; } try { setFocus(LLM_ASK_INPUT); await ensureWebSocketConnected(); setupResponseUI(question, inputElement); isStreaming = true; socket.send(JSON.stringify({ prompt: question, sessionId, agent })); } catch (err) { console.error('Unable to process request:', err); setupResponseUI(question, inputElement); handleErrorResponse(currentBotMessageEl); addToolbar(currentBotMessageEl); } }; } START_NEW_CHAT?.addEventListener('click', startNewChartClickHandler); LLM_ASK_INPUT?.addEventListener('input', function (e) { autoGrow(e); handleMaxCharacterInput(e.target.value.trim()); }); LLM_ASK_BTN?.addEventListener('click', (e) => handleFormSubmit(LLM_ASK_INPUT)(e)); LLM_ASK_INPUT?.addEventListener('keydown', function (e) { if (e.keyCode === 13) { if (e.shiftKey) { e.preventDefault(); const start = LLM_ASK_INPUT.selectionStart; const end = LLM_ASK_INPUT.selectionEnd; LLM_ASK_INPUT.value = LLM_ASK_INPUT.value.substring(0, start) + '\n' + LLM_ASK_INPUT.value.substring(end); LLM_ASK_INPUT.selectionStart = LLM_ASK_INPUT.selectionEnd = start + 1; autoGrow(e) } else { if (isMobileOrTablet()) return; e.preventDefault(); if (LLM_ASK_BTN.classList.contains('loading')) { return; } if (!checkFormInput(e.target.value.trim())) return; LLM_ASK_BTN.click(); } } }); LLM_ASK_INPUT?.addEventListener('focus', () => { if (isMobileOrTablet()) { setTimeout(() => { LLM_ASK_INPUT.scrollIntoView({ behavior: 'smooth', block: 'nearest', }); }, 200); } }); SIDEBAR_BUTTONS_CONTAINER?.addEventListener('click', (e) => { const target = e.target.closest('button'); if (target && target.dataset.target) { const value = target.dataset.target; const questions = askAARPContainer.querySelector(`[value='${value}']`)?.parentElement.getAttribute('data-cmp-constraint-message').split('\n'); const promptMessagesLength = questions.length; const randomIndex = Math.floor(Math.random() * promptMessagesLength); const promptText = questions[randomIndex]; LLM_ASK_INPUT.value = promptText; autoGrow({ target: LLM_ASK_INPUT }); LLM_ASK_BTN.click(); } }); window.addEventListener('beforeunload', () => { if (socket && socket.readyState === WebSocket.OPEN) { socket.close(); } }); askAARPContainer .querySelectorAll("div[data-target='clickable']") .forEach((el) => { el.addEventListener('JS_EVENT_CLICKED', (e) => { const promptText = e.target.innerText; localStorage.setItem('eventNameForAnalytics', e.target.id.replace('_MOBILE', '')); promptSuggestionsClick(promptText); }); }); const toggle = (event) => { if (window.innerWidth <= 1023) { event.stopPropagation(); LEFT_RAIL_MENU.classList.toggle('show'); } }; function trapTabKey(e) { if (e.keyCode === 9) { if (e.shiftKey) { if (document.activeElement === firstTabStop) { e.preventDefault(); lastTabStop.focus(); } } else { if (document.activeElement === lastTabStop) { e.preventDefault(); firstTabStop.focus(); } } } } function openPanel(event) { focusedElementBefore = document.activeElement; toggle(event); firstTabStop.focus(); document.querySelector('body').style.overflow = 'hidden'; document.querySelector('body').style.position = 'fixed'; RESPONSE_SECTION.style.overflowY = 'hidden'; LEFT_RAIL_MENU.addEventListener('keydown', trapTabKey); } function closePanel(event) { toggle(event); LEFT_RAIL_MENU.removeEventListener('keydown', trapTabKey); document.querySelector('body').removeAttribute('style'); document.querySelector('body').setAttribute('style', `--base_height_ask_container: ${baseHeightAskContainer}px;`); RESPONSE_SECTION.style.overflowY = 'auto'; if (focusedElementBefore) { focusedElementBefore.focus(); } } //hamburger menu HAMBURGER_MENU?.addEventListener('click', openPanel); HAMBURGER_MENU?.addEventListener('keydown', (e) => { if (e.key === "Enter") { e.preventDefault(); openPanel(e); } }); //close btn mobile CLOSE_BUTTON?.addEventListener('click', closePanel); CLOSE_BUTTON?.addEventListener('keydown', (e) => { if (e.key === "Enter") { e.preventDefault(); closePanel(e); } }); document.addEventListener('click', (e) => { if ( LEFT_RAIL_MENU?.classList.contains('show') ) { toggle(e); } }); function addTabIndexLeftRailItems() { setTabIndex(HAMBURGER_MENU, TAB_INDEX_DEFAULT); setTabIndex(CLOSE_BUTTON, TAB_INDEX_DEFAULT); if (HAMBURGER_MENU) { HAMBURGER_MENU.setAttribute('aria-label', 'Open menu'); } if (CLOSE_BUTTON) { CLOSE_BUTTON.setAttribute('aria-label', 'Close menu'); } } init(); } if (AARP && AARP.readyStateLoader) { AARP.readyStateLoader(function () { const LLM_AI_SECTIONS = document.querySelectorAll("[data-target='ask_aarp_container']"); if (LLM_AI_SECTIONS.length > 0) { LLM_AI_SECTIONS.forEach(section => { initAskAARP(section); }); } }, false); } console.log("Inside text.babel.js file");window.addEventListener('load', function() { urlParams = new URLSearchParams(window.location.search); jkcValue = urlParams.get("jkc"); rkcValue = urlParams.get("rkc"); cmpValue = urlParams.get("campaignid"); jCmpId = jkcValue || cmpValue || "UDFLTTC"; rCmpId = rkcValue || cmpValue || "ZDFLTTC"; assignJoinLink(jCmpId); assignRenewLink(rCmpId); function assignJoinLink(jCmpId) { if (document.querySelector("[data-target='joinNow']")) { document.querySelectorAll("[data-target='joinNow']").forEach(el => { joinLink = el.getAttribute("href"); const joinUrl = new URL(joinLink); let params = joinUrl.searchParams; if(params.has("campaignid")) { params.set('campaignid', jCmpId); } else { params.append('campaignid', jCmpId); } el.setAttribute("href", joinUrl); }); } } function assignRenewLink(rCmpId) { if (document.querySelector("[data-target='renew']")) { document.querySelectorAll("[data-target='renew']").forEach(el => { renewLink = el.getAttribute("href"); const renewUrl = new URL(renewLink); let params = renewUrl.searchParams; if(params.has("campaignid")) { params.set('campaignid', rCmpId); } else { params.append('campaignid', rCmpId); } el.setAttribute("href", renewUrl); }); } } const closeIcon = document.querySelector('.uxdia-c-close-icon button'); closeIcon?.addEventListener('click', () => { const closeContainer = document.querySelector('.uxdia-c-close-container-wrapper'); if (closeContainer?.style) { closeContainer.style.display = 'none' } }); const setCampaignID = () => { window?.ContextHub?.Utils?.Eventing()?.on( window.ContextHub.Constants.EVENT_TEASER_LOADED, function() { assignJoinLink(jCmpId); assignRenewLink(rCmpId); }); }; AARP.Externals.ContextHub.onLoad(setCampaignID); }); window.addEventListener('load', function() { const initializeVariation = () => { const isSwatTemplate = document.querySelector('.uxdia-c-swat-template__container'); const expandedVariation = document.querySelector('#uxdia-c-swat-expanded-variation'); const closedvariation = document.querySelector('#uxdia-c-swat-close-variation'); if (isSwatTemplate && expandedVariation && closedvariation) { const swatParent = isSwatTemplate.parentElement?.closest('.container') if (swatParent) { swatParent.style.marginLeft = 'auto'; } if (window.top.location.href.indexOf('/editor.html/') === -1) { const device = window.matchMedia('(max-width: 767px)'); if (device.matches) { // always display closed variation in mobile expandedVariation.style.display = 'none'; closedvariation.style.display = 'block'; } else { const isExpandedVariationClosed = localStorage.getItem('isExpandedVariationClosed'); if (isExpandedVariationClosed) { expandedVariation.style.display = 'none'; closedvariation.style.display = 'block'; } else { expandedVariation.style.display = 'block'; closedvariation.style.display = 'none'; } } } else { closedvariation.style.display = 'block'; expandedVariation.style.display = 'block'; } const expandedcloseIcon = document.querySelector('#uxdia-c-swat-expanded-variation .uxdia-c-hide-icon-text'); expandedcloseIcon?.addEventListener('click', () => { expandedVariation.style.display = 'none'; closedvariation.style.display = 'block'; localStorage.setItem('isExpandedVariationClosed', true); }); const closeVariationIcon = document.querySelector('#uxdia-c-swat-close-variation .uxdia-c-hide-icon-text'); closeVariationIcon?.addEventListener('click', () => { closedvariation.style.display = 'none'; }); } } // Initializing without listening for 'at-content-rendering-succeeded' in case target content already rendered // And also when target is not loaded initializeVariation(); // Event listener for capturing Adobe Target Content Render Success document.addEventListener('at-content-rendering-succeeded', () => { initializeVariation(); }); }); var redirectSearchURL=function(b,a){b&&a&&(b=encodeURIComponent(b),a=AARP.Everywhere.endecaSearchUrl+"?q\x3d"+b+"\x26c\x3d"+a+"\x26"+AARP.Everywhere.endecaSearchUrlInternalTracking,window.dispatchEvent(new CustomEvent("SEND_ANALYTICS_ON_NEW_SEARCH_SUBMIT")),window.location=a)}; function addSearchListeners(){var b=document.querySelector(".search-modal-header__container .search__button"),a=document.querySelector(".search-modal__inputbox");a&&a.addEventListener("keyup",function(c){13!=c.which&&13!=c.keyCode||d()});var d=function(){if(a&&a.value){var c=document.querySelector(".combo-option.option-current");redirectSearchURL(a.value,c.getAttribute("value"))}};b&&b.removeEventListener("click",d);b&&b.addEventListener("click",d)}addSearchListeners(); var setSearchListeners=function(){var b,a,d,c;null===(b=window)||void 0===b?void 0:null===(a=b.ContextHub)||void 0===a?void 0:null===(d=a.Utils)||void 0===d?void 0:null===(c=d.Eventing())||void 0===c?void 0:c.on(window.ContextHub.Constants.EVENT_TEASER_LOADED,function(){addSearchListeners()})};AARP.Externals.ContextHub.onLoad(setSearchListeners);AARP=AARP||{};AARP.Everywhere=AARP.Everywhere||{};AARP.Everywhere.getEnvironment=function(){var t=!0,n=window.location.hostname.split(""),l;for(l in n){if("-"===n[l])var u=l;if("."===n[l]&&t){t=!1;var v=l}}return u?n.slice(u,v).join(""):""}; AARP.Everywhere.Page=new function(){function t(){var a=N.parseURL(document.location.toString());n=a.url;l=a.protocol;u=a.host;v=a.subdomain;A=a.port;B=a.anchor;C=a.file;D=a.dirIndex;E=a.path;F=a.pathc;G=a.parameters;H=a.querystring;I=a.path_effective;x=a.pathc_effective;J=a.isInternal;AARP.Everywhere.isAuthor||"undefined"==typeof $aarpe||$aarpe.ajaxSetup({xhrFields:{withCredentials:!!$aarpe.cookie("at")}})}var n,l,u,v,A,B,C,D,E,F,G,H,I,x,J,N=this,y=[];this.getUrl=function(){return n};this.getProtocol= function(){return l};this.getHost=function(){return u};this.getSubdomain=function(){return v};this.getPort=function(){return A};this.getAnchor=function(){return B};this.getFile=function(){return C};this.getDirIndex=function(){return D};this.getPath=function(){return E};this.getPathc=function(){return F};this.getQuerystring=function(){return H};this.getParameters=function(){return G};this.getPath_effective=function(){return I};this.getPathc_effective=function(){return x};this.getIsInternal=function(){return J}; this.getSite=function(){};this.getSiteZone=function(a){if(a)var c=a.pathc_effective;else{if(0{function f(){window.getGUID()&&cdApi.changeContext(window.biocatchActivityType)}function g(e){var t=document.createElement("meta");t.name="bcsid",t.content=e||window.getGUID(),document.head.append(t),AARP.Externals.attachAsyncDependency({"id":"bioCatchScript","url":i,"success":f})}var e,t,n,i=""==AARP.Everywhere.getEnvironment()?"https://bcdn-god.we-stats.com/scripts/26d6cd71/26d6cd71.js":"https://bcdn-god.we-stats.com/scripts/181e494/97e45b82.js";window.GUIDContext="Earn-",window.getGUID=function(){return window.GUIDContext+window.GUID},window.GUID=(e=new Date,t=sessionStorage.getItem("guid-time"),n=sessionStorage.getItem("guid"),t&&n&&(e-new Date(t))/6e4<60||(n=((t=function(){return(65536*(1+Math.random())|0).toString(36).substring(1)})()+t()+t()+t().substr(0,3)+t()+t()+t()).toLowerCase(),sessionStorage.setItem("guid",n),sessionStorage.setItem("guid-time",e)),n),window.addEventListener("loyalty-get-activity-response",function(e){var t;"d57cdff9-014c-455a-9485-832e3377a0c3"!==(null==e||null==(t=e.detail)?void 0:t.identifier)&&(window.biocatchActivityType="rewards-earn-activity-".concat(null==e||null==(t=e.detail)||null==(e=t.activityType)?void 0:e.identifier),g())}),window.addEventListener("redeem-page-events",function(e){e=null==e?void 0:e.detail;e&&(e=e.replace(/[^a-zA-Z0-9] -_/g,"").replace(/ /g,"_"),window.biocatchActivityType="".concat(e)),g(window.getGUID())})})();function _classCallCheck(l,n){if(!(l instanceof n))throw new TypeError("Cannot call a class as a function");}function _defineProperty(l,n,p){n in l?Object.defineProperty(l,n,{value:p,enumerable:!0,configurable:!0,writable:!0}):l[n]=p;return l} (function(){var l=new function p(){var b=this;_classCallCheck(this,p);_defineProperty(this,"emitAnalyticsRecorded",function(){});_defineProperty(this,"setMemberAnalytics",function(){b.setEnrollStatus();b.setVisitStatus();b.setOptInStatus();b.setEmailStatus();b.setTotalPoints();b.setRewardType()});_defineProperty(this,"setEnrollStatus",function(){var a;b.rewardsData.enrollstatus="Y"===(null===(a=AARP.store.getState().cookie.at)||void 0===a?void 0:a.rs)});_defineProperty(this,"setVisitStatus",function(){b.rewardsData.visitstatus= null});_defineProperty(this,"setOptInStatus",function(a){b.rewardsData.optinstatus=null});_defineProperty(this,"setEmailStatus",function(){var a,f,c=!1,e=null===(a=AARP.store.getState().cookie)||void 0===a?void 0:null===(f=a.at)||void 0===f?void 0:f.n;e&&(c=JSON.parse(e).includes(59102));b.rewardsData.emailstatus=c});_defineProperty(this,"setTotalPoints",function(){b.rewardsData.totalpoints=AARP.store.getState().cookie.aarp_rewards_balance});_defineProperty(this,"setTodaysPoints",function(a){b.rewardsData.todayspoints= a});_defineProperty(this,"setLastActivity",function(a){b.setActivityPoints(a.amount);b.setActivityType(a.activityType);b.setActivityID(a.id)});_defineProperty(this,"setActivityPoints",function(a){b.rewardsData.activitypoints=a});_defineProperty(this,"setActivityType",function(a){b.rewardsData.activitytype=a});_defineProperty(this,"setActivityID",function(a){b.rewardsData.activityid=a});_defineProperty(this,"setRedeemStatus",function(a){b.rewardsData.redeemstatus=a});_defineProperty(this,"setRewardType", function(){b.userData.rewardtype=status});_defineProperty(this,"checkMismatchWithLMP",function(){var a,f,c,e,h,k=0k.xhrStatusCode||400<=k.xhrStatusCode))m="LMP-mismatch-error:".concat(k.xhrStatusCode,". AARP-").concat(a,", ").concat(m,", ").concat(c),b.errors.errormessage=m,window.dispatchEvent(new CustomEvent("ana_event_error"));else if(e=k.userIdentifier,h={ACTIVE:"0",NON_MEMBER:"1",CANCEL:"4",EXPIRE:"5",MEMBER_REQUEST_SUSPEND:"M",UNDELIVERABLE_SUSPEND:"U",DECEASED_SUSPEND:"D"}[k.membershipStatus||"NON_MEMBER"],k=k.membershipExpiration||"null",g=Math.ceil(Math.abs(new Date(c)-new Date(k))/ 864E5),m!=h||1t?Promise.resolve({success:!1}):Promise.resolve({success:!0})}catch(v){return console.error(v,"check token fail"),Promise.resolve({success:!1})}});_defineProperty(this,"_toJSONString",function(e){return JSON.stringify(e)}); this.access_token=AARP.store.getState().auth.authToken;this.isRewardsUser=AARP.store.getState().user.rewardsUser;AARP.store.subscribe(function(){a.access_token=AARP.store.getState().auth.authToken});var c=document.querySelector(".aarp-u-loyalty-plus-switch");this.eodTS=(new Date).setHours(24,0,0,0);this.dailyErrorTS=JSON.parse(localStorage.getItem("dailyErrorTS"));this.time_travel=AARP.store.getState().cookie.TimeTravelCookie;this.loyalty_backend=AARP.store.getState().cookie.LoyaltyBackend;this.isLoyaltyPlus= "true"===(null===c||void 0===c?void 0:null===(b=c.dataset)||void 0===b?void 0:b.isLoyaltyPlus);this.future_space_testing=AARP.store.getState().cookie["x-aarp-system-future"];this.userID=AARP.store.getState().cookie.fedid;AARP.store.subscribe(function(){a.userID=AARP.store.getState().cookie.fedid});b=document.querySelector(".enable-internal-api");this.tla=window.AARP.TranslationLayerAnalytics;this.baseUrl=AARP.store.getState().currentEnvironment.servicesEndpoint;this.loginUrlHost=AARP.store.getState().currentEnvironment.secureEndpoint; this.clientId=AARP.store.getState().currentEnvironment.isLive?"0oa3rtsa6ahTQReOG2p7":"0oakgt9j4hwrtHWUl0h7";this.loyaltyCatalogPath="".concat(this.baseUrl,"applications/loyalty-catalog/");this.checkRedeemUrl="".concat(this.loyaltyCatalogPath,"aarp/redemption/check/").concat(this.userID);this.getActivityListUrl=b?"/bin/staying-sharp/earnlist.json":"".concat(this.loyaltyCatalogPath,"activity/listV3");this.activityUrl="".concat(this.loyaltyCatalogPath,"activity/");this.getActivityLimitsUrl="".concat(this.loyaltyCatalogPath, "activity/limit");this.getMemberResourceUrl="".concat(this.loyaltyCatalogPath,"member/");this.getTransactionHistoryUrl="".concat(this.loyaltyCatalogPath,"transaction");this.getPointsExpirationUrl="".concat(this.loyaltyCatalogPath,"aarp/expiration/user/");this.submitSecretWordUrl="".concat(this.loyaltyCatalogPath,"secretword");this.getEntertainmentOffersUrl="".concat(this.loyaltyCatalogPath,"offers");this.redeemOfferUrl="".concat(this.loyaltyCatalogPath,"eredeem/");this.goodsUrl="".concat(this.loyaltyCatalogPath, "goods");this.redeemItemUrl="".concat(this.loyaltyCatalogPath,"aarp/redemption/").concat(this.userID);this.getUserUrl="".concat(this.baseUrl,"applications/CoreApi/user");this.getAddressFromItcUrl="".concat(this.baseUrl,"applications/rewards-egreeting/user/address");this.updateUserUrl="".concat(this.baseUrl,"applications/CoreApi/user/updateLoyaltyProfile/");this.offerFiltersUrl="".concat(this.loyaltyCatalogPath,"categories");this.getActivityBundleUrl="".concat(this.baseUrl,"applications/loyalty-catalog/activity/bundle"); this.getUserLessonCompletionUrl="".concat(this.loyaltyCatalogPath,"aarp/lessons/status");this.getUserSingleLessonCompletionUrl="".concat(this.loyaltyCatalogPath,"aarp/status/{USERID}?lessonIdentifier\x3dlessonid");this.getSingleLessonsUrl="".concat(this.loyaltyCatalogPath,"aarp/lessons/{lessonID}");this.getAllLessonsUrl="".concat(this.loyaltyCatalogPath,"aarp/lessons");this.loginUrl="".concat(this.loginUrlHost,"applications/user/login?response_type\x3dcode\x26client_id\x3d").concat(this.clientId, "\x26redirect_uri\x3d").concat(window.location.origin,"/aarp/auth/callback\x26scope\x3dbui+bmi\x26state\x3d").concat(window.location.href);this.createFitnessGoalUrl="".concat(this.loyaltyCatalogPath,"user/createFitnessGoal/").concat(this.userID);this.storeFitnessGoalUrl="".concat(this.loyaltyCatalogPath,"user/storeFitnessGoal/").concat(this.userID);this.dailyOverviewUrl="".concat(this.loyaltyCatalogPath,"user/dailyOverview/").concat(this.userID);this.weeklyOverviewUrl="".concat(this.loyaltyCatalogPath, "user/weeklyOverview/").concat(this.userID);this.totalSweepsEntriesUrl="".concat(this.loyaltyCatalogPath,"aarp/redemption/").concat(this.userID,"/totalEntries/");this.offerAvailabilityUrl="".concat(this.redeemOfferUrl,"{offerId}?userIdentifier\x3d").concat(this.userID);this.goodsInventoryAndDateUrl="".concat(this.loyaltyCatalogPath,"goods/goodsinventoryndate");this.getUserActivityGoalUrl="".concat(this.loyaltyCatalogPath,"user/getUserActivityGoal/").concat(this.userID);this.getUserDashboardInformationUrl= "".concat(this.loyaltyCatalogPath,"/dashboard/member/").concat(this.userID,"/information");this.createUserActivityGoalUrl="".concat(this.loyaltyCatalogPath,"user/createUserActivityGoal/").concat(this.userID);this.setUserActivityGoalUrl="".concat(this.loyaltyCatalogPath,"user/storeUserActivityGoal/").concat(this.userID,"?");this.getFitnessInformationUrl="".concat(this.loyaltyCatalogPath,"user/").concat(this.userID,"/getInformation");this.getRedeemedAndSavedOfferUrl="".concat(this.redeemOfferUrl,"redeemedandsavedoffers?userIdentifier\x3d").concat(this.userID); this.getDeleteSavedOfferUrl="".concat(this.loyaltyCatalogPath,"eredeem/deletesavedoffer/");this.reportLocalOffersIssueUrl="/bin/servlet/local-offers-support";this.getRewardsStatusUrl="".concat(this.getUserUrl,"/rewards/status");this.doXHR=this.doXHR.bind(this);this.fetchMembershipData=this.fetchMembershipData.bind(this);this.getActivities=this.getActivities.bind(this);this.addLimitsToActivities=this.addLimitsToActivities.bind(this);this.fetchTransactionHistory=this.fetchTransactionHistory.bind(this); this.fetchPointsExpiring=this.fetchPointsExpiring.bind(this);this.submitSecretWord=this.submitSecretWord.bind(this);this.getEntertainmentOffers=this.getEntertainmentOffers.bind(this);this.reportLocalOffersIssue=this.reportLocalOffersIssue.bind(this);this.getUserLessonCompletion=this.getUserLessonCompletion.bind(this);this.createFitnessGoal=this.createFitnessGoal.bind(this);this.storeFitnessGoal=this.storeFitnessGoal.bind(this);this.getDailyOverview=this.getDailyOverview.bind(this);this.getWeeklyOverview= this.getWeeklyOverview.bind(this);this.submitActivity=this.submitActivity.bind(this);this.getRewardsStatus=this.getRewardsStatus.bind(this);this.getCall=this.getCall.bind(this);this.saveLocalOffer=this.saveLocalOffer.bind(this);this.unsaveLocalOffer=this.unsaveLocalOffer.bind(this);this.checkRedeemForAll=this.checkRedeemForAll.bind(this);this.checkRedeemMulti=this.checkRedeemMulti.bind(this);this.userID&&"undefined"!==this.userID?this.setCurrentBalanceURL():console.warn("userID not found or undefined, no pointsbalance"); this.lessonData="";this.currentUserPointBalance=AARP.store.getState().cookie.aarp_rewards_balance||null}_createClass(r,[{key:"xhrWrapper",value:function(a){var b=this,c=a.url,e=a.data,d=a.params,f=a.getAddress,h=void 0===f?!1:f;f=a.enableBiocatch;var q=void 0===f?!1:f;f=a.redirectUrl;var t=void 0===f?"":f;f=a.method;var v=void 0===f?"GET":f;a=a.stringResponse;var C=void 0===a?!1:a;g[c]&&0c.indexOf("limit"))return console.warn("too many similar TL requests", g),g[c];a=(new Promise(function(u,D){if(d&&"object"===_typeof(d)){var w="?";Object.keys(d).forEach(function(n){w="".concat(w).concat(n,"\x3d").concat(d[n],"\x26")});c+=w}else d&&console.warn("doXHR params need to be an object.");var m=new XMLHttpRequest,x="GET";e&&(x="POST");"POST"==v&&(x="POST");m.open(x,c,!0);e&&m.setRequestHeader("Content-Type","application/json;charset\x3dUTF-8");b.access_token&&m.setRequestHeader("Authorization","Bearer ".concat(b.access_token));h&&(t=b.loginUrl,m.withCredentials= !0,m.setRequestHeader("ascp","ba aa"));if(q){var y,z,A;m.setRequestHeader("cd","{ customerSessionID: ".concat(window.getGUID(),", emailAddress: ").concat(null===(y=AARP)||void 0===y?void 0:null===(z=y.cookies)||void 0===z?void 0:null===(A=z.at)||void 0===A?void 0:A.e," }"))}b.time_travel&&(b.time_travel=(new Date(b.time_travel)).toISOString(),m.setRequestHeader("X-Time-Travel",b.time_travel));(b.loyalty_backend||b.isLoyaltyPlus)&&m.setRequestHeader("X-Loyalty-Backend","LoyaltyPlus");b.future_space_testing&& (m.withCredentials=!0);m.onload=function(){if(200<=this.status&&400>this.status){var n=this.response;""===this.response&&(n=null);n=C?n:JSON.parse(n);delete g[c];0c.xhrStatusCode||400<=c.xhrStatusCode||"XHR failed"===c.message)document.dispatchEvent(new CustomEvent("LESSON_DATA_ERROR",{detail:c}));else return document.dispatchEvent(new CustomEvent("LESSON_DATA_SENT",{bubbles:!0,detail:a.lessonData})),a.lessonData})["catch"](function(c){console.error("An error has occurred getting the lesson completion: ",c);document.dispatchEvent(new CustomEvent("LESSON_DATA_ERROR",{detail:c}))});document.dispatchEvent(new CustomEvent("LESSON_DATA_SENT",{bubbles:!0, detail:this.lessonData}));return this.lessonData}},{key:"getOfferAvailablity",value:function(a){var b=this.offerAvailabilityUrl.replace("{offerId}",a);return this.doXHR({url:b}).then(function(c){return c})["catch"](function(c){return console.error("An error has occurred getting the availability of offer: ".concat(a),c)})}},{key:"getAllLessons",value:function(){return this.doXHR({url:this.getAllLessonsUrl}).then(function(a){return a})["catch"](function(a){return console.error("An error has occurred getting the lessons: ", a)})}},{key:"addLimitsToActivities",value:function(a){var b=this,c=this.userID,e={activityList:[]};a.forEach(function(d){(d.identifier||d.id||d.activityIdentifier)&&e.activityList.push({activityIdentifier:d.identifier||d.id||d.activityIdentifier})});return 0===e.activityList.length?new Promise(function(d){d({})}):this.doXHR({url:this.getActivityLimitsUrl+"/"+c,data:e}).then(function(d){b.tla.setTodaysPoints(d.userDailyPointsLeft);b.tla.emitAnalyticsRecorded();localStorage.setItem("user_daily_points_left", d.userDailyPointsLeft);500>d.userDailyPointsLeft&&window.dispatchEvent(new CustomEvent("max-points-pushdown-listener"));a.forEach(function(f){var h=d.activityList.filter(function(q){return q.activityIdentifier===(f.identifier||f.id||f.activityIdentifier)})[0];h?(f.limitHit=h.limitHit,f.limitPeriod=h.limitPeriod):(f.limitHit=!1,f.limitPeriod="")});return a})["catch"](function(d){return console.error("An error has occurred getting the activity limits: ",d)})}},{key:"getCurrentBalance",value:function(){var a= this,b=0 r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) { n[e] = r[e]; } return n; } (function () { var featuredTiles = document.querySelectorAll('.uxdia-c-featured-tile-wrapper'); var isMember = AARP.store.getState().user.member; var isRewardsUser = AARP.store.getState().user.rewardsUser; var rewardsLimitsSet = false; featuredTiles.forEach(function (featuredTile) { var tileDataset = featuredTile.dataset; var rewardsActivityId = tileDataset.rewardsActivityId; if (rewardsActivityId && isRewardsUser) { var activityBadge = featuredTile.querySelector('.uxdia-c-featured-tile__activity-badge'); var activityLoaded = tileDataset.activityLoaded; if (activityLoaded === 'true') { return; } var activityPoints = featuredTile.querySelector('.uxdia-c-featured-tile__points-amount'); var activityPointsAbbr = featuredTile.querySelector('.uxdia-c-featured-tile__points-abbr'); AARP.translationLayerService.getActivityWithId(rewardsActivityId).then(function (activityInfo) { var activityType = activityInfo.activityType; var activityTypeId = activityType.identifier; var isDoublePoints = activityTypeId && activityTypeId.indexOf('double') === 0; var pointsValue = isMember ? activityType.basePointValue + activityType.memberPointBonus : activityType.basePointValue; activityPoints.innerText = pointsValue.toLocaleString(); if (isDoublePoints) { activityPointsAbbr.innerText = '2X PTS'; activityPointsAbbr.setAttribute('title', 'Double points'); } featuredTile.dataset.activityLoaded = 'true'; if (rewardsLimitsSet) { activityBadge.classList.remove('uxdia-c-featured-tile__activity--plain-star'); } }); } }); if (rewardsLimitsSet === true) { return; } var allActivityIds = _toConsumableArray(featuredTiles).map(function (tile) { return { identifier: tile.dataset.rewardsActivityId }; }); allActivityIds = allActivityIds.filter(function (activityId) { return activityId.identifier; }); if (allActivityIds.length > 0 && isRewardsUser) { AARP.translationLayerService.addLimitsToActivities(allActivityIds).then(function (activityList) { activityList.length >= 0 && featuredTiles.forEach(function (featuredTile) { var tileDataset = featuredTile.dataset; rewardsActivityId = tileDataset.rewardsActivityId; if (rewardsActivityId) { var activityBadge = featuredTile.querySelector('.uxdia-c-featured-tile__activity-badge'); var activityLimits = activityList.find(function (limit) { var activityIdentifier = limit.identifier || limit.id || limit.activityIdentifier; return activityIdentifier === rewardsActivityId; }); if (activityLimits !== null && activityLimits !== void 0 && activityLimits.limitHit) { activityBadge.innerHTML = ''; activityBadge.classList.add('uxdia-c-featured-tile__completed-badge'); } if (featuredTile.dataset.activityLoaded === 'true') { activityBadge.classList.remove('uxdia-c-featured-tile__activity--plain-star'); } } }); rewardsLimitsSet = true; }); } })(); (function(){window.CQ=window.CQ||{};window.CQ.CoreComponents=window.CQ.CoreComponents||{};window.CQ.CoreComponents.container=window.CQ.CoreComponents.container||{};window.CQ.CoreComponents.container.utils={};window.CQ.CoreComponents.container.utils={removeUrlHash:function(){history.replaceState(void 0,void 0," ")},updateUrlHash:function(a,b,c){a&&a._elements&&a._elements[b]&&a._elements[b][c]&&a._elements[b][c].id&&history.replaceState(void 0,void 0,"#"+a._elements[b][c].id)},getDeepLinkItemIdx:function(a, b,c){if(window.location.hash){var d=window.location.hash.substring(1);if(d&&document.getElementById(d)&&a&&a._config&&a._config.element&&a._elements[b]&&a._config.element.querySelector("[id\x3d'"+d+"']"))for(var e=0;e -1) { var deepLinkItem = that._elements["tab"][deepLinkItemIdx]; if (deepLinkItem && that._elements["tab"][that._active].id !== deepLinkItem.id) { navigateAndFocusTab(deepLinkItemIdx, true); } var hashId = window.location.hash.substring(1); if (hashId) { var hashItem = document.querySelector("[id='" + hashId + "']"); if (hashItem) { hashItem.scrollIntoView(); } } } } } /** * Returns the index of the active tab, if no tab is active returns 0 * * @param {Array} tabs Tab elements * @returns {Number} Index of the active tab, 0 if none is active */ function getActiveIndex(tabs) { if (tabs) { for (var i = 0; i < tabs.length; i++) { if (tabs[i].classList.contains(selectors.active.tab)) { return i; } } } return 0; } /** * Caches the Tabs elements as defined via the {@code data-tabs-hook="ELEMENT_NAME"} markup API * * @private * @param {HTMLElement} wrapper The Tabs wrapper element */ function cacheElements(wrapper) { that._elements = {}; that._elements.self = wrapper; var hooks = that._elements.self.querySelectorAll("[data-" + NS + "-hook-" + IS + "]"); for (var i = 0; i < hooks.length; i++) { var hook = hooks[i]; if (hook.closest("." + NS + "-" + IS) === that._elements.self) { // only process own tab elements var capitalized = IS; capitalized = capitalized.charAt(0).toUpperCase() + capitalized.slice(1); var key = hook.dataset[NS + "Hook" + capitalized]; if (that._elements[key]) { if (!Array.isArray(that._elements[key])) { var tmp = that._elements[key]; that._elements[key] = [tmp]; } that._elements[key].push(hook); } else { that._elements[key] = hook; } } } } /** * Binds Tabs event handling * * @private */ function bindEvents() { window.addEventListener("hashchange", scrollToDeepLinkIdInTabs, false); var tabs = that._elements["tab"]; if (tabs) { for (var i = 0; i < tabs.length; i++) { (function(index) { tabs[i].addEventListener("click", function(event) { navigateAndFocusTab(index); }); tabs[i].addEventListener("keydown", function(event) { onKeyDown(event); }); })(i); } } } /** * Handles tab keydown events * * @private * @param {Object} event The keydown event */ function onKeyDown(event) { var index = that._active; var lastIndex = that._elements["tab"].length - 1; switch (event.keyCode) { case keyCodes.ARROW_LEFT: case keyCodes.ARROW_UP: event.preventDefault(); if (index > 0) { navigateAndFocusTab(index - 1); } break; case keyCodes.ARROW_RIGHT: case keyCodes.ARROW_DOWN: event.preventDefault(); if (index < lastIndex) { navigateAndFocusTab(index + 1); } break; case keyCodes.HOME: event.preventDefault(); navigateAndFocusTab(0); break; case keyCodes.END: event.preventDefault(); navigateAndFocusTab(lastIndex); break; default: return; } } /** * Refreshes the tab markup based on the current {@code Tabs#_active} index * * @private */ function refreshActive() { var tabpanels = that._elements["tabpanel"]; var tabs = that._elements["tab"]; if (tabpanels) { if (Array.isArray(tabpanels)) { let currentlyActive = false; const closestWeTabs = tabpanels[0]?.closest(".we-tabs"); for (var i = 0; i < tabpanels.length; i++) { if (i === parseInt(that._active)) { const activePanel = tabpanels[i]; activePanel.classList.add(selectors.active.tabpanel); activePanel.removeAttribute("aria-hidden"); tabs[i].classList.add(selectors.active.tab); if (!document.querySelector('#aarp-c-header--uxdia-ctg-subheader')) tabs[i].setAttribute("aria-selected", true); // Display dark overlay below for megamenu if (closestWeTabs && !mainExists && !closestWeTabs.classList.contains('uxdia-c-megamenu-sub-tabs') && !activePanel.classList.contains('right_container')) { const rect = closestWeTabs.getBoundingClientRect(); const bottomPosition = rect.bottom; currentlyActive = true; document.documentElement.style.setProperty("--megamenu-panel-bottom", `${bottomPosition}px`); } } else { tabpanels[i].classList.remove(selectors.active.tabpanel); tabpanels[i].setAttribute("aria-hidden", true); tabpanels[i]?.classList?.contains('right_container') && tabpanels[i]?.setAttribute("aria-hidden", false); tabs[i].classList.remove(selectors.active.tab); if (!document.querySelector('#aarp-c-header--uxdia-ctg-subheader')) tabs[i].setAttribute("aria-selected", false); } if (currentlyActive && !mainExists) { closestWeTabs && closestWeTabs.classList.add('megamenu-dark-overlay'); } else { closestWeTabs && closestWeTabs.classList.remove('megamenu-dark-overlay'); } } } else { // only one tab tabpanels.classList.add(selectors.active.tabpanel); tabs.classList.add(selectors.active.tab); } } } /** * Focuses the element and prevents scrolling the element into view * * @param {HTMLElement} element Element to focus */ function focusWithoutScroll(element) { var x = window.scrollX || window.pageXOffset; var y = window.scrollY || window.pageYOffset; element.focus(); window.scrollTo(x, y); } /** * Navigates to the tab at the provided index * * @private * @param {Number} index The index of the tab to navigate to */ function navigate(index) { that._active = index; refreshActive(); } /** * Navigates to the item at the provided index and ensures the active tab gains focus * * @private * @param {Number} index The index of the item to navigate to * @param {Boolean} keepHash true to keep the hash in the URL, false to update it */ function navigateAndFocusTab(index, keepHash) { var exActive = that._active; var isUxdia = true; if (!keepHash && containerUtils && !isUxdia) { containerUtils.updateUrlHash(that, "tab", index); } navigate(index); focusWithoutScroll(that._elements["tab"][index]); if (dataLayerEnabled) { var activeItem = getDataLayerId(that._elements.tabpanel[index]); var exActiveItem = getDataLayerId(that._elements.tabpanel[exActive]); dataLayer.push({ event: "cmp:show", eventInfo: { path: "component." + activeItem } }); dataLayer.push({ event: "cmp:hide", eventInfo: { path: "component." + exActiveItem } }); var tabsId = that._elements.self.id; var uploadPayload = { component: {} }; uploadPayload.component[tabsId] = { shownItems: [activeItem] }; var removePayload = { component: {} }; removePayload.component[tabsId] = { shownItems: undefined }; dataLayer.push(removePayload); dataLayer.push(uploadPayload); } } } /** * Reads options data from the Tabs wrapper element, defined via {@code data-cmp-*} data attributes * * @private * @param {HTMLElement} element The Tabs element to read options data from * @returns {Object} The options read from the component data attributes */ function readData(element) { var data = element.dataset; var options = []; var capitalized = IS; capitalized = capitalized.charAt(0).toUpperCase() + capitalized.slice(1); var reserved = ["is", "hook" + capitalized]; for (var key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { var value = data[key]; if (key.indexOf(NS) === 0) { key = key.slice(NS.length); key = key.charAt(0).toLowerCase() + key.substring(1); if (reserved.indexOf(key) === -1) { options[key] = value; } } } } return options; } /** * Parses the dataLayer string and returns the ID * * @private * @param {HTMLElement} item the accordion item * @returns {String} dataLayerId or undefined */ function getDataLayerId(item) { if (item) { if (item.dataset.cmpDataLayer) { return Object.keys(JSON.parse(item.dataset.cmpDataLayer))[0]; } else { return item.id; } } return null; } /** * Document ready handler and DOM mutation observers. Initializes Tabs components as necessary. * * @private */ function onDocumentReady() { dataLayerEnabled = document.body.hasAttribute("data-cmp-data-layer-enabled"); dataLayer = (dataLayerEnabled) ? window.adobeDataLayer = window.adobeDataLayer || [] : undefined; var elements = document.querySelectorAll(selectors.self); for (var i = 0; i < elements.length; i++) { new Tabs({ element: elements[i], options: readData(elements[i]) }); } var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver; var body = document.querySelector("body"); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { // needed for IE var nodesArray = [].slice.call(mutation.addedNodes); if (nodesArray.length > 0) { nodesArray.forEach(function(addedNode) { if (addedNode.querySelectorAll) { var elementsArray = [].slice.call(addedNode.querySelectorAll(selectors.self)); elementsArray.forEach(function(element) { new Tabs({ element: element, options: readData(element) }); }); } }); } }); }); observer.observe(body, { subtree: true, childList: true, characterData: true }); } AARP.readyStateLoader(onDocumentReady); if (containerUtils) { window.addEventListener("load", containerUtils.scrollToAnchor, false); } }()); AARP = AARP || {}; AARP.Uxdia = AARP.Uxdia || {}; AARP.Uxdia.megaMenuWrapper = (() => { const megamenuFunctionality = () => { const tabs = document.querySelectorAll('.uxdia-c-megamenu .cmp-tabs__tab'); const ctgHeader = document.querySelector('#aarp-c-header--uxdia-ctg-subheader'); const close = document.querySelectorAll('.uxdia-c-megamenu--close'); const back = document.querySelectorAll('.uxdia-c-megamenu-back--button'); const container = document.querySelector('.uxdia-c-megamenu'); const tabContents = document.querySelectorAll('.uxdia-c-megamenu .cmp-tabs__tabpanel'); const rightContainer = document.querySelector('.right_container '); const tabsMenu = document.querySelectorAll('.uxdia-c-megamenu--tabs'); const mediaQuery = window.matchMedia("(max-width: 1024px)"); const tabletMediaQuery = window.matchMedia("(min-width: 768px)"); const openMegamenu = '.aarp-c-header__menu-icon-link'; const closeMegamenu = document.querySelector('.uxdia-c-megamenu--close'); const moreTab = document.querySelector('.uxdia-c-megamenu .cmp-tabs__tabpanel--more'); const moreTabContent = document.querySelector('.uxdia-c-megamenu .cmp-tabs__tabpanel--more .cmp-tabs__tablist li'); const header = document.querySelector('header'); const addSticky = 'uxdia-c-megamenu--js-sticky'; const alertBar = document.querySelector('.aarp-c-alert-bar'); const tabletCloseIcon = '.js-aarp-c-header__close-icon--megamenu'; let main = document.querySelector('main, .search-container-wrapper'); if (!main) { main = document.querySelector('.aarpe-main-content-wrap'); } const bodyElement = document.querySelector('body'); let scrolledDepth = 0; const channelTabs = document.querySelectorAll('.uxdia-c-megamenu .uxdia-c-megamenu--tabs')[0]?.querySelectorAll('.cmp-tabs__tab'); const channelContents = document.querySelectorAll('.uxdia-c-megamenu .uxdia-c-megamenu-sub-tabs'); const currentUrl = !!window.location.pathname.match('/content/aarpe/') ? window.location.pathname : '/content/aarpe/' + Granite?.I18n?.getLocale() + '/home' + window.location.pathname; const darkOverlay = 'uxdia-c__mega-menu--darkOverlay'; const menuitems = document.querySelectorAll('.cmp-tabs__tab'); const firstMegaSubTab = document.querySelector('.uxdia-c-megamenu-sub-tabs .uxdia-c-megamenu--tabs .cmp-tabs__tablist .cmp-tabs__tab'); const firstMegaSubTabPanel = document.querySelector('.uxdia-c-megamenu .uxdia-c-megamenu-sub-tabs .cmp-tabs__tabpanel'); const mainIn = document.getElementsByTagName('main')[0]; if (ctgHeader) { document.querySelector('.cmp-tabs__tablist').removeAttribute('role'); document.querySelector('.cmp-tabs__tablist').removeAttribute('aria-multiselectable'); document.querySelectorAll('.cmp-tabs__tablist li').forEach((eachLi) => { eachLi.setAttribute('role', 'listitem'); }) } const showDarkOverlay = (currentActiveTabPannel) => { const closestWeTabs = currentActiveTabPannel && currentActiveTabPannel.closest(".we-tabs"); // Display dark overlay below for megamenu if (closestWeTabs && !main && !closestWeTabs.classList.contains('uxdia-c-megamenu-sub-tabs') && !currentActiveTabPannel.classList.contains('right_container')) { const rect = closestWeTabs.getBoundingClientRect(); const bottomPosition = rect.bottom; document.documentElement.style.setProperty("--megamenu-panel-bottom", `${bottomPosition}px`); closestWeTabs.classList.add('megamenu-dark-overlay'); } }; const hideDarkOverlay = (currentInactiveTabPannel) => { if (currentInactiveTabPannel && !main) { const closestWeTabs = currentInactiveTabPannel.closest(".we-tabs"); closestWeTabs && closestWeTabs.classList.remove('megamenu-dark-overlay'); } }; AARP?.Externals?.ContextHub.onLoad(() => { window?.ContextHub?.Utils?.Eventing()?.on(window.ContextHub.Constants.EVENT_STORE_READY + ':ss-usertypes-jsonp',() => { const ssUserTypesInContextHub = window?.ContextHub?.getStore('ss-usertypes-jsonp')?.getItem('/'); const sponseredUser = ssUserTypesInContextHub?.fullResponse?.user.access_and_features?.sponsor; const stayingSharpDomain = document.location.hostname.match('stayingsharp'); const rightContainer = document.querySelector('.right_container'); stayingSharpDomain ? rightContainer?.classList.add('staying-sharp-megamenu-right__container') : ''; if (sponseredUser) { switch (sponseredUser) { case 'UHCOP': const onePassLogo = rightContainer.querySelector('.svgTag.stayingsharp-sponsor__one-pass'); onePassLogo?.classList.add('display-logo'); break; case 'UHCMS15': const renewLogo = rightContainer.querySelector('.svgTag.stayingsharp-sponsor__ms'); renewLogo?.classList.add('display-logo'); break; case 'UHCMS35': case 'UHCMA': const msLogo = rightContainer.querySelector('.svgTag.stayingsharp-sponsor__renew-active'); msLogo?.classList.add('display-logo'); break; case 'PRUDENTIAL': const prudentialLogo = rightContainer.querySelector('.svgTag.stayingsharp-sponsor__prudential'); prudentialLogo?.classList.add('display-logo'); break; default: break; } } },'sponsored-user',true); }) // mouse over event handler function const closeMenuOnHoverOut = (event) => { if (!container?.contains(event.target) && !document.querySelector(tabletCloseIcon)?.contains(event.target)) { closeMenu(); }; scrolledDepth = window.pageYOffset; } function closeMenu() { let hamburgerIcon = document.querySelector(openMegamenu); let tabletCloseButton = document.querySelector(tabletCloseIcon); main?.classList.remove(darkOverlay); tabContents?.forEach(function (e) { e.classList.remove('cmp-tabs__tabpanel--active'); hideDarkOverlay(e); }); tabs?.forEach(function (e) { e.classList.remove('cmp-tabs__tab--active'); }); //make first tab and tabpanel of megamenu subtabs active as they are getting removed above (in L.No 36) if (!mediaQuery.matches) { firstMegaSubTab?.classList.add('cmp-tabs__tab--active'); firstMegaSubTabPanel?.classList.add('cmp-tabs__tabpanel--active'); showDarkOverlay(firstMegaSubTabPanel); } else if (tabletMediaQuery.matches) { dispatchEvent(new CustomEvent('activateShyHeader', { detail: 'megaMenuClosed' })); } activeChannel(); if (bodyElement?.dataset.megaMenuHover) { bodyElement.removeEventListener("mouseover", closeMenuOnHoverOut); bodyElement.dataset.megaMenuHover = false; } if (tabletCloseButton && hamburgerIcon) { tabletCloseButton.style.display = 'none'; hamburgerIcon.style.display = 'flex'; } } // closing megamenu on tabbed out mainIn?.addEventListener('keydown', function (event) { if (event.key === "Tab") { closeMenu(); } }); moreTab?.addEventListener("click", (event) => { moreTabContent?.click(); }); document.addEventListener("mousedown", (event) => { if (!container?.contains(event.target)) { closeMenu(); } }); close?.forEach(function (e) { e.addEventListener('click', function (ele) { ele.preventDefault(); closeMenu(); }); }); back?.forEach(function (e) { e.addEventListener('click', function (ele) { ele.preventDefault(); inactiveChannels(); tabContents?.forEach(function (e) { e.classList.remove('cmp-tabs__tabpanel--active'); hideDarkOverlay(e); }); tabsMenu?.forEach(function (e) { e.style.display = "block"; }); rightContainer ? rightContainer.style.display = "block" : ''; }); }); function inactiveChannels() { tabs?.forEach(function (ele) { ele.classList.remove('cmp-tabs__tab--active'); }); } closeMenu(); tabs?.forEach(function (e) { e.addEventListener('click', function (e) { if (e.target.tagName === 'LI') { tabsMenu?.forEach(function (e) { e.style.display = "none"; }); rightContainer ? rightContainer.style.display = "none" : ''; inactiveChannels(); e.target.classList.add('cmp-tabs__tab--active'); } }); const ssDomain = (window.location.hostname).includes('stayingsharp') || (window.location.href).includes('staying-sharp'); if (ssDomain) { const dataItem = e.getAttribute('data-cmp-url'); if (dataItem !== null) { var lastItem = dataItem.slice(0, -1).split('/') var activeItem = lastItem[lastItem.length - 1]; } var url = window.location.pathname.split('/'); var item = url.find(part => part === activeItem); if (activeItem === item) { e.classList.add('cmp-tabs-listitem--active'); } } }); var bypassCheck = false; function setMegaMenuHeight() { let coreHeader = document.querySelector(".coreHeader"), updatedMegamenu = document.querySelector(".uxdia-c-megamenu"); if (bypassCheck || (tabletMediaQuery?.matches && mediaQuery?.matches)) { updatedMegamenu ? updatedMegamenu.style.height = window.innerHeight - coreHeader?.offsetTop - coreHeader?.clientHeight + "px" : ''; bypassCheck = false; } else if (mediaQuery.matches) { updatedMegamenu ? updatedMegamenu.style.height = "-webkit-fill-available" : ''; } else { updatedMegamenu ? updatedMegamenu.style.height = "" : ''; } } window.onresize = setMegaMenuHeight; function openMenuInMobile() { let hamburgerIcon = document.querySelector(openMegamenu), tabletCloseButton = document.querySelector(tabletCloseIcon); if (tabletMediaQuery?.matches) { bypassCheck = true; setMegaMenuHeight(); } if (container?.classList?.contains('uxdia-c-megamenu--open') && bodyElement?.classList?.contains('aarp-c-offscreen-nav-uxdia__open')) { container?.classList?.remove('uxdia-c-megamenu--open'); header?.classList?.remove('uxdia-c-megamenu-header-open'); bodyElement.classList.remove('aarp-c-offscreen-nav-uxdia__open'); bodyElement.style.position = ''; } else { container?.classList.add('uxdia-c-megamenu--open'); bodyElement?.classList.add('aarp-c-offscreen-nav-uxdia__open'); header?.classList?.add('uxdia-c-megamenu-header-open'); if (tabletMediaQuery.matches) { bodyElement.style.position = 'fixed'; } tabsMenu?.forEach(function (e) { e.style.display = "block"; }); rightContainer ? rightContainer.style.display = "block" : ''; } if (tabletCloseButton && hamburgerIcon) { tabletCloseButton.style.display = 'flex'; hamburgerIcon.style.display = 'none'; } // Accessibility Fix const dropdownContainer = document.querySelector('.aarp-c-offscreen-nav-uxdia__open .cmp-tabs__tabpanel--shown .aarp-c-linked-dropdown__link-list'); if (dropdownContainer) { const headerSearchIcon = document.querySelector(`.${tabletMediaQuery?.matches ? 'aarp-c-offscreen-nav-uxdia__open' : 'uxdia-c-megamenu-offscreen--links'} .aarp-c-search__button--open`); const promoHeaderButton = document.querySelector('.promoHeader .uxdia-c-button--promo-header:last-child a'); const megamenuTabs = document.querySelectorAll('.aarp-c-offscreen-nav-uxdia__open .uxdia-c-megamenu--tabs'); ((promoHeaderButton && !tabletMediaQuery?.matches) ? promoHeaderButton : headerSearchIcon)?.addEventListener('blur', (e) => { dropdownContainer?.querySelector('.aarp-c-linked-dropdown__list-item:first-child .aarp-c-linked-dropdown__link-item')?.focus(); }); dropdownContainer?.querySelector('.aarp-c-linked-dropdown__list-item:last-child .aarp-c-linked-dropdown__link-item')?.addEventListener('blur', (e) => { megamenuTabs[0]?.querySelector('.uxdia-homepage-health')?.focus(); }); megamenuTabs[0]?.querySelector('.uxdia-homepage-travel')?.addEventListener('blur', (e) => { megamenuTabs[1]?.querySelector('.cmp-tabs__tab:first-child')?.focus(); }); } } document.querySelector(openMegamenu)?.addEventListener('click', openMenuInMobile); document.querySelector(tabletCloseIcon)?.addEventListener('click', closeMenu); document.addEventListener("mousedown", (event) => { if (!container?.contains(event.target)) { container?.classList.remove('uxdia-c-megamenu--open'); header?.classList.remove('uxdia-c-megamenu-header-open'); bodyElement?.classList.remove('aarp-c-offscreen-nav-uxdia__open'); bodyElement.style.position = ''; } }); closeMegamenu?.addEventListener('click', function () { container?.classList.remove('uxdia-c-megamenu--open'); header?.classList.remove('uxdia-c-megamenu-header-open'); bodyElement?.classList.remove('aarp-c-offscreen-nav-uxdia__open'); tabsMenu?.forEach(function (e) { e.style.display = "block"; }); }); const svgCloseIcon = closeMegamenu?.querySelector('svg'); if (svgCloseIcon) { svgCloseIcon.role = 'button'; svgCloseIcon.ariaLabel = 'Close menu'; svgCloseIcon.tabIndex = 0; } AARP?.Externals?.ContextHub.onLoad(() => { window?.ContextHub?.Utils?.Eventing()?.on("ch-segment-engine:teaser-loaded", (x, y) => { y?.keys?.all?.list?.forEach(item => { let megaMenuFragment = document.querySelector(`#${item}`), updatedHamburgerIcon = megaMenuFragment?.querySelector(openMegamenu), updatedTabletCloseElement = megaMenuFragment?.querySelector(tabletCloseIcon); if (updatedHamburgerIcon && updatedTabletCloseElement) { updatedHamburgerIcon.addEventListener('click', openMenuInMobile); updatedTabletCloseElement.addEventListener('click', closeMenu); } }); }, "mega-menu", true); }); // Move right_container above tabsMenu in mobile view and handle moreTab aria-hidden function rearrangeRightContainerForMobile() { const moreTabs = document.querySelectorAll('.uxdia-c-megamenu .cmp-tabs__tabpanel--more'); if (!rightContainer || !tabsMenu[0]) return; if (mediaQuery.matches) { // Mobile view // Only move if not already above if (rightContainer.previousElementSibling === tabsMenu[0]) { tabsMenu[0].parentNode.insertBefore(rightContainer, tabsMenu[0]); } // Set moreTab aria-hidden to false in mobile if (moreTabs[1] && moreTabs[1].getAttribute('aria-hidden') === 'true') { moreTabs[1].setAttribute('aria-hidden', 'false'); } } else { // Desktop view // Move rightContainer back after tabsMenu if needed if (tabsMenu[0].nextElementSibling !== rightContainer) { tabsMenu[0].parentNode.insertBefore(rightContainer, tabsMenu[0].nextElementSibling); } // Set moreTab aria-hidden to true in desktop if (moreTabs[1] && moreTabs[1].getAttribute('aria-hidden') === 'false') { moreTabs[1].setAttribute('aria-hidden', 'true'); } } } // Rearrange on resize/breakpoint change mediaQuery.addEventListener('change', rearrangeRightContainerForMobile); rearrangeRightContainerForMobile(); mediaQuery.onchange = function (event) { if (!event.matches) { tabsMenu?.forEach(function (e) { e.style.display = ""; }); rightContainer ? rightContainer.style.display = "" : ''; } } let currentActiveTabPannel = '', moreTabPanel = document.querySelector('.uxdia-c-megamenu-sub-tabs'), previouslyInsideMoreTab = false; // previouslyInsideMoreTab is a boolean variable which will tell whether the recent previous active tab was a more tab tabs?.forEach(function (e) { let enterTimeout; e.addEventListener('mouseleave', function () { if (document.querySelectorAll(".cmp-tabs__tabpanel--active")?.length <= 1) { clearTimeout(enterTimeout); } }) e.addEventListener("mouseenter", function () { let timeout = document.querySelectorAll(".cmp-tabs__tabpanel--active")?.length > 1 ? 100 : 500; enterTimeout = setTimeout(() => { let thisRef = this; if (!mediaQuery.matches) { desktopInteraction(thisRef); } }, timeout); }); // code to remove focus from focused menu item e.addEventListener("mouseout", function () { document.activeElement?.blur(); }); }); let currentStickiness = false; //desktop mega menu interaction const desktopInteraction = (thisRef) => { if (!document.querySelector('.cmp-tabs__tabpanel--more.cmp-tabs__tabpanel--active')?.contains(thisRef)) { if (previouslyInsideMoreTab) { document.querySelector('.cmp-tabs__tabpanel--more.cmp-tabs__tab--active')?.classList.remove('cmp-tabs__tab--active'); document.querySelector('.cmp-tabs__tabpanel--more.cmp-tabs__tabpanel--active')?.classList.remove('cmp-tabs__tabpanel--active'); hideDarkOverlay(document.querySelector('.cmp-tabs__tabpanel--more.cmp-tabs__tabpanel--active')); previouslyInsideMoreTab = false; } else { document.querySelectorAll('.cmp-tabs__tab--active').forEach((elem) => { let isMoreTabChannel = document.querySelector('.cmp-tabs__tabpanel.cmp-tabs__tabpanel--more')?.contains(elem); isMoreTabChannel ? '' : elem.classList.remove('cmp-tabs__tab--active'); }); currentActiveTabPannel?.classList?.remove('cmp-tabs__tabpanel--active'); hideDarkOverlay(currentActiveTabPannel); } } else { moreTabPanel?.querySelectorAll('.cmp-tabs__tab--active').forEach((elem) => { elem.classList.remove('cmp-tabs__tab--active'); }); moreTabPanel?.querySelectorAll('.cmp-tabs__tabpanel--active').forEach((elem) => { elem.classList.remove('cmp-tabs__tabpanel--active'); hideDarkOverlay(elem); }); previouslyInsideMoreTab = true; } currentActiveTabPannel = commonHoverInteraction(thisRef, currentActiveTabPannel); if (bodyElement) { bodyElement.dataset.megaMenuHover = true; bodyElement.addEventListener("mouseover", closeMenuOnHoverOut); } }; // When we hover mouse over any mega menu item then the below lines of code is common irrespective of whether the channel is inside More tab or outside, hence the name. const commonHoverInteraction = (thisRef, currentActiveTabPannel) => { let tabControlId = thisRef.getAttribute('aria-controls'); currentActiveTabPannel = document.querySelector('div#' + tabControlId); if (thisRef.classList.contains('cmp-tabs__tab--active')) { currentActiveTabPannel?.classList.add('cmp-tabs__tabpanel--active'); currentActiveTabPannel?.removeAttribute("aria-hidden"); } else { thisRef.classList.add('cmp-tabs__tab--active'); currentActiveTabPannel?.classList.add('cmp-tabs__tabpanel--active'); currentActiveTabPannel?.removeAttribute("aria-hidden"); } showDarkOverlay(currentActiveTabPannel); main?.classList.add(darkOverlay); return currentActiveTabPannel; } // scroll handling function const megaMenuScrolled = () => { let scrollDifference = Math.abs(window.pageYOffset - scrolledDepth); let windowHeight = window.screen.availHeight; let activeTabBottom = document.getElementsByClassName("cmp-tabs__tabpanel--active")?.length > 0 ? document.getElementsByClassName("cmp-tabs__tabpanel--active")[0].getBoundingClientRect().bottom : 0; if (activeTabBottom && windowHeight && activeTabBottom < windowHeight - 140 && scrollDifference > 100 && (main ? main.classList.contains(darkOverlay) : true)) { closeMenu(); scrolledDepth = window.pageYOffset; } else if (activeTabBottom && windowHeight && activeTabBottom < windowHeight && scrollDifference > 150 && (main ? main.classList.contains(darkOverlay) : true)) { closeMenu(); scrolledDepth = window.pageYOffset; } } // capturing scroll event window.onscroll = megaMenuScrolled; // Adding Sticky Feature to marquee const syncWithCoreHeader = (stickyOverride, container = document) => { const coreHeaderSticky = document.querySelector('.coreHeader')?.classList?.contains('coreHeader--js-sticky'); const megaCoreHeader = document.querySelector('.coreHeader .aarp-c-header')?.clientHeight; const galleryNotActive = !document.querySelector('.gallery.gallery__container'); const stickyClassObject = document.querySelector('.uxdia-u-bg-ads--utility-medium-grey, #container-81ea044270'); const stickyClass = (window.scrollY < 1 && stickyClassObject) ? stickyClassObject : stickyClassObject?.classList.contains('uxdia-leaderboard-js--sticky'); const adHeight = stickyClass && stickyClassObject?.clientHeight || 0; container?.querySelectorAll('.uxdia-c-megamenu')?.forEach(instance => { if (stickyOverride || AARP?.header?.sticky && coreHeaderSticky) { if (!instance?.classList.contains(addSticky)) { instance.classList.add(addSticky); } } else { if (instance?.classList.contains(addSticky)) { instance.classList.remove(addSticky); } } if (!mediaQuery.matches) { galleryNotActive && instance?.style && (instance.style.top = (megaCoreHeader ? megaCoreHeader : 0) + adHeight + 'px'); } else if (instance) { instance.style.top = ''; } }); }; AARP?.Externals?.ContextHub?.attachContexthubCallback({ callback: (added, removed, details) => { details?.keys?.set?.list?.forEach(item => { const container = document.getElementById(item); syncWithCoreHeader(currentStickiness, container); }); } }); window.addEventListener('CORE_HEADER.STICKY_UPDATE', ({ detail: { sticky } }) => { currentStickiness = sticky; syncWithCoreHeader(sticky); }); function activeChannel() { const isValidURL = (url = '') => { try { return !!new URL(url); } catch (err) { return false; } } const isMatch = (tabLink = '') => { try { const params = new URLSearchParams(tabLink?.replaceAll('&', '&')?.split('?')[1]); return !!currentUrl?.match(new URL(params.get('state'))?.pathname); } catch (err) { return false; } } let longestMatchLength = 0; let activeTab = null; // hightlight channel channelTabs?.forEach((tab) => { const tabLink = tab?.getAttribute('data-cmp-url') || ''; if ( tabLink && ((currentUrl.includes(tabLink) && tabLink.length > longestMatchLength) || (isValidURL(tabLink) && isMatch(tabLink))) ) { longestMatchLength = tabLink.length; activeTab = tab; } if (!mediaQuery.matches) { tab?.addEventListener('mouseover', (e) => { setTimeout(() => { activeChannelContent(); updateOverlayPosition(); }, 50) }); } }); if (activeTab) { activeTab.classList.add('cmp-tabs__tab--active'); } activeChannelContent(); } // hightlight more and sub-channel function activeChannelContent() { function resetDefaultActive(tabsLinks) { let tab = tabsLinks[0]; let tabId = tab?.getAttribute('id'); tab?.classList.remove('cmp-tabs__tab--active'); document.getElementById(tabId + 'panel')?.classList.remove('cmp-tabs__tabpanel--active'); hideDarkOverlay(document.getElementById(tabId + 'panel')); } channelContents?.forEach((content) => { let contentLinks = content?.querySelectorAll('.cmp-tabs__tab'); contentLinks.forEach(link => { let linkUrl = !!link?.getAttribute('data-cmp-url') ? link?.getAttribute('data-cmp-url') : ''; let urlMatch = linkUrl !== '' ? currentUrl.match(linkUrl) : ''; if (!!urlMatch && !link?.classList.contains('cmp-tabs__tab--active')) { resetDefaultActive(contentLinks); link?.classList.add('cmp-tabs__tab--active'); if (link?.closest('.cmp-tabs__tabpanel')) { let linkParentId = link?.closest('.cmp-tabs__tabpanel')?.getAttribute('id'); let linkId = link?.getAttribute('id'); document.querySelector('[aria-controls="' + linkParentId + '"]')?.classList.add('cmp-tabs__tab--active'); if (!mediaQuery.matches) { document.querySelector('[aria-labelledby="' + linkId + '"]')?.classList.add('cmp-tabs__tabpanel--active'); showDarkOverlay(document.querySelector('[aria-labelledby="' + linkId + '"]')); } } } }); }); } activeChannel(); menuitems?.forEach((item) => { if (item?.classList?.contains('cmp-tabs__tabpanel--more')) { return null; } else { ['mousedown', 'keydown'].forEach((eventName) => { item?.addEventListener(eventName, function (e) { let url = e.target.getAttribute('data-megamenu-cmp-url'); let tabpanelID = e.target.getAttribute('id') + 'panel'; var tabpanelEl = document.getElementById(tabpanelID); if (eventName === 'mousedown' && e.target.tagName === 'SPAN' && e.button !== 2) { e.stopPropagation(); url && (window.location.href = url); } if (eventName === 'mousedown' && e.target.tagName === 'LI' && e.button !== 2 && !mediaQuery.matches) { e.stopPropagation(); url && (window.location.href = url); } else if (eventName === 'mousedown' && e.target.tagName === 'LI' && ctgHeader && e.button !== 2 && !tabpanelEl.firstChild.classList.contains('uxdia-c-megamenu--wrapper')) { e.stopPropagation(); url && (window.location.href = url); } else if (eventName === 'keydown' && e.key === 'Enter' && e.target.tagName === 'LI') { e.preventDefault(); url && (window.location.href = url); } else { return null; } }); }); } }); function updateOverlayPosition() { const selector = document.querySelector(".we-tabs"); if (!selector) return; const rect = selector.getBoundingClientRect(); const bottomPosition = rect.bottom; // Update the CSS variable document.documentElement.style.setProperty("--megamenu-panel-bottom", `${bottomPosition}px`); } // Run on load, resize, and scroll events window.addEventListener("DOMContentLoaded", updateOverlayPosition); window.addEventListener("resize", updateOverlayPosition); window.addEventListener("scroll", updateOverlayPosition, { passive: true }); } megamenuFunctionality(); return { megamenuFunctionality: megamenuFunctionality }; })();window.addEventListener("load",function(g){var e=document.getElementById("leavingModal"),h=document.getElementsByClassName("aarp-c-leaving-modal__heading")[0],k=document.getElementsByClassName("aarp-c-leaving-modal__button-cancel")[0];g=document.getElementsByClassName("aarp-c-leaving-modal__close")[0];var n=window!==window.parent&&document.body,p=function(a){var c=1 r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) { n[e] = r[e]; } return n; } var ssLocalPage = window.location.hostname.includes('cms-l') && window.location.href.includes('staying-sharp'); var isStayingSharp = window.location.hostname.includes('stayingsharp') || ssLocalPage; var classToHideElement = 'aarp-u-display-none'; var classToDispayElement = 'aarp-u-display__block'; // For excluding exclusive content for non sponsored users in featured list outside gallery var hideExclusiveTilesonPageLoad = function hideExclusiveTilesonPageLoad(recExclusiveTiles, parentElement, withLoadmore, recSponsorType) { var _ref, _exclusiveTiles; var displayedTilesCount = 0, allFeatureTiles, exclusiveTiles = recExclusiveTiles, allTilesCount = 0, hiddenExclusiveCount = 0; if (withLoadmore) { var _allFeatureTiles, _allFeatureTiles2; allFeatureTiles = parentElement === null || parentElement === void 0 ? void 0 : parentElement.querySelectorAll('.uxdia-c-featured-tile__section-wrapper'); allTilesCount = (_allFeatureTiles = allFeatureTiles) === null || _allFeatureTiles === void 0 ? void 0 : _allFeatureTiles.length; (_allFeatureTiles2 = allFeatureTiles) === null || _allFeatureTiles2 === void 0 ? void 0 : _allFeatureTiles2.forEach(function (eachTile) { var _window$getComputedSt; var isDisplayed = (_window$getComputedSt = window.getComputedStyle(eachTile)) === null || _window$getComputedSt === void 0 ? void 0 : _window$getComputedSt.display; isDisplayed && isDisplayed != 'none' && displayedTilesCount++; }); } var checkExclusiveEligibilty = function checkExclusiveEligibilty(recTile) { var _exclusiveSponsoredUs; var exclusiveSponsoredUsers = recTile === null || recTile === void 0 ? void 0 : recTile.getAttribute('data-user-type'); return exclusiveSponsoredUsers === null || exclusiveSponsoredUsers === void 0 ? void 0 : (_exclusiveSponsoredUs = exclusiveSponsoredUsers.split(',')) === null || _exclusiveSponsoredUs === void 0 ? void 0 : _exclusiveSponsoredUs.includes(recSponsorType); }; exclusiveTiles = (_ref = _toConsumableArray(recExclusiveTiles)) === null || _ref === void 0 ? void 0 : _ref.filter(function (eachExclusive) { var _window$getComputedSt2; var isDisplayed = (_window$getComputedSt2 = window.getComputedStyle(eachExclusive === null || eachExclusive === void 0 ? void 0 : eachExclusive.closest('.uxdia-c-featured-tile__section-wrapper'))) === null || _window$getComputedSt2 === void 0 ? void 0 : _window$getComputedSt2.display; var isExclusiveSponsorRelated = checkExclusiveEligibilty(eachExclusive); return isDisplayed && isDisplayed != 'none' && !isExclusiveSponsorRelated; }); // Hiding the exclusive tiles notrelated to the sponsor or user (_exclusiveTiles = exclusiveTiles) === null || _exclusiveTiles === void 0 ? void 0 : _exclusiveTiles.forEach(function (eachExclusive, index) { var reqExclusiveTile = eachExclusive === null || eachExclusive === void 0 ? void 0 : eachExclusive.closest('.uxdia-c-featured-tile__section-wrapper'); reqExclusiveTile === null || reqExclusiveTile === void 0 ? void 0 : reqExclusiveTile.classList.add(classToHideElement); reqExclusiveTile === null || reqExclusiveTile === void 0 ? void 0 : reqExclusiveTile.classList.remove(classToDispayElement); hiddenExclusiveCount++; if (withLoadmore) { var _allFeatureTiles3, _allFeatureTiles5, _allFeatureTiles5$cla; var isNextExclusive = (_allFeatureTiles3 = allFeatureTiles[displayedTilesCount + index]) === null || _allFeatureTiles3 === void 0 ? void 0 : _allFeatureTiles3.querySelector('.uxdia-c-featured-tile__exclusive'); while (isNextExclusive && !checkExclusiveEligibilty(isNextExclusive)) { var _allFeatureTiles4; displayedTilesCount++; hiddenExclusiveCount++; isNextExclusive = (_allFeatureTiles4 = allFeatureTiles[displayedTilesCount + index]) === null || _allFeatureTiles4 === void 0 ? void 0 : _allFeatureTiles4.querySelector('.uxdia-c-featured-tile__exclusive'); } (_allFeatureTiles5 = allFeatureTiles[displayedTilesCount + index]) === null || _allFeatureTiles5 === void 0 ? void 0 : (_allFeatureTiles5$cla = _allFeatureTiles5.classList) === null || _allFeatureTiles5$cla === void 0 ? void 0 : _allFeatureTiles5$cla.toggle(classToDispayElement); } }); return hiddenExclusiveCount; }; var hideExclusiveTilesOnLoadmore = function hideExclusiveTilesOnLoadmore(recFeaturedTile, recSponsorType) { var isExclusiveTile = recFeaturedTile === null || recFeaturedTile === void 0 ? void 0 : recFeaturedTile.querySelector('.uxdia-c-featured-tile__exclusive'); var showExclusiveForSponsor = !isExclusiveTile; if (isExclusiveTile && recSponsorType) { var _exclusiveSponsoredUs2; var exclusiveSponsoredUsers = isExclusiveTile === null || isExclusiveTile === void 0 ? void 0 : isExclusiveTile.getAttribute('data-user-type'); var isExclusiveSponsorRelated = exclusiveSponsoredUsers === null || exclusiveSponsoredUsers === void 0 ? void 0 : (_exclusiveSponsoredUs2 = exclusiveSponsoredUsers.split(',')) === null || _exclusiveSponsoredUs2 === void 0 ? void 0 : _exclusiveSponsoredUs2.includes(recSponsorType); showExclusiveForSponsor = isExclusiveSponsorRelated; } showExclusiveForSponsor && (recFeaturedTile === null || recFeaturedTile === void 0 ? void 0 : recFeaturedTile.classList.toggle(classToDispayElement)); }; var hideExclusiveTilesOutsideGallery = function hideExclusiveTilesOutsideGallery(sponsorType) { var allFeatureLists = document.querySelectorAll('.uxdia-c-featured-list'); allFeatureLists === null || allFeatureLists === void 0 ? void 0 : allFeatureLists.forEach(function (eachList) { var _eachList$parentEleme; var isGalleryChild = eachList === null || eachList === void 0 ? void 0 : eachList.closest('.uxdia-c-news-gallery__wrapper'); var loadmoreExists = eachList === null || eachList === void 0 ? void 0 : (_eachList$parentEleme = eachList.parentElement) === null || _eachList$parentEleme === void 0 ? void 0 : _eachList$parentEleme.querySelector('.uxdia-c-news-gallery__button'); if (!isGalleryChild || isGalleryChild && !loadmoreExists) { var exlsiveTiles = eachList === null || eachList === void 0 ? void 0 : eachList.querySelectorAll('.uxdia-c-featured-tile__section-wrapper .uxdia-c-featured-tile__exclusive'); exlsiveTiles.length > 0 && hideExclusiveTilesonPageLoad(exlsiveTiles, eachList, false, sponsorType); } }); if (sponsorType) { var allLockIcon = document.querySelectorAll('.uxdia-info_lock-icon'); var allBadgeIcon = document.querySelectorAll('.uxdia-c-featured-tile__moa-badge-icon'); allLockIcon === null || allLockIcon === void 0 ? void 0 : allLockIcon.forEach(function (eachLockEle) { var _eachLockEle$closest; eachLockEle === null || eachLockEle === void 0 ? void 0 : (_eachLockEle$closest = eachLockEle.closest('.uxdia-info_mb-card')) === null || _eachLockEle$closest === void 0 ? void 0 : _eachLockEle$closest.remove(); }); allBadgeIcon === null || allBadgeIcon === void 0 ? void 0 : allBadgeIcon.forEach(function (eachBadgeEle) { var _eachBadgeEle$closest; eachBadgeEle === null || eachBadgeEle === void 0 ? void 0 : (_eachBadgeEle$closest = eachBadgeEle.closest('.uxdia-c-featured-tile__moa-badge-wrapper')) === null || _eachBadgeEle$closest === void 0 ? void 0 : _eachBadgeEle$closest.remove(); }); } }; var initChannelFeatureList = function initChannelFeatureList(sponsorType) { var _document$querySelect; (_document$querySelect = document.querySelectorAll('.uxdia-u-channel-v2 .uxdia-c-news-gallery__wrapper')) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.forEach(function (galleryWrapper) { var featureList = galleryWrapper.querySelectorAll('.featuredList'); var loadMoreBtns = galleryWrapper.querySelectorAll('.uxdia-c-news-gallery__button'); if (loadMoreBtns.length > 0) { var loadMoreFeatureLists = []; featureList.forEach(function (element) { if (element.querySelector('.uxdia-c-news-gallery-button-wrapper')) { loadMoreFeatureLists.push(element); } }); loadMoreBtns.forEach(function (loadMoreBtn, index) { if (isStayingSharp) { var parentFeatureList = loadMoreFeatureLists[index]; var allExclusiveTiles = parentFeatureList === null || parentFeatureList === void 0 ? void 0 : parentFeatureList.querySelectorAll('.uxdia-c-featured-tile__section-wrapper .uxdia-c-featured-tile__exclusive'); var exclusiveTilesCount = allExclusiveTiles === null || allExclusiveTiles === void 0 ? void 0 : allExclusiveTiles.length; if (exclusiveTilesCount > 0) { var _featureListElements$; var reqExclusiveCount = hideExclusiveTilesonPageLoad(allExclusiveTiles, parentFeatureList, true, sponsorType); var featureListElements = parentFeatureList === null || parentFeatureList === void 0 ? void 0 : parentFeatureList.querySelectorAll('.uxdia-c-featured-list--tabbed'); var itemsDataset = (_featureListElements$ = featureListElements[0]) === null || _featureListElements$ === void 0 ? void 0 : _featureListElements$.dataset; itemsDataset.loadmore = +itemsDataset.loadmore + reqExclusiveCount; } } loadMoreBtn.addEventListener('click', function (ev) { var _featureListElements$2, _featureListElements$3; var parentFeatureList = loadMoreFeatureLists[index]; var featureListElements = parentFeatureList === null || parentFeatureList === void 0 ? void 0 : parentFeatureList.querySelectorAll('.uxdia-c-featured-list--tabbed'); var tiles = parentFeatureList === null || parentFeatureList === void 0 ? void 0 : parentFeatureList.querySelectorAll('.uxdia-c-featured-tile__section-wrapper'); var itemsToShow = (_featureListElements$2 = featureListElements[0]) === null || _featureListElements$2 === void 0 ? void 0 : (_featureListElements$3 = _featureListElements$2.dataset) === null || _featureListElements$3 === void 0 ? void 0 : _featureListElements$3.loadmore; if (itemsToShow) { itemsToShow = Number(itemsToShow); } for (var i = itemsToShow; i < tiles.length; i++) { hideExclusiveTilesOnLoadmore(tiles[i], sponsorType); } galleryWrapper.querySelectorAll(".uxdia-c-featured-tile-wrapper--display-ad .aarpe-ad[data-adsize='300x250']").forEach(function (ad) { ad.classList.add('border-add@mobile'); }); loadMoreBtn.classList.add(classToHideElement); }, false); }); } }); }; var initLandingPageFeatureList = function initLandingPageFeatureList(sponsorType) { var isChannel = document.querySelectorAll('.uxdia-u-channel-v2'); if (isChannel && !isChannel.length) { var _document$querySelect2; (_document$querySelect2 = document.querySelectorAll('.uxdia-c-news-gallery__wrapper')) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.forEach(function (galleryWrapper) { var tiles = galleryWrapper.querySelectorAll('.uxdia-c-featured-tile__section-wrapper'); var loadMoreBtn = galleryWrapper.querySelector('.uxdia-c-news-gallery__button'); var itemsToShow = 6; if (loadMoreBtn) { if (isStayingSharp) { var allExclusiveTiles = galleryWrapper.querySelectorAll('.uxdia-c-featured-tile__section-wrapper .uxdia-c-featured-tile__exclusive'); var exclusiveTilesCount = allExclusiveTiles === null || allExclusiveTiles === void 0 ? void 0 : allExclusiveTiles.length; if (exclusiveTilesCount > 0) { var reqExclusiveCount = hideExclusiveTilesonPageLoad(allExclusiveTiles, galleryWrapper, true, sponsorType); itemsToShow = itemsToShow + reqExclusiveCount; } } loadMoreBtn.addEventListener('click', function (ev) { var _tiles, _sixthTile; for (var index = itemsToShow; index < tiles.length && index < 2 * itemsToShow; index++) { hideExclusiveTilesOnLoadmore(tiles[index], sponsorType); } // Shifting focus from loadmore button to 6th item so that on clicking tab it will read remaining cards. var sixthTile = (_tiles = tiles[itemsToShow - 1]) === null || _tiles === void 0 ? void 0 : _tiles.querySelector('.uxdia-c-featured-tile-container-link'); if (!sixthTile) { var _tiles2; sixthTile = (_tiles2 = tiles[itemsToShow - 1]) === null || _tiles2 === void 0 ? void 0 : _tiles2.querySelector('.aarpe-ad-wrapper'); } (_sixthTile = sixthTile) === null || _sixthTile === void 0 ? void 0 : _sixthTile.focus(); galleryWrapper.querySelectorAll(".uxdia-c-featured-tile-wrapper--display-ad .aarpe-ad[data-adsize='300x250']").forEach(function (ad) { ad === null || ad === void 0 ? void 0 : ad.classList.add('border-add@mobile'); }); loadMoreBtn === null || loadMoreBtn === void 0 ? void 0 : loadMoreBtn.classList.add(classToHideElement); }, false); } }); } }; var renderFeaturedList = function renderFeaturedList(isSponsor) { // LoadMore Functionality for new variation of the channel templates initChannelFeatureList(isSponsor); // LoadMore Functionality for landing pages except the channel new variation template initLandingPageFeatureList(isSponsor); isStayingSharp && hideExclusiveTilesOutsideGallery(isSponsor); }; if (isStayingSharp) { var _AARP, _AARP$Externals; (_AARP = AARP) === null || _AARP === void 0 ? void 0 : (_AARP$Externals = _AARP.Externals) === null || _AARP$Externals === void 0 ? void 0 : _AARP$Externals.ContextHub.onLoad(function () { var _ContextHub, _ContextHub$Utils; ((_ContextHub = ContextHub) === null || _ContextHub === void 0 ? void 0 : _ContextHub.Utils) && ((_ContextHub$Utils = ContextHub.Utils) === null || _ContextHub$Utils === void 0 ? void 0 : _ContextHub$Utils.Eventing().on(ContextHub.Constants.EVENT_STORE_READY + ':ss-usertypes-jsonp', function () { var _window$getContextHub; var isSponsoredUser = (_window$getContextHub = window.getContextHubData('ss-usertypes-jsonp')) === null || _window$getContextHub === void 0 ? void 0 : _window$getContextHub.hasSponsoredSubscription; renderFeaturedList(isSponsoredUser && isSponsoredUser != 'false' ? isSponsoredUser : false); }, 'usertypes', true)); }); } else { renderFeaturedList(false); } var handleAdsNewsListTileWithNoAds = function handleAdsNewsListTileWithNoAds() { var newsListTilesWithAds = '.uxdia-c-featured-article-collection--sub-article-list .uxdia-c-featured-tile-wrapper--display-ad .aarpe-ad-wrapper'; document.querySelectorAll(newsListTilesWithAds).forEach(function (adsWrapperEl) { adsWrapperEl.closest('.uxdia-c-featured-tile__section-wrapper').classList.add('uxdia_newsListTile--ads'); }); }; AARP.readyStateLoader(function () { handleAdsNewsListTileWithNoAds(); // Games Center DOM element adjustments setGamesCentreTilesWidth(); }); function setGamesCentreTilesWidth() { var isDesktop = window.matchMedia('(min-width: 1024px)').matches; var listsWithAutoWidthTiles = document.querySelectorAll('.uxdia-c-gc-game-cards-container.uxdia-c-gc-game-cards-shared-width-tiles'); listsWithAutoWidthTiles.forEach(function (gcList) { var noOfTiles = gcList.querySelectorAll('.uxdia-c-featured-tile__section-wrapper').length; var clsToShowTilesView = ""; if (noOfTiles == 1) { clsToShowTilesView = 'uxdia-c-feature-grid-1-col'; } else if (noOfTiles == 2 || noOfTiles == 4) { clsToShowTilesView = 'uxdia-c-feature-grid-2-col'; } else { clsToShowTilesView = 'uxdia-c-feature-grid-3-col'; } gcList.classList.add(clsToShowTilesView); // Setting up the height to large tile, which means silbing contaier have 6 tiles per design. if (noOfTiles < 6) return; // Observe tiles container height and set it to large tile on change. new ResizeObserver(function (entries, observer) { var _entries$ = entries[0], gcListHeight = _entries$.contentRect.height, gcList = _entries$.target; var gcListContainer = gcList.closest('.container.responsivegrid'); var prevListContainer = gcListContainer.previousElementSibling; var nxtListContainer = gcListContainer.nextElementSibling; if (prevListContainer != null) { var prevBanner = prevListContainer.querySelector('.articleimage.image'); if (prevBanner != null) { prevBanner.style.padding = 0; if (isDesktop) { setGCMembersOnlyTileHeight(prevBanner, gcListHeight); } return; } var prevListRef = prevListContainer.querySelector('.uxdia-c-gc-game-cards-container.uxdia-c-gc-game-cards-shared-width-tiles'); if (isDesktop && prevListRef && prevListRef.querySelectorAll('.uxdia-c-featured-tile__section-wrapper').length == 1) { prevListRef.querySelector('.uxdia-c-featured-tile__container').style.height = "".concat(gcListHeight, "px"); return; } } if (nxtListContainer != null) { var nxtBanner = nxtListContainer.querySelector('.articleimage.image'); if (nxtBanner != null) { nxtBanner.style.padding = 0; if (isDesktop) { setGCMembersOnlyTileHeight(nxtBanner, gcListHeight); } return; } var nxtListRef = nxtListContainer.querySelector('.uxdia-c-gc-game-cards-container.uxdia-c-gc-game-cards-shared-width-tiles'); if (isDesktop && nxtListRef != null && nxtListRef.querySelectorAll('.uxdia-c-featured-tile__section-wrapper').length == 1) { nxtListRef.querySelector('.uxdia-c-featured-tile__container').style.height = "".concat(gcListHeight, "px"); } return; } observer.unobserve(gcList); }).observe(gcList); }); } function setGCMembersOnlyTileHeight(bannerRef, height) { var cmpImg = bannerRef.querySelector('.cmp-image'); cmpImg.style.display = "flex"; cmpImg.style.justifyContent = "center"; cmpImg.style.height = "".concat(height, "px"); cmpImg.style.overflow = "hidden"; cmpImg.style.borderRadius = "4px"; var cmpImgImg = bannerRef.querySelector('.cmp-image__image'); cmpImgImg.style.height = "".concat(height, "px"); cmpImgImg.style.width = 'auto'; } var featureTileWrappers = document.querySelectorAll(".uxdia-c-featured-tile__section-wrapper"); var buttonWrapper = '.uxdia-c-featured-tile__button-section'; var titleLink = ".uxdia-c-featured-tile__title"; var titleLinkContainer = ".uxdia-c-featured-tile__container"; // remove hover effect for the feature tile title when we hove on the button inside the feature tile featureTileWrappers === null || featureTileWrappers === void 0 ? void 0 : featureTileWrappers.forEach(function (element) { var buttonSections = element === null || element === void 0 ? void 0 : element.querySelectorAll(buttonWrapper); buttonSections === null || buttonSections === void 0 ? void 0 : buttonSections.forEach(function (buttonSection) { buttonSection === null || buttonSection === void 0 ? void 0 : buttonSection.addEventListener("mouseenter", function () { var _element$querySelecto, _element$querySelecto2; element === null || element === void 0 ? void 0 : (_element$querySelecto = element.querySelector(titleLink)) === null || _element$querySelecto === void 0 ? void 0 : (_element$querySelecto2 = _element$querySelecto.classList) === null || _element$querySelecto2 === void 0 ? void 0 : _element$querySelecto2.add('title-underline-remove'); buttonSection === null || buttonSection === void 0 ? void 0 : buttonSection.addEventListener("mouseleave", function () { var _element$querySelecto3, _element$querySelecto4; element === null || element === void 0 ? void 0 : (_element$querySelecto3 = element.querySelector(titleLink)) === null || _element$querySelecto3 === void 0 ? void 0 : (_element$querySelecto4 = _element$querySelecto3.classList) === null || _element$querySelecto4 === void 0 ? void 0 : _element$querySelecto4.remove('title-underline-remove'); }); }); }); }); // Below code is to add analytics tag to Magazine & Bulletins var magazineContentType = 'aarp publications'; var bulletinsContentType = 'aarp bulletin'; var bulletinsComponentId = 'Bulletin Cover'; var magazineComponentId = 'Publications Cover'; var bulletins = 'bulletins'; var magazine = 'magazine'; featureTileWrappers === null || featureTileWrappers === void 0 ? void 0 : featureTileWrappers.forEach(function (element) { var _ref2; var mainLinkOne = element === null || element === void 0 ? void 0 : element.querySelectorAll(titleLink); var mainLinkTwo = element === null || element === void 0 ? void 0 : element.querySelectorAll(titleLinkContainer); (_ref2 = [mainLinkOne, mainLinkTwo]) === null || _ref2 === void 0 ? void 0 : _ref2.forEach(function (list) { list === null || list === void 0 ? void 0 : list.forEach(function (el) { var _link$href$split$filt; var link = el === null || el === void 0 ? void 0 : el.querySelector('a'); // Code to extract title from href var splitTitle = (_link$href$split$filt = link === null || link === void 0 ? void 0 : link.href.split('/').filter(Boolean).pop()) !== null && _link$href$split$filt !== void 0 ? _link$href$split$filt : ''; var linkTitle = splitTitle === null || splitTitle === void 0 ? void 0 : splitTitle.split('.')[0]; var linkHref = link === null || link === void 0 ? void 0 : link.href; if (link) { /*** * Checking if link is related to bulletin or magazine * Analytics tags should be only for magazin & bulletins **/ if (linkHref.includes(bulletins)) { link.dataset.contentTitle = linkTitle.trim(); link.dataset.componentid = bulletinsComponentId; link.dataset.contentType = bulletinsContentType; } else if (linkHref.includes(magazine)) { link.dataset.contentTitle = linkTitle.trim(); link.dataset.componentid = magazineComponentId; link.dataset.contentType = magazineContentType; } } }); }); }); // Download Button & Supporting Material Placeholder in iPad and Mobile View var priSection = document.createDocumentFragment(); if (document.querySelectorAll(".uxdia-o-right-rail .uxdia-c-pri-btn-download").length) { priSupportingMaterialPlaceholder(); window.addEventListener('resize', priSupportingMaterialPlaceholder); } function priSupportingMaterialPlaceholder() { if (window.innerWidth > 1179) { if(document.querySelectorAll(".uxdia-c-pri-supporting-material").length){ priSection.appendChild(document.querySelector('.uxdia-c-pri-supporting-material')); document.querySelector('.uxdia-pri-supporting-material-placeholder-desktop > .cmp-container > .aem-Grid').appendChild(priSection); } } else if (window.innerWidth < 1179 ) { if(document.querySelectorAll(".uxdia-c-pri-supporting-material").length){ priSection.appendChild(document.querySelector('.uxdia-c-pri-supporting-material')); document.querySelector('.uxdia-pri-supporting-material-placeholder-tablet').appendChild(priSection); } priSection.appendChild(document.querySelector('.uxdia-c-pri-btn-download')); document.querySelector('.uxdia-pri-download-btn-placeholder-tablet article > .cmp-container > .aem-Grid > .articlecontentfragment:first-child').prepend(priSection); } }; // Chapters & Supporting Material component Sticky const priSticky = (element) => { const navBarElement = document.querySelector('.uxdia-o-header'); const navBarHeight = navBarElement ? navBarElement.offsetHeight + 40 : 0; let elementMainWrapper = element.closest('.uxdia-pri-sticky-container').parentNode; const elementMainWrapperTop = elementMainWrapper.getBoundingClientRect().top; // right rail element and Navbar Overlapping if (elementMainWrapperTop < navBarHeight) { element.style.position = 'fixed'; element.style.paddingBottom = '40px'; element.style.top = navBarHeight + 'px'; element.style.width = element.parentElement.offsetWidth + 'px'; } else { element.style.position = 'static'; element.style.top = 0 + 'px'; } // when full-width block encounters const fullWidthWrappers = document.querySelectorAll('.uxdia-o-full-width-ads-in-view'); elementMainWrapper = element.getBoundingClientRect(); for (let i = 0; i < fullWidthWrappers.length; i++) { const fullWidthWrapper = fullWidthWrappers[i].getBoundingClientRect(); if (elementMainWrapper.left < fullWidthWrapper.left + fullWidthWrapper.width && elementMainWrapper.left + elementMainWrapper.width > fullWidthWrapper.left && elementMainWrapper.top < fullWidthWrapper.top + fullWidthWrapper.height - 40 && elementMainWrapper.top + elementMainWrapper.height + 40 > fullWidthWrapper.top) { const top = fullWidthWrappers[i].offsetTop - elementMainWrapperTop - element.clientHeight - window.scrollY; element.style.top = top + 'px'; element.style.position = 'absolute'; break; } } }; const priStickySection = () => { // Only for desktop if (window.innerWidth >= 1180) { const elements = document.querySelectorAll('.uxdia-pri-sticky-container > .cmp-container > .aem-Grid'); elements.forEach(function (rightRailElement) { priSticky(rightRailElement); }); } else { const priTabletPosition = document.querySelector(".uxdia-pri-sticky-container > .cmp-container > .aem-Grid"); priTabletPosition.style.cssText = "position: static"; } }; if (document.querySelectorAll(".uxdia-pri-sticky-container").length) { if (window.innerWidth >= 1180) { priStickySection(); window.addEventListener('resize', priStickySection); window.addEventListener('scroll', priStickySection); } } // Expert List Detail Page See All btn const priFeatureTileSeeAllBtn = () => { document.querySelectorAll('.uxdia-pri-article-expert-details-page .uxdia-c-related-articles-wrapper').forEach(priExpertTiles => { const priExpertListCardTiles = priExpertTiles.querySelectorAll('.uxdia-pri-article-expert-details-page .uxdia-c-featured-tile__section-wrapper'); const priExpertListSeeAllBtn = priExpertTiles.querySelector('.uxdia-pri-article-expert-details-page .uxdia-c-news-gallery__button'); const priExpertListItemsToShow = 6; if (priExpertListSeeAllBtn) { priExpertListSeeAllBtn?.addEventListener('click', () => { for (let index = priExpertListItemsToShow; index < priExpertListCardTiles.length; index++) { priExpertListCardTiles[index].classList.toggle('pri-expert-detail-card-display-block'); } priExpertListSeeAllBtn?.classList.add('pri-expert-list-see-all-btn-display-none'); }, false); } }); } if (document.querySelectorAll(".uxdia-pri-article-expert-details-page").length) { priFeatureTileSeeAllBtn(); } (function(f){window.CMP=window.CMP||{};window.CMP.utils=function(){return{readData:function(c,b){c=c.dataset;var d=[];b=b.charAt(0).toUpperCase()+b.slice(1);b=["is","hook"+b];for(var a in c)if(Object.prototype.hasOwnProperty.call(c,a)){var e=c[a];0===a.indexOf("cmp")&&(a=a.slice(3),a=a.charAt(0).toLowerCase()+a.substring(1),-1===b.indexOf(a)&&(d[a]=e))}return d},setupProperties:function(c,b){var d={},a;for(a in b)if(Object.prototype.hasOwnProperty.call(b,a)){var e=b[a];d[a]=c&&null!=c[a]?e&&"function"=== typeof e.transform?e.transform(c[a]):c[a]:b[a]["default"]}return d}}}();f.dispatchEvent(new CustomEvent("core.wcm.components.commons.site.utils.loaded"))})(window.document);(function(){function D(f){function h(b){a._config=b;b.element.removeAttribute("data-cmp-is");t(b.options);n(b.element);a._active=0;a._paused=!1;a._elements.item&&(I(),u(),v(),A(),w());window.Granite&&window.Granite.author&&window.Granite.author.MessageChannel&&(window.CQ=window.CQ||{},window.CQ.CoreComponents=window.CQ.CoreComponents||{},window.CQ.CoreComponents.MESSAGE_CHANNEL=window.CQ.CoreComponents.MESSAGE_CHANNEL||new window.Granite.author.MessageChannel("cqauthor",window),window.CQ.CoreComponents.MESSAGE_CHANNEL.subscribeRequestMessage("cmp.panelcontainer", function(c){c.data&&"cmp-carousel"===c.data.type&&c.data.id===a._elements.self.dataset.cmpPanelcontainerId&&"navigate"===c.data.operation&&q(c.data.index)}))}function w(){if(k){var b=k.getDeepLinkItemIdx(a,"item","item");if(-1b||b>a._elements.item.length-1)){a._active=b;var d=a._elements.item,e=a._elements.indicator;if(d)if(Array.isArray(d))for(var g=0;gb){var l;this.buttonContainer&&this.buttonContainer.remove();this.buttonContainer=document.createElement("div");this.bulletWrapper=document.createElement("div");this.bulletWrapper.className="sharp-c-carousel__bullet-wrapper sharp-c-carousel__bullet-wrapper@mobile sharp-c-carousel__bullet-wrapper@tablet"; this.bulletContainer=document.createElement("ul");this.nextButton=document.createElement("a");this.prevButton=document.createElement("a");this.bulletContainer.className="sharp-c-carousel__bullets-container";this.buttonContainer.className="sharp-c-carousel__buttons sharp-c-carousel__buttons@mobile sharp-c-carousel__buttons@tablet";this.nextButton.className="sharp-c-carousel__navButton sharp-c-carousel__next sharp-u-carousel-box-shadow sharp-u-background-color--utility-white";this.nextButton.addEventListener("click", function(e){a.nextButton.getAttribute("disabled")||a.handleSlideChange("next",e,b)});this.prevButton.className="sharp-c-carousel__navButton sharp-c-carousel__prev sharp-u-carousel-box-shadow sharp-u-background-color--utility-white";this.prevButton.addEventListener("click",function(e){a.prevButton.getAttribute("disabled")||a.handleSlideChange("prev",e,b)});this.bulletLength=Math.ceil(this.contentTilesLength/b);for(var f=0;fwindow.innerWidth&&5<=f&&g.classList.add("sharp-c-carousel__bullets--invisible");this.bulletContainer.appendChild(g)}this.buttonContainer.appendChild(this.prevButton);this.prevButton.setAttribute("disabled",!0);this.bulletWrapper.appendChild(this.bulletContainer);this.buttonContainer.appendChild(this.bulletWrapper); this.buttonContainer.appendChild(this.nextButton);null===(l=this.carouselContainer)||void 0===l?void 0:l.appendChild(this.buttonContainer)}this.windowResize()}},{key:"bindEvents",value:function(){var a=this;window.addEventListener("resize",function(){var b=window.innerWidth;768>a.windowSize&&768>b||768<=a.windowSize&&768<=b?a.windowResize():a.init();a.windowSize=b});this.isTouchDevice()&&(this.carouselWrapper.addEventListener("touchstart",function(b){a.touchstartX=b.changedTouches[0].screenX},!1), this.carouselWrapper.addEventListener("touchend",function(b){a.touchendX=b.changedTouches[0].screenX;null==b.target.closest(".sharp-c-content-tile__menu")&&null==b.target.closest(".sharp-c-content-tile__menu-list")&&a.handleGesture()},!1))}},{key:"windowResize",value:function(){var a,b=null===(a=this.carouselContainer)||void 0===a?void 0:a.querySelector(".sharp-c-carousel__bullets--active");if(this.carouselWrapper){this.carouselWrapper.style.transition="none";this.carouselWrapper.style.marginLeft= 0;this.carouselWrapper.style.width="auto";this.contentTiles[0].style.maxWidth="initial";a=window.getComputedStyle(this.contentTiles[0]);this.contentTilesWidth=this.contentTiles[0].offsetWidth;this.contentTilesWidthWithMargin=this.contentTiles[0].offsetWidth+parseInt(a.getPropertyValue("margin-left"))+parseInt(a.getPropertyValue("margin-right"));for(a=0;awindow.innerWidth){var n;a=this.touchstartX&&this.prevButton.click()}}]);return d}(),k=function(d){var a=null===d||void 0===d?void 0:d.querySelectorAll(".challengeRecommendation, .sharp-c-content-tile__container"),b=0,l=function(){if(0!=(null===a||void 0===a?void 0:a.length)){null===a||void 0===a?void 0:a.forEach(function(q){q.classList.remove("carousel__item-prev");q.classList.remove("carousel__item-prev-prev");q.classList.remove("carousel__item-next");q.classList.remove("carousel__item-next-next"); q.classList.remove("carousel__item--active")});var e=b-1,h=b-2,n=b+1,p=b+2;switch(b){case (null===a||void 0===a?NaN:a.length)-2:p=0;break;case (null===a||void 0===a?NaN:a.length)-1:n=0;p=1;break;case 1:h=(null===a||void 0===a?NaN:a.length)-1;break;case 0:e=(null===a||void 0===a?NaN:a.length)-1,h=(null===a||void 0===a?NaN:a.length)-2}null!==a&&void 0!==a&&a.length&&a[b].classList.add("carousel__item--active");1<(null===a||void 0===a?void 0:a.length)&&a[n].classList.add("carousel__item-next");2<(null=== a||void 0===a?void 0:a.length)&&a[p].classList.add("carousel__item-next-next");3<(null===a||void 0===a?void 0:a.length)&&a[e].classList.add("carousel__item-prev");4<(null===a||void 0===a?void 0:a.length)&&a[h].classList.add("carousel__item-prev-prev")}},f=function(){b==(null===a||void 0===a?NaN:a.length)-1?b=0:b++;l()},g=function(){0==b?b=(null===a||void 0===a?NaN:a.length)-1:b--;l()};l();(function(){var e=document.createElement("div");e.classList.add("carousel__button-prev");var h=document.createElement("div"); h.classList.add("carousel__button-next");e.addEventListener("click",g);h.addEventListener("click",f);null===d||void 0===d?void 0:d.appendChild(e);null===d||void 0===d?void 0:d.appendChild(h);1===(null===a||void 0===a?void 0:a.length)&&(e.style.visibility="hidden",h.style.visibility="hidden")})();(function(){null===d||void 0===d?void 0:d.addEventListener("click",function(e){var h=e.path?e.path.filter(function(n){return n.classList&&n.classList.contains("carousel__item")})[0]:e.target;if(h&&h.classList.contains("carousel__item"))switch(["carousel__item-next-next", "carousel__item-next","carousel__item-prev","carousel__item-prev-prev"].filter(function(n){return h.classList.contains(n)})[0]){case "carousel__item-next-next":case "carousel__item-next":f();break;case "carousel__item-prev-prev":case "carousel__item-prev":g()}})})()},m=function(d){var a=function(f,g){var e=0;null===f||void 0===f?void 0:f.forEach(function(h){h.classList.contains("challengeRecommendation")&&h.classList.add("carousel__item");h.style.removeProperty("height");e=Math.max(h.offsetHeight, e);h.classList.contains("sharp-c-content-tile__container")&&h.classList.add("carousel__item")});null===f||void 0===f?void 0:f.forEach(function(h){h.style.height="".concat(e,"px")});g&&(g.style.minHeight="".concat(e+30,"px"))},b=d.querySelector(".sharp-js-carousel__wrapper-view-horizontal"),l=null===b||void 0===b?void 0:b.querySelectorAll(".challengeRecommendation, .sharp-c-content-tile__container");a(l,b);window.addEventListener("resize",function(){return a(l,b)});k(b,b);setTimeout(function(){a(l, b)},100)};document.querySelectorAll(".sharp-c-carousel").forEach(function(d){m(d);new c(d)});return{createHorizontalView:m,createCarousel:c}}();(function(){var f=document.querySelector(".uxdia-o-header"),l=f?f.offsetHeight+40:0;f=document.querySelectorAll(".sharp-c-social-icon-share__icon");var m=document.querySelector('link[rel\x3d"canonical"]'),k="";m&&(k=m.getAttribute("href"));null===f||void 0===f?void 0:f.forEach(function(c){if(c.hasAttribute("href")){var a=c.getAttribute("href");a=a.replace("*fullURL*",k);c.setAttribute("href",a)}c.hasAttribute("data-fullUrl")&&c.setAttribute("data-fullUrl",k);null===c||void 0===c?void 0:c.addEventListener("mouseover", function(){c.focus()});null===c||void 0===c?void 0:c.addEventListener("mouseout",function(){c.blur()});c.addEventListener("click",function(b){var d=b.target;if(d.hasAttribute("data-settings")||d.hasAttribute("data-windowName")||d.hasAttribute("data-url")){b.preventDefault();b=d.getAttribute("data-url");var e=d.getAttribute("data-fullUrl"),g=d.getAttribute("data-windowName");d=d.getAttribute("data-settings");window.open(b+e,g,d+",left\x3d"+(screen.width-700)/2+",top\x3d"+(screen.height-300)/2)}},!1)}); window.addEventListener("scroll",function(){var c;"undefined"!=typeof window.onorientationchange&&(c=0==window.orientation?"portrait":"landscape");(1025<=window.innerWidth||1024==window.innerWidth&&"portrait"==c)&&document.querySelectorAll(".uxdia-c-social-icon-share--uxdia-body-theme.uxdia-c-social-icon-share--sticky").forEach(function(a){var b=a.getBoundingClientRect(),d=a.offsetHeight,e=a.offsetWidth;if(b.top>=-d&&b.left>=-e&&b.right<=(window.innerWidth||document.documentElement.clientWidth)+e&& b.bottom<=(window.innerHeight||document.documentElement.clientHeight)+d){b=a.closest(".uxdia-c-social-share__container").parentNode;d=b.getBoundingClientRect().top;dh.left&&b.toph.top){a.style.top=e[g].offsetTop-d-a.clientHeight-window.scrollY+"px";a.style.position="absolute";break}}}})})})();!function(){var t,e=AARP.store.getState().currentEnvironment.servicesEndpoint,i=AARP.store.getState().cookie.LoyaltyBackend,n=document.querySelector(".aarp-u-loyalty-plus-switch"),a="true"===(null==n||null===(t=n.dataset)||void 0===t?void 0:t.isLoyaltyPlus),o={ACTIVITY_LIST:"".concat(e,"applications/loyalty-catalog/activity/listV3"),ACTIVITY_WITH_ID:"".concat(e,"applications/loyalty-catalog/activity/"),LIMIT:"".concat(e,"applications/loyalty-catalog/activity/limit")},r=AARP.store.getState().user.rewardsUser,d=function(t){return new CustomEvent("loyalty-error",{detail:t})},l=function(t){var e=t.url,n=t.data,o=t.bearer,r=t.header;return new Promise((function(t,d){var l,s,c,u,v=new XMLHttpRequest,y="GET";n&&(y="POST"),v.open(y,e,!0),n&&v.setRequestHeader("Content-Type","application/json;charset=UTF-8"),o&&v.setRequestHeader("Authorization","Bearer ".concat(o)),r&&Object.keys(r).forEach((function(t){v.setRequestHeader(t,JSON.stringify(r[t]))})),null!==(l=AARP)&&void 0!==l&&null!==(s=l.store)&&void 0!==s&&s.getState().cookie["x-aarp-system-future"]&&(v.withCredentials=!0);var w=null===(c=AARP)||void 0===c||null===(u=c.store)||void 0===u?void 0:u.getState().cookie.TimeTravelCookie;w&&(w=new Date(w).toISOString(),v.setRequestHeader("X-Time-Travel",w)),(i||a)&&v.setRequestHeader("X-Loyalty-Backend","LoyaltyPlus"),v.onload=function(){if(this.status>=200&&this.status<400){var e=JSON.parse(this.response);return t(e)}console.warn("Error on XHR: ".concat(this.status," ").concat(this.response)),d()},v.onerror=function(){console.warn("Error trying to reach ".concat(e)),d()},n?v.send(JSON.stringify(n)):v.send()}))};window.addEventListener("loyalty-get-activity",(function(t){var e=t.detail;l({url:o.ACTIVITY_LIST}).then((function(t){t.length||window.dispatchEvent(d({error:"get-activity-empty"}));var i=t.filter((function(t){return t.identifier===e}))[0];return u(i)})).catch((function(){window.dispatchEvent(d({error:"get-activity-failed"}))}))}));var s=[];window.addEventListener("loyalty-get-activity-with-id",(function(t){var e=t.detail;s.includes(e)||(s.push(e),l({url:o.ACTIVITY_WITH_ID+e}).then((function(t){u(t),s.push(e)})).catch((function(){s.push(e),window.dispatchEvent(d({error:"get-activity-failed"}))})))})),window.addEventListener("empty-loyalty-get-activity",(function(){s=[]}));var c=[],u=function(t){if(!c.includes(t.identifier))if(t.active){var e=(new Date).setUTCHours(0,0,0,0);if(new Date(t.endDate).setUTCHours(0,0,0,0)new Date)return window.dispatchEvent(d({error:"invalid-activity-date",activityID:t})),!1;if(null===t.startDate||null===t.endDate)return window.dispatchEvent(d({error:"invalid-activity-date",activityID:t})),!1;c.push(t.identifier),window.dispatchEvent(new CustomEvent("loyalty-get-activity-response",{detail:t}))}else window.dispatchEvent(d({error:"invalid-activity-id",activityID:t}))};window.addEventListener("loyalty-deposit-points",(function(t){var e,i,n=t.detail,a=n=function(t){if(!t.activityIdentifier){var e=document.querySelector("[data-badge-target]");e&&(t.activityIdentifier=e.getAttribute("data-activity-id"))}return t}(n),o=a.activityIdentifier,r=a.hide_notification,l=!0;"d57cdff9-014c-455a-9485-832e3377a0c3"!==o&&"510f43ea-494b-4e3a-8594-632ee80cb798"!==o||(l=!1);var s,c,u=function(t,e){!t||t.length<36||window.AARP.translationLayerService.submitActivity(t,e).then((function(e){v(e,t,r)})).catch((function(e){var i;429===(null===(i=e.error)||void 0===i?void 0:i.code)?v({},t,r):window.dispatchEvent(d({error:"loyaty-deposit-failed",activityIdentifier:t}))}))},v=function(t,e,i){var n,a,o,r,l;if(localStorage.setItem("rewards_submited",!0),t&&(t.activityIdentifier=e),429===(null==t||null===(n=t.error)||void 0===n?void 0:n.code)&&window.dispatchEvent(d({error:"loyaty-deposit-limited",errorDetail:t.error})),"error.business.F.YouAreUnableToParticipateInThisProgramContactCustCareIfYouHaveAnyFurtherQuestions"===(null==t||null===(a=t.error)||void 0===a?void 0:a.code))null===(r=AARP)||void 0===r||null===(l=r.TranslationLayerAnalytics)||void 0===l||l.setRewardType("F");else if("error.business.I.YouAreUnableToParticipateInThisProgramContactCustCareIfYouHaveAnyFurtherQuestions"===(null==t||null===(o=t.error)||void 0===o?void 0:o.code)){var s,c;null===(s=AARP)||void 0===s||null===(c=s.TranslationLayerAnalytics)||void 0===c||c.setRewardType("I")}if(i)return window.dispatchEvent(new CustomEvent("loyalty-deposit-response-no-notification",{detail:t})),!0;window.dispatchEvent(new CustomEvent("loyalty-deposit-response",{detail:t}))};null!==(e=AARP)&&void 0!==e&&null!==(i=e.translationLayerService)&&void 0!==i&&i.access_token?u(o,l):null===(s=AARP)||void 0===s||null===(c=s.translationLayerService)||void 0===c||c.init().then((function(){u(o,l)}))})),window.addEventListener("loyalty-get-activity-limited",(function(t){var e=t.detail,i=e.activityList,n=e.userIdentifier,a=e.access_token;l({url:o.LIMIT+"/"+n,data:{activityList:i},bearer:a}).then((function(t){var e,i;null===(e=AARP)||void 0===e||null===(i=e.TranslationLayerAnalytics)||void 0===i||i.setTodaysPoints(t.userDailyPointsLeft),window.dispatchEvent(new CustomEvent("loyalty-limited-response",{detail:t}))})).catch((function(){window.dispatchEvent(d({error:"get-activity-limited-failed",activityIdentifier:e.activityIdentifier}))}))})),r&&window.addEventListener("loyalty-get-current-balance",(function(t){var e=t.detail,i=null==e?void 0:e.forceCall;window.fetchingPoints=!0,window.AARP.translationLayerService.getCurrentBalance(i).then((function(t){var e,i=t.currentBalance;AARP.store.dispatch({type:"WRITE_COOKIE",payload:{key:"aarp_rewards_balance",value:"".concat(i),maxAge:"86400",domain:"aarp.org"}}),window.dispatchEvent(new CustomEvent("loyalty-points-updated",{detail:i})),window.dispatchEvent(new CustomEvent("loyalty-points-resolved")),window.fetchingPoints=!1,null!==(e=AARP.MetaInfo)&&void 0!==e&&e.rewardsData&&(AARP.MetaInfo.rewardsData.totalpoints=i||null)})).catch((function(){window.dispatchEvent(d({error:"get-points-failed"})),window.dispatchEvent(new CustomEvent("loyalty-points-resolved")),window.fetchingPoints=!1}))})),window.addEventListener("loyalty-error",(function(t){var e=t.detail;console.error("error on activity load: ",e)})),window.addEventListener("ExternalPrerollEnd",(function(){document.getElementById("framingModal").classList.add("earn-activity-badge__framing-mobile-hidden")})),window.addEventListener("loyalty-points-updated",(function(t){var e=parseInt(t.detail),i=document.querySelector(".aarp-js-loyalty-points-updated"),n=e.toLocaleString("en"),a="AARP Rewards ".concat(n," POINTS");e&&i&&(window.dispatchEvent(new CustomEvent("update-header-points",{detail:e})),i.innerText=a)}))}();var AARP=AARP||{},loadCheckLoyaltyPoints=(AARP.checkLoyaltyPoints=function(){var b=AARP.store.getState().auth.authToken,c=AARP.store.getState().cookie.aarp_rewards_balance,d=AARP.store.getState().cookie.fedid,e="Y"===(null==(a=AARP.store.getState().cookie.at)?void 0:a.rs)||null,a=d&&b&&e;(!c&&a||"null"===c&&a)&&window.dispatchEvent(new CustomEvent("loyalty-get-current-balance",{detail:{userIdentifier:d,access_token:b}}));AARP.store.subscribe(function(){var f;e="Y"===(null==(f=AARP.store.getState().cookie.at)? void 0:f.rs)||null;b=AARP.store.getState().auth.authToken})},function(){AARP.store.getState().cookie.hasOwnProperty("at")&&AARP.checkLoyaltyPoints()}),pointsLoaded=!1;AARP.readyStateLoader(function(){(pointsLoaded||AARP.store.getState().cookie.aarp_rewards_balance)&&"null"!==AARP.store.getState().cookie.aarp_rewards_balance||(pointsLoaded=!0,loadCheckLoyaltyPoints())},!1);(AARP=AARP||{}).dailyLoginBonus=function(){var e=JSON.parse(localStorage.getItem("firstLoginTS")),c=(c=new Date).setHours(24,0,0,0),h=AARP.store.getState().cookie.at,f=!1,g=AARP.store.getState().auth.authToken,d=(AARP.store.subscribe(function(){g=AARP.store.getState().auth.authToken}),"Y"===(null==(d=AARP.store.getState().cookie.at)?void 0:d.rs));h&&g&&d&&(!e||eb&&8<=a&&20>=a){var k;b=(null===(k=c.innerText)||void 0===k?void 0:k.trim())||"Cobrowse";c.innerHTML="\x3ca href\x3d'javascript:GLANCE.Cobrowse.Visitor.showTerms();'\x3e".concat(b,"\x3c/a\x3e")}else c.remove()}else c&&c.remove()};null===(e=AARP)||void 0===e?void 0:null===(f=e.Externals)||void 0===f?void 0:f.attachPageJsCallback(l);null===(g=AARP)||void 0===g?void 0:null===(h=g.Externals)||void 0===h?void 0:h.ContextHub.onLoad(function(){var b,a,c,d;null===(b=window)||void 0===b?void 0: null===(a=b.ContextHub)||void 0===a?void 0:null===(c=a.Utils)||void 0===c?void 0:null===(d=c.Eventing())||void 0===d?void 0:d.on(window.ContextHub.Constants.EVENT_TEASER_LOADED,l)})})();AARP.Externals._loaded.push("page-js");AARP.Externals._pageJsCallbacks.map(function(a){a()});AARP.Externals.initialize();AARP.searchBox=AARP.searchBox||{};AARP.searchBox.actions=AARP.searchBox.actions||{};AARP.searchBox.actions.getRepresentatives=function(b){console.log(b)};"use strict"; (function(){if(document.getElementsByClassName("aarp-c-microform--newsletter")[0]){var b=AARP.searchBox.newsLetterArray[1],a=null,c=null,f=function(d){var e=!1,g=null;if(0c.indexOf(g.rankID)){e=!1;break}}else g=d[0];!0===e&&(g=d[0]);return[g,e]};AARP.readyStateLoader(function(){b&&(c=AARP.store.getState().cookie&&AARP.store.getState().cookie.at?AARP.store.getState().cookie.at.n:[],a=f(b),AARP.searchBox.newsLetterLink=a[0].rankLink,AARP.token.store.newsLetterTitle= {value:""},AARP.token.store.newsLetterPromoText={value:""},AARP.token.store.description={value:""},AARP.token.store.newsLetterTitle.value=a[0].rankTitle,AARP.token.store.newsLetterPromoText.value=a[0].newsLetterPromoText,AARP.token.store.description.value=a[0].rankDescription,document.querySelectorAll(".aarp-c-microform--newsletter").forEach(function(d){AARP.store.getState().cookie.at?d.classList.remove("aarp-c-microform--newsletter-anonymous"):d.classList.add("aarp-c-microform--newsletter-anonymous"); if(a[1]){var e='\x3cp class\x3d"aarp-c-microform--newsletter-subscribed"\x3e'.concat(AARP.searchBox.newsLetterEndMessage,"\x3c/p\x3e");if(document.querySelector(".aarp-u-homepage-newsletter-promo-text"))d.innerHTML=e;else{if(d=document.querySelector(".uxdia-c-hp-newsletter__text"))d.innerHTML=e;if(e=document.querySelector(".uxdia-c-hp-newsletter__body-text"))e.innerHTML="";if(e=document.querySelector(".aarp-c-microform--newsletter .aarp-c-microform__subscribe"))e.innerHTML=AARP.searchBox.newsLetterAllSubscribed.manageLinkLabel; AARP.searchBox.newsLetterLink=AARP.searchBox.newsLetterAllSubscribed.manageLink}}}),a[1]&&document.querySelectorAll(".aarp-u-homepage-newsletter-promo-text").forEach(function(d){d.innerHTML=""}),window.dispatchEvent(new CustomEvent("TOKEN_REPLACE",{detail:".aarp-c-microform--newsletter"})))})}})();AARP.searchBox.actions.newsletterSubscribe=function(b){var a=AARP.searchBox.newsLetterLink;b.newTab?window.open(a,"_blank").focus():window.location.href=a};"use strict"; AARP.searchBox.actions.helpSearch=function(b,a){a.preventDefault();a=b.trackingId.substring(1);a=b.url+"?q\x3d"+b.inputEl.value+"\x26"+a;b.newTab?window.open(a,"_blank").focus():window.location.href=a};"use strict"; AARP.searchBox.actions.anmMapSearch=function(b,a){a.preventDefault();document.querySelector(".aarp-c-microform--anm-map .aarp-c-microform--submit-button");a=b.url;document.querySelector(".change-text p").innerText="Find AARP in "+b.inputEl.value;b.newTab?window.open(a,"_blank").focus():window.location.href=a};"use strict";var _document$querySelect;AARP=AARP||{}; var selectStateDropdown=document.querySelector(".uxdia-c-state-page-selector-form .uxdia-u-form-select"),stateArray="Alabama;Alaska;Arizona;Arkansas;California;Colorado;Connecticut;Delaware;District of Columbia;Florida;Georgia;Hawaii;Idaho;Illinois;Indiana;Iowa;Kansas;Kentucky;Louisiana;Maine;Maryland;Massachusetts;Michigan;Minnesota;Mississippi;Missouri;Montana;Nebraska;Nevada;New Hampshire;New Jersey;New Mexico;New York;North Carolina;North Dakota;Ohio;Oklahoma;Oregon;Pennsylvania;Puerto Rico;Rhode Island;South Carolina;South Dakota;Tennesse;Texas;Utah;Vermont;Virginia;Virgin Islands;Washington;West Virginia;Wisconsin;Wyoming".split(";"),pageNamesArray= "https://states.aarp.org/alabama/ https://states.aarp.org/alaska/ https://states.aarp.org/arizona/ https://states.aarp.org/arkansas/ https://states.aarp.org/california/ https://states.aarp.org/colorado/ https://states.aarp.org/connecticut/ https://states.aarp.org/delaware/ https://states.aarp.org/washington-dc/ https://states.aarp.org/florida/ https://states.aarp.org/georgia/ https://states.aarp.org/hawaii/ https://states.aarp.org/idaho/ https://states.aarp.org/illinois/ https://states.aarp.org/indiana/ https://states.aarp.org/iowa/ https://states.aarp.org/kansas/ https://states.aarp.org/kentucky/ https://states.aarp.org/louisiana/ https://states.aarp.org/maine/ https://states.aarp.org/maryland/ https://states.aarp.org/massachusetts/ https://states.aarp.org/michigan/ https://states.aarp.org/minnesota/ https://states.aarp.org/mississippi/ https://states.aarp.org/missouri/ https://states.aarp.org/montana/ https://states.aarp.org/nebraska/ https://states.aarp.org/nevada/ https://states.aarp.org/new-hampshire/ https://states.aarp.org/new-jersey/ https://states.aarp.org/new-mexico https://states.aarp.org/new-york/ https://states.aarp.org/north-carolina/ https://states.aarp.org/north-dakota/ https://states.aarp.org/ohio/ https://states.aarp.org/oklahoma/ https://states.aarp.org/oregon/ https://states.aarp.org/pennsylvania/ https://states.aarp.org/puerto-rico/ https://states.aarp.org/rhode-island/ https://states.aarp.org/south-carolina/ https://states.aarp.org/south-dakota/ https://states.aarp.org/tennessee/ https://states.aarp.org/texas/ https://states.aarp.org/utah/ https://states.aarp.org/vermont/ https://states.aarp.org/virginia/ https://states.aarp.org/virgin-islands/ https://states.aarp.org/washington/ https://states.aarp.org/west-virginia/ https://states.aarp.org/wisconsin/ https://states.aarp.org/wyoming/".split(" "), spanishStateArray="Alabama;Alaska;Arizona;Arkansas;California;California (Los Angeles);Carolina del Norte;Carolina del Sur;Colorado;Connecticut;Dakota del Norte;Dakota del Sur;Delaware;Distrito de Columbia;Florida;Florida (Miami);Georgia;Haw\u00e1i;Idaho;Illinois;Indiana;Iowa;Islas Virgenes;Kansas;Kentucky;Luisiana;Maine;Maryland;Massachusettes;Michigan;Minnesota;Misispi;Misuri;Montana;Nebraska;Nevada;Nueva Jersey;Nueva York;Nueva York (Ciudad de Nueva York);Nueva Hampshire;Ohio;Oklahoma;Oreg\u00f3n;Pensilvania;Puerto Rico;Rhode Island;Tennessee;Texas;Texas (Houston);Utah;Vermont;Virginia;Virginia Occidental;Washington;Wisconsin;Wyoming".split(";"), spanishPageNamesArray="https://states.aarp.org/alabama/section/espanol/ https://states.aarp.org/alaska/section/espanol/ https://states.aarp.org/arizona/section/espanol/ https://states.aarp.org/arkansas/section/espanol/ https://states.aarp.org/california/section/espanol/ https://local.aarp.org/los-angeles-ca/happenings/espanol/ https://states.aarp.org/north-carolina/section/espanol/ https://states.aarp.org/south-carolina/section/espanol/ https://states.aarp.org/colorado/section/espanol/ https://states.aarp.org/connecticut/section/espanol/ https://states.aarp.org/north-dakota/section/espanol/ https://states.aarp.org/south-dakota/section/espanol/ https://states.aarp.org/delaware/section/espanol/ https://states.aarp.org/washington-dc/section/espanol/ https://states.aarp.org/florida/section/espanol/ https://local.aarp.org/miami-fl/happenings/espanol/ https://states.aarp.org/georgia/section/espanol/ https://states.aarp.org/hawaii/section/espanol/ https://states.aarp.org/idaho/section/espanol/ https://states.aarp.org/illinois/section/espanol/ https://states.aarp.org/indiana/section/espanol/ https://states.aarp.org/iowa/section/espanol/ https://states.aarp.org/virgin-islands/section/espanol/ https://states.aarp.org/kansas/section/espanol/ https://states.aarp.org/kentucky/section/espanol/ https://states.aarp.org/louisiana/section/espanol/ https://states.aarp.org/maine/section/espanol/ https://states.aarp.org/maryland/section/espanol/ https://states.aarp.org/massachusetts/section/espanol/ https://states.aarp.org/michigan/section/espanol/ https://states.aarp.org/minnesota/section/espanol/ https://states.aarp.org/mississippi/section/espanol/ https://states.aarp.org/missouri/section/espanol/ https://states.aarp.org/montana/section/espanol/ https://states.aarp.org/nebraska/section/espanol/ https://states.aarp.org/nevada/section/espanol/ https://states.aarp.org/new-jersey/section/espanol/ https://states.aarp.org/new-york/section/espanol/ https://local.aarp.org/new-york-ny/happenings/espanol/ https://states.aarp.org/new-hampshire/section/espanol/ https://states.aarp.org/ohio/section/espanol/ https://states.aarp.org/oklahoma/section/espanol/ https://states.aarp.org/oregon/section/espanol/ https://states.aarp.org/pennsylvania/section/espanol/ https://states.aarp.org/puerto-rico/ https://states.aarp.org/rhode-island/section/espanol/ https://states.aarp.org/tennessee/section/espanol/ https://states.aarp.org/texas/section/espanol/ https://local.aarp.org/houston-tx/happenings/espanol/ https://states.aarp.org/utah/section/espanol/ https://states.aarp.org/vermont/section/espanol/ https://states.aarp.org/virginia/section/espanol/ https://states.aarp.org/west-virginia/section/espanol/ https://states.aarp.org/washington/section/espanol/ https://states.aarp.org/wisconsin/section/espanol/ https://states.aarp.org/wyoming/section/espanol/".split(" "), stateDropDownType=null===(_document$querySelect=document.querySelector(".aarp-c-microform--state-selector-dropdown .uxdia-u-form-select__wrapper select"))||void 0===_document$querySelect?void 0:_document$querySelect.getAttribute("id"),language="en";stateDropDownType&&"state_page_selector_ES_dropdown"===stateDropDownType&&(language="es",stateArray=spanishStateArray); var setLocation=function(b){if(""!=b){for(var a=0;a